87 lines
2.4 KiB
PHP
87 lines
2.4 KiB
PHP
<?php
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
// Check for Composer autoloader
|
|
if (!file_exists(__DIR__ . '/../../vendor/autoload.php')) {
|
|
http_response_code(500);
|
|
echo json_encode([
|
|
'success' => 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__ . '/../../db/config.php';
|
|
|
|
// Get DB connection
|
|
$pdo = db();
|
|
|
|
// Fetch Stripe secret key from settings
|
|
$stmt = $pdo->query("SELECT stripe_secret_key FROM settings ORDER BY id DESC LIMIT 1");
|
|
$settings = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
$stripe_secret_key = $settings['stripe_secret_key'] ?? '';
|
|
|
|
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 = $pdo->prepare("SELECT price FROM products WHERE id = ?");
|
|
$stmt->execute([$product_id]);
|
|
$product = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if (!$product) {
|
|
http_response_code(404);
|
|
echo json_encode(['success' => false, 'message' => 'Product not found.']);
|
|
exit;
|
|
}
|
|
|
|
$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()
|
|
]);
|
|
} |