By using Stripe webhooks, we can check the settings of the Payment Links we’ve created from the dashboard or API.
We can use the API to automatically check a new Payment Link’s settings, and correct them if need be.
Supported event types for the Payment Links
We can listen for the following events:
- payment_link.created
- payment_link.updated
Example code
The following code listens for the Payment Link events mentioned earlier:
const stripe = require('stripe')('YOUR_SECRET_API_KEY');
const express = require('express');
const app = express();
// This is your Stripe CLI webhook secret for testing your endpoint locally.
const endpointSecret = "whsec_xxxxxxx";
app.post('/webhook', express.raw({type: 'application/json'}), async (request, response) => {
const sig = request.headers['stripe-signature'];
let event;
try {
event = stripe.webhooks.constructEvent(request.body, sig, endpointSecret);
} catch (err) {
response.status(400).send(`Webhook Error: ${(err as Error).message}`);
return;
}
if (![
'payment_link.created',
'payment_link.updated'
].includes(event.type)) {
response.send();
return;
}
/**
* TODO: Check Payment Link settings
**/
const paymentLink = event.data.object
console.log(paymentLink)
// Return a 200 response to acknowledge receipt of the event
response.send();
});
app.listen(4242, () => console.log('Running on port 4242'));
The request object (event.data.object) contains the details of the Payment Link. Using this object we can check its details and settings.
If you want to know why we execute the stripe.webhooks.constructEvent function before handling the event, please read the webhook signature docs.
Correct configuration errors automatically
If we want to correct any issues with our configuration automatically, we can add the following code into the TODO area from the previous code example:
/**
* If the link does not allow the promotion code field,
* it's invalid configuration!
*/
if (!paymentLink.allow_promotion_codes) {
/**
* Call Payment Links API to enable it.
*/
await stripe.paymentLinks.update(paymentLink.id, {
allow_promotion_codes: true
})
}
The request object (event.data.object) contains the details and settings of the Payment Link.
This example will correct the allow_promotion_codes
options, in case it wasn’t correctly set when creating the Link.
We can also correct these types of settings:
- Collect Billing / Shipping address
- Activate Stripe Tax
- Behavior after the purchase is complete
Learn more about Stripe Payment Links
Top comments (0)