Webhook quickstart

Learn to use example code to set up webhooks for payment notifications
Applies to:Developers

This guide covers setting up a basic flow to receive webhook notifications from the API using a server. The result is a server running on Express.js that listens for incoming ApprovedPayment events and queries the API for more information about each transaction.

Dependencies

Before you begin, make sure you have the following installed on your machine:

Set up the server

Run these commands in your terminal to configure the webhook example server on your local machine:

1

Create a new project

Create a new directory for your project and navigate into it:

$mkdir webhook-example
>cd webhook-example
>npm init -y
2

Install the dependencies

Install the express for the server:

$npm install express
3

Create the server file

Create a new file named server.js in your project directory:

$touch server.js
4

Write the server code

The interactive walkthrough displays code examples alongside step-by-step explanations.

Loading walkthrough content

Loading walkthrough...

Loading walkthrough...

/// Import dependencies

Import the required package to create an Express server.

1// server.js
2import express from 'express';

/// Initialize Express app

Create an Express application and configure it to parse JSON request bodies from incoming webhooks using Express’s built-in JSON parser.

-5
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());

/// Define API credentials

Set your Payabli API key and environment. Replace YOUR_API_KEY with your actual API key from your Payabli account. Set API_BASE_URL to the sandbox environment’s base URL.

-8
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());
6
7const API_KEY = 'YOUR_API_KEY';
8const API_BASE_URL = 'https://api-sandbox.payabli.com/api';

/// Create webhook endpoint

Define a POST /webhook endpoint to receive webhook notifications from Payabli. The endpoint must return a success response to Payabli’s API.

-14
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());
6
7const API_KEY = 'YOUR_API_KEY';
8const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
9
10app.post('/webhook', async (req, res) => {
11 console.log('Webhook received:', JSON.stringify(req.body, null, 2));
12
13 res.status(200).send('Webhook received');
14});

/// Extract event details

Parse the webhook payload to extract the event type and transaction ID. These values identify what event occurred and which transaction triggered the event.

-13
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());
6
7const API_KEY = 'YOUR_API_KEY';
8const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
9
10app.post('/webhook', async (req, res) => {
11 console.log('Webhook received:', JSON.stringify(req.body, null, 2));
12 const eventType = req.body.Event;
13 const transactionId = req.body.transId;
14
15 res.status(200).send('Webhook received');
16});

/// Query API for transaction details

Use the transaction ID to query the Payabli API for the transaction’s details. Set the requestToken header to your API key.

-28
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());
6
7const API_KEY = 'YOUR_API_KEY';
8const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
9
10app.post('/webhook', async (req, res) => {
11 console.log('Webhook received:', JSON.stringify(req.body, null, 2));
12 const eventType = req.body.Event;
13 const transactionId = req.body.transId;
14
15 if (transactionId && eventType === 'ApprovedPayment') {
16 try {
17 const response = await fetch(`${API_BASE_URL}/MoneyIn/details/${transactionId}`, {
18 headers: {
19 'requestToken': API_KEY
20 }
21 });
22 const data = await response.json();
23 console.log('Transaction details:', data);
24 } catch (error) {
25 console.error('Error fetching transaction:', error.message);
26 }
27 }
28
29 res.status(200).send('Webhook received');
30});

/// Configure the server

Configure the server to listen on port 3000.

-35
1// server.js
2import express from 'express';
3
4const app = express();
5app.use(express.json());
6
7const API_KEY = 'YOUR_API_KEY';
8const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
9
10app.post('/webhook', async (req, res) => {
11 console.log('Webhook received:', JSON.stringify(req.body, null, 2));
12 const eventType = req.body.Event;
13 const transactionId = req.body.transId;
14
15 if (transactionId && eventType === 'ApprovedPayment') {
16 try {
17 const response = await fetch(`${API_BASE_URL}/MoneyIn/details/${transactionId}`, {
18 headers: {
19 'requestToken': API_KEY
20 }
21 });
22 const data = await response.json();
23 console.log('Transaction details:', data);
24 } catch (error) {
25 console.error('Error fetching transaction:', error.message);
26 }
27 }
28
29 res.status(200).send('Webhook received');
30});
31
32const PORT = 3000;
33app.listen(PORT, () => {
34 console.log(`Webhook server listening on port ${PORT}`);
35});
5

Run the server

Run the server with the following command:

$node server.js

The server should run locally on port 3000. You can stop the server and move on to the next step.

Expose the server

To receive webhooks from the API, your server must be publicly accessible from the internet. You can expose your local server to the public internet using a tunneling tool. There are many tunneling tools available for testing environments. This section covers exposing your local server using two common tunneling tools:

Choosing a tool

You can use either localhost.run or ngrok in this guide to expose your server.

