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()); } }