77 lines
2.6 KiB
PHP
77 lines
2.6 KiB
PHP
<?php
|
|
require_once __DIR__ . '/../vendor/autoload.php';
|
|
require_once __DIR__ . '/../db/config.php';
|
|
|
|
\Stripe\Stripe::setApiKey('sk_test_51Hh9Y2L9s5P2Q8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4sYgY8Z4');
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
$json_str = file_get_contents('php://input');
|
|
$json_obj = json_decode($json_str);
|
|
|
|
$pdo = db();
|
|
|
|
try {
|
|
// 1. Validation
|
|
if (empty($json_obj->plan_id) || empty($json_obj->name) || empty($json_obj->email) || empty($json_obj->address) || empty($json_obj->password)) {
|
|
throw new Exception('Incomplete data provided.');
|
|
}
|
|
|
|
// 2. Fetch Plan
|
|
$stmt = $pdo->prepare("SELECT * FROM plans WHERE id = ?");
|
|
$stmt->execute([$json_obj->plan_id]);
|
|
$plan = $stmt->fetch(PDO::FETCH_OBJ);
|
|
if (!$plan) {
|
|
throw new Exception('Plan not found.');
|
|
}
|
|
$order_amount = $plan->price_monthly; // Amount in dollars
|
|
|
|
// 3. Create Stripe Customer
|
|
$stripe_customer = \Stripe\Customer::create([
|
|
'name' => $json_obj->name,
|
|
'email' => $json_obj->email,
|
|
'address' => [
|
|
'line1' => $json_obj->address
|
|
],
|
|
]);
|
|
|
|
// 4. Create Local Customer
|
|
$hashed_password = password_hash($json_obj->password, PASSWORD_DEFAULT);
|
|
$stmt = $pdo->prepare("INSERT INTO customers (name, email, password, service_address, stripe_customer_id) VALUES (?, ?, ?, ?, ?)");
|
|
$stmt->execute([$json_obj->name, $json_obj->email, $hashed_password, $json_obj->address, $stripe_customer->id]);
|
|
$customer_id = $pdo->lastInsertId();
|
|
|
|
// 5. Create Local Order
|
|
$stmt = $pdo->prepare("INSERT INTO orders (customer_id, plan_id, order_status, amount) VALUES (?, ?, 'pending', ?)");
|
|
$stmt->execute([$customer_id, $plan->id, $order_amount]);
|
|
$order_id = $pdo->lastInsertId();
|
|
|
|
// 6. Create Stripe Payment Intent
|
|
$paymentIntent = \Stripe\PaymentIntent::create([
|
|
'customer' => $stripe_customer->id,
|
|
'amount' => round($order_amount * 100), // Amount in cents
|
|
'currency' => 'aud',
|
|
'automatic_payment_methods' => [
|
|
'enabled' => true,
|
|
],
|
|
'metadata' => [
|
|
'order_id' => $order_id,
|
|
'customer_id' => $customer_id,
|
|
'plan_id' => $plan->id
|
|
]
|
|
]);
|
|
|
|
// 7. Update Local Order with Payment Intent ID
|
|
$stmt = $pdo->prepare("UPDATE orders SET stripe_payment_intent_id = ? WHERE id = ?");
|
|
$stmt->execute([$paymentIntent->id, $order_id]);
|
|
|
|
// 8. Return Client Secret
|
|
echo json_encode([
|
|
'clientSecret' => $paymentIntent->client_secret,
|
|
]);
|
|
|
|
} catch (Exception $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['error' => $e->getMessage()]);
|
|
}
|