81 lines
2.7 KiB
PHP
81 lines
2.7 KiB
PHP
<?php
|
|
// Include the Stripe PHP library (assuming it's installed via Composer)
|
|
// require_once 'vendor/autoload.php';
|
|
|
|
require_once 'db/config.php';
|
|
|
|
// Set your Stripe API key and webhook secret
|
|
// \Stripe\Stripe::setApiKey('YOUR_STRIPE_SECRET_KEY');
|
|
$webhook_secret = 'YOUR_STRIPE_WEBHOOK_SECRET';
|
|
|
|
$payload = @file_get_contents('php://input');
|
|
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
|
|
$event = null;
|
|
|
|
/*
|
|
try {
|
|
$event = \Stripe\Webhook::constructEvent(
|
|
$payload, $sig_header, $webhook_secret
|
|
);
|
|
} catch(\UnexpectedValueException $e) {
|
|
// Invalid payload
|
|
http_response_code(400);
|
|
exit();
|
|
} catch(\Stripe\Exception\SignatureVerificationException $e) {
|
|
// Invalid signature
|
|
http_response_code(400);
|
|
exit();
|
|
}
|
|
|
|
// Handle the event
|
|
switch ($event->type) {
|
|
case 'checkout.session.completed':
|
|
$session = $event->data->object;
|
|
$user_id = $session->client_reference_id;
|
|
$stripe_subscription_id = $session->subscription;
|
|
|
|
// Get subscription details
|
|
$stripe = new \Stripe\StripeClient('YOUR_STRIPE_SECRET_KEY');
|
|
$subscription = $stripe->subscriptions->retrieve($stripe_subscription_id, []);
|
|
$plan = $subscription->items->data[0]->price->nickname;
|
|
|
|
// Store subscription in the database
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, stripe_subscription_id, plan, status, start_date, end_date) VALUES (?, ?, ?, ?, FROM_UNIXTIME(?), FROM_UNIXTIME(?))");
|
|
$stmt->execute([
|
|
$user_id,
|
|
$stripe_subscription_id,
|
|
$plan,
|
|
$subscription->status,
|
|
$subscription->current_period_start,
|
|
$subscription->current_period_end
|
|
]);
|
|
} catch (PDOException $e) {
|
|
// Log error
|
|
error_log("Webhook DB Error: " . $e->getMessage());
|
|
}
|
|
break;
|
|
case 'customer.subscription.updated':
|
|
$subscription = $event->data->object;
|
|
$stripe_subscription_id = $subscription->id;
|
|
$status = $subscription->status;
|
|
$end_date = $subscription->cancel_at_period_end ? $subscription->current_period_end : null;
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->prepare("UPDATE subscriptions SET status = ?, end_date = FROM_UNIXTIME(?) WHERE stripe_subscription_id = ?");
|
|
$stmt->execute([$status, $end_date, $stripe_subscription_id]);
|
|
} catch (PDOException $e) {
|
|
// Log error
|
|
error_log("Webhook DB Error: " . $e->getMessage());
|
|
}
|
|
break;
|
|
// ... handle other event types
|
|
default:
|
|
// Unexpected event type
|
|
}
|
|
*/
|
|
|
|
http_response_code(200);
|
|
?>
|