Stripe Webhooks
Implementing Stripe webhook handling
Stripe Webhook Implementation
Webhook Endpoint
/webhooks/stripe
Setup in Stripe Dashboard
- Go to Stripe Dashboard → Developers → Webhooks
- Add endpoint:
https://yourdomain.com/webhooks/stripe - Select events:
checkout.session.completed - Copy webhook signing secret
- 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 completedpayment_intent.succeeded- Payment succeededcharge.refunded- Refund processed