localhost.run doesn’t require an account to set up and is faster to get started with. localhost.run requires the command line utility SSH to be installed on your machine. Most Unix-based operating systems (Linux, macOS) have SSH pre-installed.

ngrok requires users to create a free account and install the ngrok software. ngrok has more features for managing tunnels and inspecting traffic. If you want to inspect webhook traffic thoroughly, we recommend using ngrok.

Select the tool you want to use and follow the instructions to publicly expose your local server:

1

Start your server

Make sure your server is running locally on port 3000:

$node server.js
2

Expose your server

Use SSH to create a tunnel to your local server:

$ssh -R 80:localhost:3000 localhost.run

After running the command, a URL appears like https://6128asd171237.lhr.life. This URL forwards requests to your local server. Save this URL for the next step.

1

Create a free ngrok account

Go to ngrok.com and sign up for a free account. If you already have ngrok set up, skip to step 5.

2

Install ngrok

Install ngrok according to the instructions for your operating system.

3

Download your auth token

After logging in to your ngrok account, go to the dashboard to find your authentication token.

4

Authenticate ngrok

Run the following command to authenticate ngrok with your account:

$ngrok config add-authtoken YOUR_AUTH_TOKEN

Replace YOUR_AUTH_TOKEN with the token from your ngrok dashboard.

5

Start your server

Make sure your server is running locally on port 3000:

$node server.js
6

Expose your server

Run the following command to expose your local server:

$ngrok http 3000

After running the command, a URL appears like https://abcd1234.ngrok-free.app. This URL forwards requests to your local server. Save this URL for the next step.

Create a webhook notification

In order to receive webhook notifications, you must first create a notification via the API. Let’s create a notification that sends a webhook for the ApprovedPayment event. Call the POST /Notification endpoint to create a webhook notification. Set the target field to the public URL you created in the previous step, with /webhook appended at the end.

POST
/api/Notification
1from payabli import (
2 NotificationStandardRequest,
3 NotificationStandardRequestContent,
4 payabli,
5)
6
7client = payabli(
8 api_key="YOUR_API_KEY",
9)
10client.notification.add_notification(
11 request=NotificationStandardRequest(
12 content=NotificationStandardRequestContent(
13 event_type="CreatedApplication",
14 ),
15 frequency="untilcancelled",
16 method="web",
17 owner_id="236",
18 owner_type=0,
19 status=1,
20 target="https://webhook.site/2871b8f8-edc7-441a-b376-98d8c8e33275",
21 ),
22)

See Create notification for more information about the POST /Notification/ endpoint. See ApprovedPayment for more information about the ApprovedPayment event.

Test the webhook notification

You’ve set up your server, exposed it to the internet, and created a webhook notification pointing to it. Let’s create a test file that processes a payment in order to trigger the webhook notification.

1

Create the test file

Inside your project directory, create a new file named test-payment.js:

$touch test-payment.js
2

Write the test code

Use the interactive walkthrough to process a test payment in order to trigger your webhook notification. The interactive walkthrough displays code examples alongside step-by-step explanations.

Loading walkthrough content

Loading walkthrough...

Loading walkthrough...

/// Define API credentials

Set your Payabli API key, entrypoint, and the sandbox API base URL. Replace YOUR_API_KEY and YOUR_ENTRYPOINT with your actual credentials from your Payabli account.

1// test-payment.js
2const API_KEY = 'YOUR_API_KEY';
3const ENTRY_POINT = 'YOUR_ENTRYPOINT';
4const API_BASE_URL = 'https://api-sandbox.payabli.com/api';

/// Build the payment request

Create a request object with the paymentDetails, paymentMethod, and customerData objects. This example uses a test card number.

-28
1// test-payment.js
2const API_KEY = 'YOUR_API_KEY';
3const ENTRY_POINT = 'YOUR_ENTRYPOINT';
4const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
5
6const requestBody = {
7 entryPoint: ENTRY_POINT,
8 ipaddress: '255.255.255.255',
9 paymentDetails: {
10 totalAmount: 100,
11 serviceFee: 0
12 },
13 paymentMethod: {
14 method: 'card',
15 cardnumber: '4111111111111111',
16 cardexp: '02/27',
17 cardcvv: '999',
18 cardHolder: 'John Cassian',
19 cardzip: '12345',
20 initiator: 'payor'
21 },
22 customerData: {
23 customerId: 4440
24 }
25};

/// Make the API request

Use the fetch API to send a POST request to the API’s /MoneyIn/getpaid endpoint. Include the API key in the requestToken header and include the entrypoint in the entryPoint field.

