58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
|
require_once 'vendor/autoload.php';
|
|
require_once 'db/config.php';
|
|
|
|
session_start();
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
|
|
// Load Stripe API key from .env
|
|
$stripeSecretKey = getenv('STRIPE_SECRET_KEY');
|
|
if (!$stripeSecretKey) {
|
|
die('Stripe secret key is not configured.');
|
|
}
|
|
|
|
\Stripe\Stripe::setApiKey($stripeSecretKey);
|
|
|
|
// Get the user's Stripe Customer ID from your database
|
|
$userId = $_SESSION['user_id'];
|
|
$customerId = null;
|
|
|
|
try {
|
|
$pdo = db();
|
|
$stmt = $pdo->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());
|
|
}
|