subscription; $user_id = $checkout_session->metadata->user_id; // Double-check that the user ID from the session matches the one in Stripe metadata if ($user_id != $_SESSION['user_id']) { throw new Exception("User ID mismatch."); } // Reconstruct plan name from metadata $people = $checkout_session->metadata->people; $meals = $checkout_session->metadata->meals_per_week; $plan_name = sprintf("Weekly plan for %d %s, %d %s per week", $people, ($people > 1 ? 'people' : 'person'), $meals, ($meals > 1 ? 'meals' : 'meal') ); $product_ids = json_decode($checkout_session->metadata->product_ids ?? '[]'); if (!empty($product_ids)) { $plan_name .= " with add-ons"; } $pdo = db(); $pdo->beginTransaction(); // Save the main subscription $stmt = $pdo->prepare("INSERT INTO subscriptions (user_id, plan_id, stripe_subscription_id, status, plan_name) VALUES (?, ?, ?, 'active', ?)"); $stmt->execute([$user_id, 'custom', $stripe_subscription_id, $plan_name]); // Save the subscribed products if (!empty($product_ids)) { $product_stmt = $pdo->prepare("INSERT INTO user_subscription_products (user_id, product_id, stripe_subscription_id, quantity) VALUES (?, ?, ?, 1)"); foreach ($product_ids as $product_id) { $product_stmt->execute([$user_id, $product_id, $stripe_subscription_id]); } } $pdo->commit(); unset($_SESSION['intended_plan']); } catch (\Stripe\Exception\ApiErrorException $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Error: ' . $e->getMessage()]; header('Location: pricing.php'); exit; } catch (Exception $e) { if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); } $_SESSION['flash_message'] = ['type' => 'danger', 'message' => 'Error: ' . $e->getMessage()]; header('Location: pricing.php'); exit; } include 'admin/templates/header.php'; ?>
Thank you for subscribing. Your plan and selected products are now active.
You will be redirected to your profile page shortly.