34853-vm/api/create_payment_intent.php
2025-10-11 05:03:50 +00:00

56 lines
1.6 KiB
PHP

<?php
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../db/config.php';
// This is your test secret API key. Don't hardcode this in a real app.
\Stripe\Stripe::setApiKey('sk_test_51Hh9Y2L9s5P2Q8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4');
header('Content-Type: application/json');
function calculateOrderAmount(object $plan): int {
// Calculate 10% GST
$gst = $plan->price_monthly * 0.10;
$total = $plan->price_monthly + $gst;
// Return amount in cents
return round($total * 100);
}
try {
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if (!isset($json_obj->plan_id)) {
throw new Exception("Plan ID not provided.");
}
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ? AND is_active = 1");
$stmt->execute([$json_obj->plan_id]);
$plan = $stmt->fetch(PDO::FETCH_OBJ);
if (!$plan) {
throw new Exception("Plan not found.");
}
$paymentIntent = \Stripe\PaymentIntent::create([
'amount' => calculateOrderAmount($plan),
'currency' => 'aud',
'automatic_payment_methods' => [
'enabled' => true,
],
'metadata' => [
'plan_id' => $plan->id
]
]);
echo json_encode([
'clientSecret' => $paymentIntent->client_secret,
]);
} catch (Error $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
} catch (Exception $e) {
http_response_code(400);
echo json_encode(['error' => $e->getMessage()]);
}