prepare('SELECT * FROM discounts WHERE code = ? AND is_active = 1'); $stmt->execute([$coupon_code]); $coupon = $stmt->fetch(); if ($coupon) { // Check date validity and usage limit (already done in previous step, but good to double check) // ... try { $stripe_coupon_params = []; if ($coupon['type'] === 'percentage') { $stripe_coupon_params['percent_off'] = $coupon['value']; } else { // fixed $stripe_coupon_params['amount_off'] = $coupon['value'] * 100; $stripe_coupon_params['currency'] = 'usd'; } $stripe_coupon_params['duration'] = 'once'; // Or 'repeating', 'forever' $stripe_coupon_params['name'] = $coupon['code']; $stripe_coupon = \Stripe\Coupon::create($stripe_coupon_params); $stripe_coupon_id = $stripe_coupon->id; } catch (\Stripe\Exception\ApiErrorException $e) { // Coupon creation failed, proceed without discount } } } // Get client's stripe customer id or create a new one $stmt = db()->prepare("SELECT stripe_customer_id, email, name FROM clients WHERE id = ?"); $stmt->execute([$client_id]); $client = $stmt->fetch(); $stripe_customer_id = $client['stripe_customer_id']; if (!$stripe_customer_id) { $customer = \Stripe\Customer::create([ 'email' => $client['email'], 'name' => $client['name'], ]); $stripe_customer_id = $customer->id; $update_stmt = db()->prepare("UPDATE clients SET stripe_customer_id = ? WHERE id = ?"); $update_stmt->execute([$stripe_customer_id, $client_id]); } // Create a Stripe Checkout Session try { $checkout_params = [ 'payment_method_types' => ['card'], 'line_items' => [[ 'price_data' => [ 'currency' => $plan['currency'], 'product_data' => [ 'name' => $plan['name'], ], 'unit_amount' => $plan['price'], 'recurring' => [ 'interval' => $plan['interval'], ], ], 'quantity' => 1, ]], 'mode' => 'subscription', 'success_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/subscription-success.php?session_id={CHECKOUT_SESSION_ID}', 'cancel_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/subscription-cancel.php', 'client_reference_id' => $client_id, 'customer' => $stripe_customer_id, ]; if ($stripe_coupon_id) { $checkout_params['discounts'] = [['coupon' => $stripe_coupon_id]]; } $checkout_session = \Stripe\Checkout\Session::create($checkout_params); header("HTTP/1.1 303 See Other"); header("Location: " . $checkout_session->url); exit; } catch (\Stripe\Exception\ApiErrorException $e) { header('Location: subscribe-checkout.php?plan_id='. $plan_id .'&error=stripe_error&message=' . urlencode($e->getMessage())); exit; } catch (Exception $e) { header('Location: subscribe-checkout.php?plan_id=' . $plan_id .'&error=generic_error&message=' . urlencode($e->getMessage())); exit; }