-41
1// test-payment.js
2const API_KEY = 'YOUR_API_KEY';
3const ENTRY_POINT = 'YOUR_ENTRYPOINT';
4const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
5
6const requestBody = {
7 entryPoint: ENTRY_POINT,
8 ipaddress: '255.255.255.255',
9 paymentDetails: {
10 totalAmount: 100,
11 serviceFee: 0
12 },
13 paymentMethod: {
14 method: 'card',
15 cardnumber: '4111111111111111',
16 cardexp: '02/27',
17 cardcvv: '999',
18 cardHolder: 'John Cassian',
19 cardzip: '12345',
20 initiator: 'payor'
21 },
22 customerData: {
23 customerId: 4440
24 }
25};
26
27console.log('Processing payment...');
28
29fetch(`${API_BASE_URL}/MoneyIn/getpaid`, {
30 method: 'POST',
31 headers: {
32 'Content-Type': 'application/json',
33 'requestToken': API_KEY
34 },
35 body: JSON.stringify(requestBody)
36})

/// Handle the response

Parse the JSON response and display the payment result. Check if the transaction was successful and log the reference ID.

-49
1// test-payment.js
2const API_KEY = 'YOUR_API_KEY';
3const ENTRY_POINT = 'YOUR_ENTRYPOINT';
4const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
5
6const requestBody = {
7 entryPoint: ENTRY_POINT,
8 ipaddress: '255.255.255.255',
9 paymentDetails: {
10 totalAmount: 100,
11 serviceFee: 0
12 },
13 paymentMethod: {
14 method: 'card',
15 cardnumber: '4111111111111111',
16 cardexp: '02/27',
17 cardcvv: '999',
18 cardHolder: 'John Cassian',
19 cardzip: '12345',
20 initiator: 'payor'
21 },
22 customerData: {
23 customerId: 4440
24 }
25};
26
27console.log('Processing payment...');
28
29fetch(`${API_BASE_URL}/MoneyIn/getpaid`, {
30 method: 'POST',
31 headers: {
32 'Content-Type': 'application/json',
33 'requestToken': API_KEY
34 },
35 body: JSON.stringify(requestBody)
36})
37 .then(response => response.json())
38 .then(data => {
39 console.log('Payment Response:', JSON.stringify(data, null, 2));
40
41 if (data.isSuccess) {
42 console.log('✓ Payment processed successfully!');
43 console.log(` Reference ID: ${data.responseData.referenceId}`);
44 } else {
45 console.log('✗ Payment failed:', data.responseText);
46 }
47 })

/// Add error handling

Add error handling to catch any network errors or API failures during the payment process.

-51
1// test-payment.js
2const API_KEY = 'YOUR_API_KEY';
3const ENTRY_POINT = 'YOUR_ENTRYPOINT';
4const API_BASE_URL = 'https://api-sandbox.payabli.com/api';
5
6const requestBody = {
7 entryPoint: ENTRY_POINT,
8 ipaddress: '255.255.255.255',
9 paymentDetails: {
10 totalAmount: 100,
11 serviceFee: 0
12 },
13 paymentMethod: {
14 method: 'card',
15 cardnumber: '4111111111111111',
16 cardexp: '02/27',
17 cardcvv: '999',
18 cardHolder: 'John Cassian',
19 cardzip: '12345',
20 initiator: 'payor'
21 },
22 customerData: {
23 customerId: 4440
24 }
25};
26
27console.log('Processing payment...');
28
29fetch(`${API_BASE_URL}/MoneyIn/getpaid`, {
30 method: 'POST',
31 headers: {
32 'Content-Type': 'application/json',
33 'requestToken': API_KEY
34 },
35 body: JSON.stringify(requestBody)
36})
37 .then(response => response.json())
38 .then(data => {
39 console.log('Payment Response:', JSON.stringify(data, null, 2));
40
41 if (data.isSuccess) {
42 console.log('✓ Payment processed successfully!');
43 console.log(` Reference ID: ${data.responseData.referenceId}`);
44 } else {
45 console.log('✗ Payment failed:', data.responseText);
46 }
47 })
48 .catch(error => {
49 console.error('Error processing payment:', error.message);
50 });
3

Run the test

Run the test file with the following command:

$node test-payment.js

This file processes a payment and triggers the webhook notification.

4

Check output

Check your server’s console output to see the received webhook data. You should see the details of the approved transaction printed in the console.

Next steps

Congrats! You’ve built a basic webhook integration that includes:

  • A webhook notification for the ApprovedPayment event
  • A server that listens for the ApprovedPayment event and fetches details about the payment

Try creating new webhook notifications for different event types and triggering them with API calls. All webhook integrations follow the same structure as the one you built in this guide. See the Webhook notification response reference for more information about the different event types you can create webhook notifications for. Contact your Payabli solutions engineer for assistance with webhook integrations in your projects.

See these related resources to help you get the most out of Payabli.