Note: This is mock/placeholder content for demonstration purposes.
Webhooks notify your application when billing events occur, ensuring your app stays synchronized with your payment provider.
Webhooks are essential for:
Your webhook endpoint receives events from the payment provider:
// app/api/billing/webhook/route.ts
export async function POST(request: Request) {
const body = await request.text();
const signature = request.headers.get('stripe-signature');
// Verify webhook signature
const event = stripe.webhooks.constructEvent(
body,
signature,
process.env.STRIPE_WEBHOOK_SECRET
);
// Handle the event
await handleBillingEvent(event);
return new Response('OK', { status: 200 });
}
case 'customer.subscription.created':
await prisma.subscription.create({
data: {
id: event.data.object.id,
accountId: event.data.object.metadata.accountId,
status: 'active',
planId: event.data.object.items.data[0].price.id,
currentPeriodEnd: new Date(event.data.object.current_period_end * 1000),
},
});
break;
case 'customer.subscription.updated':
await prisma.subscription.update({
where: { id: event.data.object.id },
data: {
status: event.data.object.status,
planId: event.data.object.items.data[0].price.id,
currentPeriodEnd: new Date(event.data.object.current_period_end * 1000),
},
});
break;
case 'customer.subscription.deleted':
await prisma.subscription.update({
where: { id: event.data.object.id },
data: {
status: 'canceled',
canceledAt: new Date(),
},
});
break;
case 'invoice.payment_failed':
const subscription = await prisma.subscription.findUnique({
where: { id: event.data.object.subscription },
});
// Send payment failure notification
await sendPaymentFailureEmail(subscription.accountId);
break;
stripe listen --forward-to localhost:3000/api/billing/webhook
https://yourdomain.com/api/billing/webhook.envconst signature = request.headers.get('paddle-signature');
const verified = paddle.webhooks.verify(body, signature);
if (!verified) {
return new Response('Invalid signature', { status: 401 });
}
async function handleBillingEvent(event: Event) {
try {
await processEvent(event);
} catch (error) {
// Log error for debugging
console.error('Webhook error:', error);
// Store failed event for retry
await prisma.failedWebhook.create({
data: {
eventId: event.id,
type: event.type,
payload: event,
error: error.message,
},
});
// Throw to trigger provider retry
throw error;
}
}
# Stripe stripe trigger customer.subscription.created # Test specific scenarios stripe trigger payment_intent.payment_failed
curl -X POST https://your-app.com/api/billing/webhook \ -H "Content-Type: application/json" \ -H "stripe-signature: test_signature" \ -d @test-event.json
Track webhook delivery:
Most providers offer webhook monitoring dashboards showing delivery attempts and failures.