Files
HotLunches/paypal_checkout_button.php
T
2026-10-19 15:22:52 -07:00

122 lines
4.8 KiB
PHP

<?php
/**
* PayPal Button Include (themed to match the site's own button style,
* e.g. "Print Remittance Form" — a plain btn--primary, not PayPal's own
* SDK-rendered widget, which can't be restyled).
*
* Include this file wherever you want to show the PayPal Checkout button.
*
* REQUIRED VARIABLES (must be set before including this file):
* - $owing: The amount to charge (float)
* - $trxnum: Your internal transaction/reference number (int)
*
* OPTIONAL VARIABLES:
* - $paypal_currency: Currency code (default: from config)
* - $paypal_description: Order description
* - $paypal_button_text: Button label (default: 'PayPal/Credit Card')
*
* USAGE:
* $owing = 25.00;
* $trxnum = 12345;
* include 'button_file.php';
*
* FLOW: click -> create order -> redirect to PayPal's approve page ->
* PayPal redirects back here with ?paypal=success&token=<orderId> ->
* this file captures the order server-side and shows the result.
* (Redirect-based, not the JS SDK popup/iframe button, so it can be
* styled as a plain themed link instead of PayPal's own widget.)
*/
require_once __DIR__ . '/paypal_checkout_config.php';
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
$paypal_currency = $paypal_currency ?? PAYPAL_CURRENCY;
$paypal_description = $paypal_description ?? 'Order Payment';
$paypal_button_text = $paypal_button_text ?? 'PayPal / Credit Card';
$_SESSION['paypal_checkout_amount'] = $owing;
$_SESSION['paypal_checkout_trxnum'] = $trxnum;
$_SESSION['paypal_checkout_currency'] = $paypal_currency;
$_SESSION['paypal_checkout_description'] = $paypal_description;
$containerId = 'pp-btn-' . uniqid();
// -- Handle the return trip from PayPal (redirect-based approval) ----------
$pppCaptureResult = null;
if (isset($_GET['paypal']) && $_GET['paypal'] === 'success' && isset($_GET['token'])) {
$orderId = $_GET['token'];
if (isset($_SESSION['paypal_order_id']) && $_SESSION['paypal_order_id'] === $orderId) {
require_once __DIR__ . '/paypal_checkout_api.php';
try {
$paypalApi = new PayPalCheckoutAPI();
$capture = $paypalApi->captureOrder($orderId);
if ($capture['status'] === 'COMPLETED') {
$pppCaptureResult = ['success' => true];
} else {
$pppCaptureResult = ['success' => false, 'error' => 'Payment was not completed. Status: ' . $capture['status']];
}
} catch (Exception $e) {
$pppCaptureResult = ['success' => false, 'error' => $e->getMessage()];
}
unset($_SESSION['paypal_order_id'], $_SESSION['paypal_order_trxnum'], $_SESSION['paypal_order_amount']);
}
} elseif (isset($_GET['paypal']) && $_GET['paypal'] === 'cancel') {
$pppCaptureResult = ['success' => false, 'error' => 'Payment was cancelled.'];
}
?>
<?php if ($pppCaptureResult): ?>
<div class="pp-btn-message" style="padding: 10px; margin-bottom: 10px; border-radius: 5px; max-width: 400px; margin-left: auto; margin-right: auto;
<?php echo $pppCaptureResult['success']
? 'background:#e8f5e9; color:#2e7d32; border:1px solid #a5d6a7;'
: 'background:#ffebee; color:#c62828; border:1px solid #ef9a9a;'; ?>">
<?php if ($pppCaptureResult['success']): ?>
<strong>Payment Successful!</strong>
<?php else: ?>
<?php echo htmlspecialchars($pppCaptureResult['error']); ?>
<?php endif; ?>
</div>
<?php endif; ?>
<div style="max-width: 400px; margin: 0 auto; text-align: center;">
<a href="#" id="<?php echo $containerId; ?>" class="btn btn--primary"><?php echo htmlspecialchars($paypal_button_text); ?></a>
</div>
<script>
(function() {
var btn = document.getElementById('<?php echo $containerId; ?>');
btn.addEventListener('click', function(e) {
e.preventDefault();
btn.style.pointerEvents = 'none';
var originalText = btn.textContent;
btn.textContent = 'Redirecting to PayPal...';
fetch('/paypal_checkout_create_order.php', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
amount: <?php echo json_encode($owing); ?>,
trxnum: <?php echo json_encode($trxnum); ?>,
currency: <?php echo json_encode($paypal_currency); ?>,
description: <?php echo json_encode($paypal_description); ?>
})
})
.then(function(response) { return response.json(); })
.then(function(orderData) {
if (orderData.error || !orderData.approveUrl) {
throw new Error(orderData.error || 'Could not start PayPal checkout.');
}
window.location.href = orderData.approveUrl;
})
.catch(function(err) {
alert('Payment failed: ' + err.message);
btn.style.pointerEvents = '';
btn.textContent = originalText;
});
});
})();
</script>