prepare("SELECT stripe_customer_id FROM subscriptions WHERE user_id = ? ORDER BY created_at DESC LIMIT 1"); $stmt->execute([$userId]); $customerId = $stmt->fetchColumn(); } catch (PDOException $e) { die('Could not retrieve customer data.'); } if (!$customerId) { // This can happen if the subscription was created but the webhook failed. // Or if the user has no subscription. header('Location: billing.php?error=nocustomer'); exit; } // The return URL to which the user will be redirected after managing their billing $returnUrl = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://" . $_SERVER['HTTP_HOST'] . '/billing.php'; try { // Create a Billing Portal session $portalSession = \Stripe\BillingPortal\Session::create([ 'customer' => $customerId, 'return_url' => $returnUrl, ]); // Redirect to the session URL header("Location: " . $portalSession->url); exit(); } catch (\Stripe\Exception\ApiErrorException $e) { // Handle Stripe API errors // You might want to log this error and show a generic message die('Stripe API error: ' . $e->getMessage()); }