38394-vm/checkout.php
2026-02-15 08:01:20 +00:00

148 lines
6.2 KiB
PHP

<?php
file_put_contents('checkout_log.txt', "Checkout script started.\n", FILE_APPEND);
require_once 'db/config.php';
require_once 'db/thawani_config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
file_put_contents('checkout_log.txt', "Not a POST request.\n", FILE_APPEND);
header('Location: index.php');
exit;
}
file_put_contents('checkout_log.txt', 'POST data: ' . print_r($_POST, true) . "\n", FILE_APPEND);
$case_id = (int)$_POST['case_id'];
$amount = (float)$_POST['amount'];
$donor_name = $_POST['donor_name'] ?? 'Anonymous';
$donor_email = $_POST['donor_email'] ?? '';
$donor_phone = prefix_phone($_POST['donor_phone'] ?? '');
$lang = $_POST['lang'] ?? 'ar';
// Gift fields
$is_gift = (int)($_POST['is_gift'] ?? 0);
$gift_recipient_name = $_POST['gift_recipient_name'] ?? null;
$gift_recipient_phone = prefix_phone($_POST['gift_recipient_phone'] ?? null);
$gift_message = $_POST['gift_message'] ?? null;
if ($amount <= 0) {
file_put_contents('checkout_log.txt', "Invalid amount.\n", FILE_APPEND);
die("Invalid amount");
}
$pdo = db();
// Fetch case details
$stmt = $pdo->prepare("SELECT * FROM cases WHERE id = ?");
$stmt->execute([$case_id]);
$case = $stmt->fetch();
if (!$case || $case['status'] !== 'active') {
file_put_contents('checkout_log.txt', "Case not found or not active.\n", FILE_APPEND);
die("Case not found or not active");
}
// Create pending donation
$sql = "INSERT INTO donations (case_id, amount, status, donor_name, donor_email, donor_phone, is_gift, gift_recipient_name, gift_recipient_phone, gift_message)
VALUES (?, ?, 'pending', ?, ?, ?, ?, ?, ?, ?)";
$stmt = $pdo->prepare($sql);
$stmt->execute([$case_id, $amount, $donor_name, $donor_email, $donor_phone, $is_gift, $gift_recipient_name, $gift_recipient_phone, $gift_message]);
$donation_id = $pdo->lastInsertId();
file_put_contents('checkout_log.txt', "Donation created with ID: $donation_id\n", FILE_APPEND);
// Thawani Checkout Session Request
$payload = [
'client_reference_id' => (string)$donation_id,
'mode' => 'payment',
'products' => [
[
'name' => ($is_gift ? "Gift Donation: " : "") . $case['title_en'],
'unit_amount' => (int)($amount * 1000), // Thawani uses OMR baiza (1 OMR = 1000 baiza)
'quantity' => 1
]
],
'success_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/success.php?session_id={CHECKOUT_SESSION_ID}&lang=' . $lang,
'cancel_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/index.php?lang=' . $lang,
'metadata' => [
'donation_id' => $donation_id,
'case_id' => $case_id
]
];
// Check if keys are default/empty
if (THAWANI_SECRET_KEY === 'rRQ26GcsZ60u9Y9v9876543210' || empty(THAWANI_SECRET_KEY)) {
// Simulation Mode
file_put_contents('checkout_log.txt', "Thawani simulation mode.\n", FILE_APPEND);
?>
<!DOCTYPE html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head><title>Simulating Thawani Checkout</title><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"></head>
<body class="bg-light p-5 text-center">
<div class="card mx-auto" style="max-width: 500px;">
<div class="card-body">
<img src="https://checkout.thawani.om/logo.png" alt="Thawani" height="50" class="mb-4">
<h3>Thawani Checkout Simulation</h3>
<p>Donation ID: #<?= $donation_id ?></p>
<p>Amount: OMR <?= number_format($amount, 3) ?></p>
<?php if ($is_gift): ?>
<div class="alert alert-success small">Gift for: <?= htmlspecialchars($gift_recipient_name) ?> (<?= htmlspecialchars($gift_recipient_phone) ?>)</div>
<?php endif; ?>
<div class="alert alert-info small">This is a simulation because no valid Thawani keys are configured in <code>db/thawani_config.php</code>.</div>
<form action="success.php" method="GET">
<input type="hidden" name="session_id" value="mock_session_<?= time() ?>">
<input type="hidden" name="donation_id" value="<?= $donation_id ?>">
<input type="hidden" name="lang" value="<?= htmlspecialchars($lang) ?>">
<button type="submit" class="btn btn-success w-100">Simulate Success Payment</button>
</form>
<a href="index.php?lang=<?= htmlspecialchars($lang) ?>" class="btn btn-link mt-2">Cancel</a>
</div>
</div>
</body>
</html>
<?php
exit;
}
// REAL CURL CALL
file_put_contents('checkout_log.txt', "Performing real Thawani API call.\n", FILE_APPEND);
$ch = curl_init(THAWANI_API_URL . '/checkout/session');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'thawani-api-key: ' . THAWANI_SECRET_KEY
]);
$response = curl_exec($ch);
$err = curl_error($ch);
curl_close($ch);
if ($err) {
file_put_contents('checkout_log.txt', "CURL Error: $err\n", FILE_APPEND);
die("CURL Error: " . $err);
}
$data = json_decode($response, true);
file_put_contents('checkout_log.txt', 'Thawani response: ' . print_r($data, true) . "\n", FILE_APPEND);
if (isset($data['success']) && $data['success'] === true && isset($data['data']['session_id'])) {
$session_id = $data['data']['session_id'];
// Save session_id to donation record
$stmt = $pdo->prepare("UPDATE donations SET transaction_id = ? WHERE id = ?");
$stmt->execute([$session_id, $donation_id]);
$checkout_url = (THAWANI_ENV === 'sandbox')
? "https://uatcheckout.thawani.om/pay/" . $session_id . "?key=" . THAWANI_PUBLISHABLE_KEY
: "https://checkout.thawani.om/pay/" . $session_id . "?key=" . THAWANI_PUBLISHABLE_KEY;
file_put_contents('checkout_log.txt', "Redirecting to: $checkout_url\n", FILE_APPEND);
header("Location: " . $checkout_url);
exit;
} else {
file_put_contents('checkout_log.txt', "Thawani Error: " . print_r($data, true) . "\n", FILE_APPEND);
echo "<h3>Thawani Error</h3>";
echo "<pre>";
print_r($data);
echo "</pre>";
echo "<a href='index.php?lang=" . htmlspecialchars($lang) . "'>Go Back</a>";
}