false, 'message' => 'Error: Stripe SDK not found. Please install it by running "composer require stripe/stripe-php" in your terminal.' ]); exit; } require_once __DIR__ . '/../../vendor/autoload.php'; require_once __DIR__ . '/../../includes/Database.php'; // Get DB connection $db = Database::getInstance(); $connection = $db->getConnection(); // Fetch Stripe secret key from settings $stripe_secret_key = ''; $result = $connection->query("SELECT key_value FROM settings WHERE key_name = 'stripe_secret_key'"); if ($row = $result->fetch_assoc()) { $stripe_secret_key = $row['key_value']; } if (empty($stripe_secret_key)) { http_response_code(500); echo json_encode([ 'success' => false, 'message' => 'Stripe secret key is not configured. Please set it in the admin settings.' ]); exit; } \Stripe\Stripe::setApiKey($stripe_secret_key); // Get the request body $json_str = file_get_contents('php://input'); $json_obj = json_decode($json_str); if (!$json_obj || !isset($json_obj->product_id)) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid request. Product ID is missing.']); exit; } $product_id = filter_var($json_obj->product_id, FILTER_VALIDATE_INT); if ($product_id === false) { http_response_code(400); echo json_encode(['success' => false, 'message' => 'Invalid Product ID.']); exit; } // Fetch product price from the database $stmt = $connection->prepare("SELECT price FROM products WHERE id = ?"); $stmt->bind_param("i", $product_id); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 0) { http_response_code(404); echo json_encode(['success' => false, 'message' => 'Product not found.']); exit; } $product = $result->fetch_assoc(); $price = $product['price']; // Create a PaymentIntent try { $paymentIntent = \Stripe\PaymentIntent::create([ 'amount' => $price * 100, // Amount in cents 'currency' => 'usd', // or get from settings/request ]); echo json_encode([ 'success' => true, 'clientSecret' => $paymentIntent->client_secret ]); } catch (\Stripe\Exception\ApiErrorException $e) { http_response_code(500); echo json_encode([ 'success' => false, 'message' => 'Failed to create Payment Intent.', 'error' => $e->getMessage() ]); }