Home / Webhooks / Stripe Webhooks

Stripe Webhooks

Implementing Stripe webhook handling

Stripe Webhook Implementation

Webhook Endpoint

/webhooks/stripe

Setup in Stripe Dashboard

  1. Go to Stripe Dashboard → Developers → Webhooks
  2. Add endpoint: https://yourdomain.com/webhooks/stripe
  3. Select events: checkout.session.completed
  4. Copy webhook signing secret
  5. Add secret to module configuration

Webhook Handler

// In webhooks/stripe.php
$payload = file_get_contents('php://input');
$signature = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';

// Log webhook
$db = Database::getInstance();
$stmt = $db->prepare("INSERT INTO webhooks (gateway, payload, created_at) VALUES (?, ?, NOW())");
$stmt->bind_param("ss", $gateway, $payload);
$stmt->execute();

// Process via module
$moduleManager = new ModuleManager();
$gatewayModule = $moduleManager->getModule('stripe');

if ($gatewayModule) {
    $result = $gatewayModule->execute('webhook', [
        'payload' => $payload,
        'signature' => $signature
    ]);
}

Module Webhook Handler

// In StripeGateway.php
private function handleWebhook($params) {
    $payload = $params['payload'] ?? '';
    $signature = $params['signature'] ?? '';
    
    // Verify signature
    if (!empty($this->config['webhook_secret'])) {
        try {
            $event = \Stripe\Webhook::constructEvent(
                $payload,
                $signature,
                $this->config['webhook_secret']
            );
        } catch (\Exception $e) {
            return ['success' => false, 'error' => 'Invalid signature'];
        }
    } else {
        $event = json_decode($payload, true);
    }
    
    // Handle event
    if ($event['type'] === 'checkout.session.completed') {
        $session = $event['data']['object'];
        $invoiceId = $session['metadata']['invoice_id'] ?? null;
        
        if ($invoiceId) {
            // Mark invoice as paid
            // Activate services
            // Send confirmation email
        }
    }
    
    return ['success' => true];
}

Events Handled

  • checkout.session.completed - Payment completed
  • payment_intent.succeeded - Payment succeeded
  • charge.refunded - Refund processed