84 lines
2.4 KiB
PHP
84 lines
2.4 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
require_once 'includes/api_keys.php';
|
|
require_once 'vendor/autoload.php';
|
|
|
|
// Redirect to login if user is not logged in
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header("Location: login.php");
|
|
exit();
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
|
http_response_code(405);
|
|
echo 'Method Not Allowed';
|
|
exit();
|
|
}
|
|
|
|
$userId = $_SESSION['user_id'];
|
|
$pdoconnection = db();
|
|
|
|
// Fetch cart items
|
|
$stmt = $pdoconnection->prepare("SELECT mi.name, mi.price, c.quantity FROM cart c JOIN menu_items mi ON c.menu_item_id = mi.id WHERE c.user_id = :user_id");
|
|
$stmt->bindParam(':user_id', $userId);
|
|
$stmt->execute();
|
|
$cartItems = $stmt->fetchAll(PDO::FETCH_ASSOC);
|
|
|
|
if (empty($cartItems)) {
|
|
header("Location: cart.php");
|
|
exit();
|
|
}
|
|
|
|
// Set Stripe API key
|
|
\Stripe\Stripe::setApiKey(STRIPE_API_KEY);
|
|
|
|
$line_items = [];
|
|
foreach ($cartItems as $item) {
|
|
$line_items[] = [
|
|
'price_data' => [
|
|
'currency' => 'usd',
|
|
'product_data' => [
|
|
'name' => $item['name'],
|
|
],
|
|
'unit_amount' => $item['price'] * 100, // Price in cents
|
|
],
|
|
'quantity' => $item['quantity'],
|
|
];
|
|
}
|
|
|
|
// Get delivery info from POST data
|
|
$customerName = $_POST['name'] ?? 'N/A';
|
|
$address = $_POST['address'] ?? 'N/A';
|
|
$phone = $_POST['phone'] ?? 'N/A';
|
|
$restaurantId = $_POST['restaurant_id'] ?? 0;
|
|
|
|
// Get the protocol and host
|
|
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
|
|
$host = $_SERVER['HTTP_HOST'];
|
|
|
|
try {
|
|
$checkout_session = \Stripe\Checkout\Session::create([
|
|
'payment_method_types' => ['card'],
|
|
'line_items' => $line_items,
|
|
'mode' => 'payment',
|
|
'success_url' => $protocol . '://' . $host . '/payment-success.php?session_id={CHECKOUT_SESSION_ID}',
|
|
'cancel_url' => $protocol . '://' . $host . '/payment-cancel.php',
|
|
'metadata' => [
|
|
'user_id' => $userId,
|
|
'restaurant_id' => $restaurantId,
|
|
'customer_name' => $customerName,
|
|
'address' => $address,
|
|
'phone' => $phone,
|
|
]
|
|
]);
|
|
|
|
header("HTTP/1.1 303 See Other");
|
|
header("Location: " . $checkout_session->url);
|
|
} catch (Exception $e) {
|
|
// Handle any errors from Stripe
|
|
http_response_code(500);
|
|
echo 'Error creating Stripe session: ' . $e->getMessage();
|
|
// In a real app, you would log this error
|
|
}
|
|
?>
|