Webhooks
Webhooks provide a way for PaymentKit to send real-time notifications to your application when specific events occur in your account, such as a successful payment or a new subscription. Instead of you polling the API for changes, PaymentKit pushes the data to your specified URL, making your application more efficient and responsive.
This guide covers the webhook workflow, how to set up an endpoint, and best practices for handling incoming event notifications.
Webhook Workflow#
The process involves three main steps: creating an endpoint, listening for events, and acknowledging receipt. Your server must be publicly accessible to receive these notifications from PaymentKit.
- Create an Endpoint: You register a URL in your application with PaymentKit and subscribe to the specific events you want to be notified about.
- Receive Events: PaymentKit sends an HTTP POST request with a JSON payload to your URL when a subscribed event happens.
- Acknowledge Receipt: Your endpoint must return a
2xx
HTTP status code to confirm it has received the event. If PaymentKit doesn't receive a2xx
response, it will attempt to resend the event notification multiple times.
Setting Up a Webhook Endpoint#
You can create a webhook endpoint using the payment.webhookEndpoints.create
method. You need to provide the URL that will handle the events and a list of event types you want to subscribe to.
import payment from '@blocklet/payment-js';
async function createWebhookEndpoint() {
try {
const webhookEndpoint = await payment.webhookEndpoints.create({
url: 'https://example.com/webhook',
enabled_events: [
'checkout.session.completed',
'customer.subscription.created',
'customer.subscription.deleted',
'customer.subscription.started',
'customer.subscription.renewed',
'payment_intent.succeeded'
]
});
console.log('Webhook endpoint created:', webhookEndpoint.id);
return webhookEndpoint;
} catch (error) {
console.error('Failed to create webhook endpoint:', error.message);
}
}
createWebhookEndpoint();
Common Events#
You can subscribe to a variety of events to automate your workflows. Here are some of the most common ones:
Event Type | Description |
---|---|
| Occurs when a customer completes a Checkout Session. |
| Occurs whenever a new subscription is created. |
| Occurs whenever a subscription is updated (e.g., plan change). |
| Occurs whenever a subscription is canceled. |
| Occurs when a subscription becomes active for the first time. |
| Occurs when a subscription successfully renews. |
| Occurs when a payment has been successfully processed. |
Handling Incoming Events#
Your application needs an HTTP endpoint (a route) to receive the webhook events. This endpoint should parse the JSON body of the incoming POST request to access the event data.
Here is a basic example using Express.js to listen for and process webhook events:
import express from 'express';
const app = express();
// Use a middleware to parse JSON bodies. This is crucial.
app.post('/webhook', express.json({ type: 'application/json' }), (request, response) => {
const event = request.body;
// Process the event based on its type
switch (event.type) {
case 'payment_intent.succeeded':
const paymentIntent = event.data.object;
// Logic to handle a successful payment, such as fulfilling an order.
console.log(`Payment for ${paymentIntent.amount} succeeded.`);
break;
case 'customer.subscription.created':
const subscription = event.data.object;
// Logic to handle a new subscription, such as provisioning a service.
console.log(`Subscription ${subscription.id} was created.`);
break;
// ... handle other event types
default:
console.log(`Unhandled event type: ${event.type}`);
}
// Send a 200 OK response to acknowledge receipt of the event
response.status(200).send();
});
const PORT = 3000;
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
Security and Best Practices#
When implementing webhooks, it's important to follow security and reliability best practices.
Verify Webhook Signatures#
To ensure that incoming requests are genuinely from PaymentKit and not from a malicious third party, you should verify the webhook signature. PaymentKit signs each webhook event it sends to your endpoint. This is done by including a signature in each event’s request headers. Verifying this signature confirms the event's authenticity.
While the SDK may provide helpers for this in the future, the verification process typically involves using a secret key provided when you create the webhook endpoint. Your application uses this secret to generate a signature from the request payload and compares it to the signature sent by PaymentKit. Always verify signatures in your production environment.
Handle Events Idempotently#
Your endpoint might receive the same event more than once due to network issues or retries from PaymentKit. Design your event processing logic to be idempotent, meaning that processing the same event multiple times does not result in duplicate actions, like shipping a product twice or granting service access multiple times. A common strategy is to log the ID of each processed event and skip any events whose IDs you have already logged.
For a detailed list of all methods available for managing webhook endpoints, refer to the Webhook Endpoints API Reference.