#atom

Event-driven notifications for payment processing

Core Idea: Payment webhooks are HTTP callbacks that notify applications about payment events in real-time, enabling automated responses to payment successes, failures, disputes, and other critical events without constant polling.

Key Elements

// webhook.js
const express = require('express');
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
const router = express.Router();

router.post('/stripe-webhook', express.raw({type: 'application/json'}), async (req, res) => {
  const sig = req.headers['stripe-signature'];
  let event;

  try {
    // Verify webhook signature
    event = stripe.webhooks.constructEvent(
      req.body,
      sig,
      process.env.STRIPE_WEBHOOK_SECRET
    );
  } catch (err) {
    console.log(`Webhook signature verification failed: ${err.message}`);
    return res.status(400).send(`Webhook Error: ${err.message}`);
  }

  // Handle specific events
  switch (event.type) {
    case 'payment_intent.succeeded':
      const paymentIntent = event.data.object;
      await fulfillOrder(paymentIntent);
      break;
      
    case 'checkout.session.completed':
      const session = event.data.object;
      await fulfillCheckoutSession(session);
      break;
      
    case 'invoice.payment_succeeded':
      const invoice = event.data.object;
      await handleSuccessfulSubscriptionPayment(invoice);
      break;
      
    case 'invoice.payment_failed':
      const failedInvoice = event.data.object;
      await handleFailedSubscriptionPayment(failedInvoice);
      break;
      
    default:
      console.log(`Unhandled event type: ${event.type}`);
  }

  // Return success response to acknowledge receipt
  res.status(200).json({received: true});
});

async function fulfillOrder(paymentIntent) {
  // Implementation for order fulfillment
  // - Update database
  // - Trigger email
  // - Provision access
  console.log(`Order fulfilled for payment: ${paymentIntent.id}`);
}

// Export router
module.exports = router;

Additional Connections

References

  1. Stripe Webhooks Documentation: https://stripe.com/docs/webhooks
  2. Webhook Security Best Practices: https://docs.webhook.site/best-practices.html

#webhooks #payments #event-driven


Connections:


Sources: