Handle webhook events
Learn how to use webhooks to receive payment events within your server.
A webhook is an HTTP endpoint you will create under your PayRex merchant account, allowing you to receive payment events. Some of these payment events are:
- Successful payment -
payment_intent.succeeded
. - Succesfully authorized an amount -
payment_intent.amount_capturable
.
Use cases of webhooks after receiving a payment
Manage business logic from the backend after successful payment redirection
If you don't know how to integrate payments yet, please check this guide.
After your customer completes a payment, they are redirected to the return_url
of your Payment Intent to show a page if the customer did not successfully pay the transaction. Suppose you need to trigger a custom business logic (e.g., updating records in the database) once your customer is redirected to the return_url.
In that case, developing the business logic via a separate HTTP endpoint and registering it as a webhook is best. This webhook will avoid problems:
- Suppose your customer encountered an internet connection problem. In that case, they will not be redirected to the
return_url
, and your custom business logic will not trigger. - Suppose your customer is successfully redirected to the
return_url
and hits refresh multiple times. In that case, you have to ensure that you handle this situation properly.
Realtime store of payments to your data warehouse
If you're building data analytics and want real-time data stored in your data warehouse, you can create and configure a webhook to receive successful payment data.
Setting up a webhook to receive successful payment events
1. Develop your API endpoint
Develop an API endpoint that will receive events from PayRex.
Step 1 is just an example of how to build an API endpoint and showcase how to evaluate the JSON payload that PayRex will send to your webhook. Adjust your code accordingly depending on your needs.
- Node
- PHP
- Python
- Ruby
// Protect your PayRex Secret API key at all costs. One common approach
// to store it in an environment variable.
// Add your PayRex test secret API key.
const payrexSecretApiKey = '';
const payrex = require('payrex-node')(payrexSecretApiKey);
// Highly recommended to store this to an environment variable.
webhookSecretKey = 'whsk_...';
payload = '';
signatureHeader = 't=...,te=,li=...';
try {
const event = await payrex.webhooks.parseEvent(payload, signatureHeader, webhookSecretKey);
} catch (error) {
if (error.name === 'ValueUnexpectedError') {
// Handle unexpected value
httpResponseCode = 400;
} else {
// Handle other possible errors
}
}
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data;
// Handle payment intent succeeded
break;
default:
console.log(`Received unknown event type ${event.type}`);
break;
}
require_once '../vendor/autoload.php';
// Protect your PayRex Secret API key at all costs. One common approach
// to store it in an environment variable.
// Add your PayRex test secret API key.
$payrexSecretApiKey = '';
$payrex = new \Payrex\PayrexClient($payrexSecretApiKey);
// Highly recommended to store this to an environment variable.
$webhookSecretKey = 'whsk_...';
$payload = @file_get_contents('php://input');
$signatureHeader = $_SERVER['HTTP_PAYREX_SIGNATURE'];
$payload = @file_get_contents('php://input');
$event = null;
try {
$event = \Payrex\Webhook::parseEvent(
$payload,
$signatureHeader,
$webhookSecretKey
);
} catch(\Payrex\Exceptions\UnexpectedValueException $e) {
// Invalid payload
http_response_code(400);
exit();
}
// Handle the event
switch ($event->type) {
case 'payment_intent.succeeded':
$paymentIntent = $event->data->resource; // contains a \Payrex\PaymentIntent instance
paymentIntentSucceededHandler($paymentIntent);
break;
default:
echo 'Received unknown event type ' . $event->type;
}
http_response_code(200);
from payrex import Client as PayrexClient
# Protect your PayRex Secret API key at all costs. One common approach
# to store it in an environment variable.
# Add your PayRex test secret API key.
payrex_secret_api_key = ''
payrex = PayrexClient(payrex_secret_api_key)
# Highly recommended to store this to an environment variable.
webhook_secret_key = 'whsk_...'
payload = ''
signature_header = 't=...,te=,li=...'
try:
event = payrex.webhooks.parse_event(
payload,
signature_header,
webhook_secret_key
)
except ValueUnexpectedError as e:
# Handle unexpected value
http_response_code = 400
# exit
if event.type == 'payment_intent.succeeded':
payment_intent = event.data
# Handle payment intent succeeded
else:
print(f'Received unknown event type {event.type}')
http_response_code = 200
require "payrex-ruby"
# Protect your PayRex Secret API key at all costs. One common approach
# to store it in an environment variable.
# Add your PayRex test secret API key.
payrex_secret_api_key = ""
payrex = Payrex::Client.new(payrex_secret_api_key)
# Highly recommended to store this to an environment variable.
webhook_secret_key = "whsk_..."
payload = ""
signature_header = "t=...,te=,li=..."
begin
event = payrex.webhook.parse_event(
payload: payload,
signature_header: signature_header,
webhook_secret_key: webhook_secret_key
)
rescue Payrex::Errors::ValueUnexpectedError => e
# Handle unexpected value
http_response_code = 400
exit
end
case event.type
when "payment_intent.succeeded"
payment_intent = event.data
# Handle payment intent succeeded
else
puts "Received unknown event type #{event.type}"
end
http_response_code = 200
2. Create a webhook resource
To start receiving events from the API endpoint you developed in step 1, create a Webhook resource under your PayRex merchant account.
- Node
- PHP
- Python
- Ruby
// Protect your PayRex Secret API key at all costs. One common approach
// to store it in an environment variable.
// Add your PayRex test secret API key.
const payrexSecretApiKey = '';
const payrex = require('payrex-node')(payrexSecretApiKey);
// Create a webhook
const webhook = await payrex.webhooks.create({
url: 'https://yourcompany.com/successful_payment_receiver.php',
// this is the event you should use to receive successful paid payments.
events: ['payment_intent.succeeded'],
// this is an optional attribute if you want to describe your webhook.
description: 'webhook for successful paid payments',
});
console.log(JSON.stringify(webhook));
<?php
require_once '../vendor/autoload.php';
// Protect your PayRex Secret API key at all costs. One common approach
// to store it in an environment variable.
// Add your PayRex test secret API key.
$payrexSecretApiKey = '';
$payrex = new \Payrex\PayrexClient($payrexSecretApiKey);
// Create a webhook
$webhook = $payrex->webhooks->create([
'url' => 'https://yourcompany.com/successful_payment_receiver.php',
// this is the event you should use to receive successful paid payments.
'events' => ['payment_intent.succeeded'],
// this is an optional attribute if you want to describe your webhook.
'description' => 'webhook for successful paid payments'
]);
echo json_encode($webhook);
from payrex import Client as PayrexClient
# Protect your PayRex Secret API key at all costs. One common approach
# to store it in an environment variable.
# Add your PayRex test secret API key.
payrex_secret_api_key = ''
payrex = PayrexClient(payrex_secret_api_key)
# Create a webhook
webhook = payrex.webhooks.create(
{
'url': 'https://yourcompany.com/successful_payment_receiver',
# this is the event you should use to receive successful paid payments.
'events': ['payment_intent.succeeded'],
# this is an optional attribute if you want to describe your webhook.
'description': 'webhook for successful paid payments'
}
)
print(webhook)
require "payrex-ruby"
# Protect your PayRex Secret API key at all costs. One common approach
# to store it in an environment variable.
# Add your PayRex test secret API key.
payrex_secret_api_key = ""
payrex = Payrex::Client.new(payrex_secret_api_key)
# Create a webhook
webhook = payrex.webhook.create(
url: "https://yourcompany.com/successful_payment_receiver",
# this is the event you should use to receive successful paid payments.
events: ["payment_intent.succeeded"],
# this is an optional attribute if you want to describe your webhook.
description: "webhook for successful paid payments"
)
puts webhook.to_json
From the code above, the url
is your API endpoint that will receive an event that happened from your PayRex account. You must ensure that the URL is accessible publicly to receive an event. If you are developing locally, you can use a public reverse proxy such as ngrok to expose your local development.
You should only create a webhook once. The goal is to create a webhook resource programmatically. In future releases, we will allow you to create a webhook resource from the Dashboard.
3. Test your webhook
This final step expects that you already have a working payment integration. Once you receive a successfully paid payment from your local testing, your API endpoint from step 1 should receive a payment_intent.succeeded
event.