35696-vm/webhook.php
Flatlogic Bot 011d28fa8c seck
2025-11-13 18:26:31 +00:00

93 lines
2.9 KiB
PHP

<?php
require_once 'vendor/autoload.php';
require_once 'db/config.php';
// Get Stripe keys from environment
$stripeSecretKey = getenv('STRIPE_SECRET_KEY');
$webhookSecret = getenv('STRIPE_WEBHOOK_SECRET');
if (!$stripeSecretKey || !$webhookSecret) {
http_response_code(500);
error_log('Stripe keys are not configured.');
exit('Configuration error.');
}
\Stripe\Stripe::setApiKey($stripeSecretKey);
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent(
$payload, $sig_header, $webhookSecret
);
} catch(\UnexpectedValueException $e) {
http_response_code(400);
exit(); // Invalid payload
} catch(\Stripe\Exception\SignatureVerificationException $e) {
http_response_code(400);
exit(); // Invalid signature
}
// Handle the event
switch ($event->type) {
case 'checkout.session.completed':
$session = $event->data->object;
handleCheckoutSession($session);
break;
default:
// Unexpected event type
error_log('Received unknown event type ' . $event->type);
}
http_response_code(200);
function handleCheckoutSession($session) {
$userId = $session->client_reference_id;
$stripeChargeId = $session->payment_intent; // Using payment_intent as a proxy for charge ID
if (!$userId) {
error_log('Webhook Error: No client_reference_id in checkout.session.completed');
return;
}
try {
$pdo = db();
// Retrieve the line items to find out what was purchased
$line_items = \Stripe\Checkout\Session::allLineItems($session->id, ['limit' => 1]);
$priceId = $line_items->data[0]->price->id;
// Get plan details from our database
$stmt = $pdo->prepare("SELECT id, credits_awarded, price FROM plans WHERE stripe_price_id = ?");
$stmt->execute([$priceId]);
$plan = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$plan) {
error_log("Webhook Error: Plan with price ID {$priceId} not found in database.");
return;
}
$planId = $plan['id'];
$creditsPurchased = $plan['credits_awarded'];
$amountPaid = $plan['price'];
// Record the purchase
$sql = "INSERT INTO purchases (user_id, plan_id, stripe_charge_id, credits_purchased, amount_paid) VALUES (?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId, $planId, $stripeChargeId, $creditsPurchased, $amountPaid]);
// Add credits to the user's account
$sql = "UPDATE users SET credits = credits + ? WHERE id = ?";
$stmt = $pdo->prepare($sql);
$stmt->execute([$creditsPurchased, $userId]);
} catch (\Stripe\Exception\ApiErrorException $e) {
error_log("Stripe API Error in webhook: " . $e->getMessage());
} catch (PDOException $e) {
error_log("Database error in webhook: " . $e->getMessage());
}
}