mirror of
https://github.com/myronblair/tomsjavajive
synced 2026-07-27 16:52:36 -05:00
Add Square payment processor, gated behind PAYMENT_PROCESSOR flag (default: stripe)
Consolidates payment processing onto the same Square account already used by tomtomgames.com and parkerslingshotrentals.com. Collapses the two prior parallel Stripe flows (hosted Checkout + embedded Elements) into a single Square Web Payments SDK flow, since Payments API is synchronous and removes the original reason for two paths. - includes/square.php: squareApi() cURL helper (mirrors the pattern already used on parkerslingshotrentals.com), markSquarePaymentResult() as the single source of truth for order completion shared by the sync response, webhook, and reconciliation poll - fixes a pre-existing bug where loyalty points were only ever awarded from the polling endpoint, never from the webhook. - api/create-square-payment.php replaces api/create-payment-intent.php; api/create-checkout-session.php deleted (no Square equivalent - single flow). - api/webhook.php rewritten for Squares signature scheme and event types. - api/payment-status.php repurposed to reconciliation-only fallback. - payment.php branches on PAYMENT_PROCESSOR so Stripe and Square code coexist deployed while dormant - flipping one config constant is the cutover/rollback. - admin/payments.php: added a Square settings card alongside the existing (now legacy-labeled) Stripe card. - db/schema.sql + live DB: added square_payment_id/square_order_id columns, stripe_* columns kept for historical orders. Not yet cut over - PAYMENT_PROCESSOR still defaults to stripe in config-secrets.php (outside this repo). Sandbox testing still needed before flipping to square/production.
This commit is contained in:
+100
-23
@@ -9,7 +9,7 @@ require_once __DIR__ . '/includes/header.php';
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
$section = $_POST['section'] ?? '';
|
||||
|
||||
|
||||
if ($section === 'stripe') {
|
||||
setSetting('payment_stripe', [
|
||||
'enabled' => isset($_POST['stripe_enabled']),
|
||||
@@ -20,7 +20,19 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
]);
|
||||
setFlash('success', 'Stripe settings updated');
|
||||
}
|
||||
|
||||
|
||||
if ($section === 'square') {
|
||||
setSetting('payment_square', [
|
||||
'enabled' => isset($_POST['square_enabled']),
|
||||
'sandbox' => isset($_POST['square_sandbox']),
|
||||
'app_id' => trim($_POST['square_app_id'] ?? ''),
|
||||
'location_id' => trim($_POST['square_location_id'] ?? ''),
|
||||
'access_token' => trim($_POST['square_access_token'] ?? ''),
|
||||
'webhook_signature_key' => trim($_POST['square_webhook_signature_key'] ?? '')
|
||||
]);
|
||||
setFlash('success', 'Square settings updated');
|
||||
}
|
||||
|
||||
if ($section === 'methods') {
|
||||
setSetting('payment_methods', [
|
||||
'card' => isset($_POST['method_card']),
|
||||
@@ -30,7 +42,7 @@ if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
||||
]);
|
||||
setFlash('success', 'Payment methods updated');
|
||||
}
|
||||
|
||||
|
||||
header('Location: /admin/payments.php');
|
||||
exit;
|
||||
}
|
||||
@@ -43,6 +55,15 @@ $stripe = getSetting('payment_stripe', [
|
||||
'webhook_secret' => ''
|
||||
]);
|
||||
|
||||
$square = getSetting('payment_square', [
|
||||
'enabled' => defined('PAYMENT_PROCESSOR') && PAYMENT_PROCESSOR === 'square',
|
||||
'sandbox' => defined('SQUARE_ENV') && SQUARE_ENV === 'sandbox',
|
||||
'app_id' => defined('SQUARE_APP_ID') ? SQUARE_APP_ID : '',
|
||||
'location_id' => defined('SQUARE_LOCATION_ID') ? SQUARE_LOCATION_ID : '',
|
||||
'access_token' => defined('SQUARE_ACCESS_TOKEN') ? SQUARE_ACCESS_TOKEN : '',
|
||||
'webhook_signature_key' => defined('SQUARE_WEBHOOK_SIGNATURE_KEY') ? SQUARE_WEBHOOK_SIGNATURE_KEY : ''
|
||||
]);
|
||||
|
||||
$methods = getSetting('payment_methods', [
|
||||
'card' => true,
|
||||
'cash' => true,
|
||||
@@ -70,14 +91,70 @@ $methods = getSetting('payment_methods', [
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div>
|
||||
<!-- Stripe Settings -->
|
||||
<!-- Square Settings -->
|
||||
<form method="POST">
|
||||
<input type="hidden" name="section" value="square">
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-header">
|
||||
<h3 class="admin-card-title"><i class="fas fa-square" style="color: #006AFF;"></i> Square</h3>
|
||||
</div>
|
||||
<div class="admin-card-body">
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="square_enabled" <?= $square['enabled'] ? 'checked' : '' ?>>
|
||||
Enable Square payments
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="square_sandbox" <?= $square['sandbox'] ? 'checked' : '' ?>>
|
||||
Sandbox mode (use sandbox app/location/token)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">Application ID</label>
|
||||
<input type="text" name="square_app_id" class="form-input"
|
||||
value="<?= htmlspecialchars($square['app_id']) ?>"
|
||||
placeholder="sq0idp-...">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">Location ID</label>
|
||||
<input type="text" name="square_location_id" class="form-input"
|
||||
value="<?= htmlspecialchars($square['location_id']) ?>"
|
||||
placeholder="L...">
|
||||
</div>
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">Access Token</label>
|
||||
<input type="password" name="square_access_token" class="form-input"
|
||||
value="<?= htmlspecialchars($square['access_token']) ?>"
|
||||
placeholder="EAAA...">
|
||||
</div>
|
||||
|
||||
<div class="form-group mb-0">
|
||||
<label class="form-label">Webhook Signature Key</label>
|
||||
<input type="password" name="square_webhook_signature_key" class="form-input"
|
||||
value="<?= htmlspecialchars($square['webhook_signature_key']) ?>"
|
||||
placeholder="...">
|
||||
<small class="text-muted">From the Square Developer Dashboard's webhook subscription for this site</small>
|
||||
</div>
|
||||
|
||||
<button type="submit" class="btn btn-primary mt-2">Save Square Settings</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<!-- Stripe Settings (legacy) -->
|
||||
<form method="POST">
|
||||
<input type="hidden" name="section" value="stripe">
|
||||
<div class="admin-card">
|
||||
<div class="admin-card-header">
|
||||
<h3 class="admin-card-title"><i class="fab fa-stripe" style="color: #635BFF;"></i> Stripe</h3>
|
||||
<h3 class="admin-card-title"><i class="fab fa-stripe" style="color: #635BFF;"></i> Stripe <small class="text-muted">(legacy)</small></h3>
|
||||
</div>
|
||||
<div class="admin-card-body">
|
||||
<div class="form-group">
|
||||
@@ -86,41 +163,41 @@ $methods = getSetting('payment_methods', [
|
||||
Enable Stripe payments
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="stripe_test_mode" <?= $stripe['test_mode'] ? 'checked' : '' ?>>
|
||||
Test mode (use test keys)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">Publishable Key</label>
|
||||
<input type="text" name="stripe_publishable_key" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['publishable_key']) ?>"
|
||||
<input type="text" name="stripe_publishable_key" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['publishable_key']) ?>"
|
||||
placeholder="pk_test_... or pk_live_...">
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label class="form-label">Secret Key</label>
|
||||
<input type="password" name="stripe_secret_key" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['secret_key']) ?>"
|
||||
<input type="password" name="stripe_secret_key" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['secret_key']) ?>"
|
||||
placeholder="sk_test_... or sk_live_...">
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group mb-0">
|
||||
<label class="form-label">Webhook Secret</label>
|
||||
<input type="password" name="stripe_webhook_secret" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['webhook_secret']) ?>"
|
||||
<input type="password" name="stripe_webhook_secret" class="form-input"
|
||||
value="<?= htmlspecialchars($stripe['webhook_secret']) ?>"
|
||||
placeholder="whsec_...">
|
||||
<small class="text-muted">Get this from your Stripe webhook settings</small>
|
||||
</div>
|
||||
|
||||
|
||||
<button type="submit" class="btn btn-primary mt-2">Save Stripe Settings</button>
|
||||
</div>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
|
||||
<!-- POS Payment Methods -->
|
||||
<form method="POST">
|
||||
<input type="hidden" name="section" value="methods">
|
||||
@@ -130,35 +207,35 @@ $methods = getSetting('payment_methods', [
|
||||
</div>
|
||||
<div class="admin-card-body">
|
||||
<p class="text-muted" style="margin-bottom: 1rem;">Select which payment methods are available in the Point of Sale system.</p>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="method_card" <?= $methods['card'] ? 'checked' : '' ?>>
|
||||
<i class="fas fa-credit-card"></i> Card (Terminal)
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="method_cash" <?= $methods['cash'] ? 'checked' : '' ?>>
|
||||
<i class="fas fa-money-bill"></i> Cash
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="method_wallet" <?= $methods['wallet'] ? 'checked' : '' ?>>
|
||||
<i class="fas fa-wallet"></i> Customer Wallet
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="form-group mb-0">
|
||||
<label style="display: flex; align-items: center; gap: 0.5rem; cursor: pointer;">
|
||||
<input type="checkbox" name="method_gift_card" <?= $methods['gift_card'] ? 'checked' : '' ?>>
|
||||
<i class="fas fa-gift"></i> Gift Card
|
||||
</label>
|
||||
</div>
|
||||
|
||||
|
||||
<button type="submit" class="btn btn-primary mt-2">Save Payment Methods</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Create Stripe Checkout Session API
|
||||
* Uses hosted checkout page (redirects to Stripe)
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/stripe.php';
|
||||
require_once __DIR__ . '/../includes/loyalty.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Only accept POST
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['error' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$orderId = $input['order_id'] ?? '';
|
||||
$originUrl = $input['origin_url'] ?? '';
|
||||
|
||||
if (empty($orderId)) {
|
||||
jsonResponse(['error' => 'Order ID required'], 400);
|
||||
}
|
||||
|
||||
if (empty($originUrl)) {
|
||||
$originUrl = SITE_URL;
|
||||
}
|
||||
|
||||
// Get order
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
jsonResponse(['error' => 'Order not found'], 404);
|
||||
}
|
||||
|
||||
if ($order['payment_status'] === 'paid') {
|
||||
jsonResponse(['error' => 'Order already paid'], 400);
|
||||
}
|
||||
|
||||
// Check if Stripe is configured
|
||||
if (!isStripeConfigured()) {
|
||||
// Demo mode - simulate successful payment
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'stripe_payment_intent' => 'demo_' . bin2hex(random_bytes(8))
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
if (!empty($order['customer_id'])) {
|
||||
loyalty()->awardPoints(
|
||||
$order['customer_id'],
|
||||
(float) $order['total'],
|
||||
'Order #' . $order['order_number'],
|
||||
$orderId
|
||||
);
|
||||
}
|
||||
|
||||
jsonResponse([
|
||||
'demo_mode' => true,
|
||||
'message' => 'Payment simulated (Stripe not configured)',
|
||||
'redirect' => '/order-confirmation.php?order=' . $orderId
|
||||
]);
|
||||
}
|
||||
|
||||
// Build line items from order
|
||||
$items = json_decode($order['items'], true) ?? [];
|
||||
$lineItems = [];
|
||||
|
||||
foreach ($items as $item) {
|
||||
$lineItems[] = [
|
||||
'name' => $item['name'],
|
||||
'price' => floatval($item['price']),
|
||||
'quantity' => intval($item['quantity']),
|
||||
'currency' => 'usd'
|
||||
];
|
||||
}
|
||||
|
||||
// Add shipping if applicable
|
||||
if ($order['shipping_cost'] > 0) {
|
||||
$lineItems[] = [
|
||||
'name' => 'Shipping',
|
||||
'price' => floatval($order['shipping_cost']),
|
||||
'quantity' => 1,
|
||||
'currency' => 'usd'
|
||||
];
|
||||
}
|
||||
|
||||
// Build success/cancel URLs
|
||||
$successUrl = rtrim($originUrl, '/') . '/order-confirmation.php?order=' . $orderId . '&session_id={CHECKOUT_SESSION_ID}';
|
||||
$cancelUrl = rtrim($originUrl, '/') . '/payment.php?order=' . $orderId . '&cancelled=1';
|
||||
|
||||
try {
|
||||
$session = stripe()->createCheckoutSession(
|
||||
$lineItems,
|
||||
$successUrl,
|
||||
$cancelUrl,
|
||||
[
|
||||
'customer_email' => $order['customer_email'],
|
||||
'metadata' => [
|
||||
'order_id' => $orderId,
|
||||
'order_number' => $order['order_number']
|
||||
]
|
||||
]
|
||||
);
|
||||
|
||||
// Store checkout session ID
|
||||
db()->update('orders',
|
||||
['stripe_session_id' => $session['id']],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
jsonResponse([
|
||||
'url' => $session['url'],
|
||||
'session_id' => $session['id']
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log('Stripe Checkout error: ' . $e->getMessage());
|
||||
jsonResponse(['error' => 'Failed to create checkout session: ' . $e->getMessage()], 500);
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Create Stripe Payment Intent API
|
||||
* Uses cURL-based Stripe integration (no Composer required)
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/stripe.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Only accept POST
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['error' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$orderId = $input['order_id'] ?? '';
|
||||
|
||||
if (empty($orderId)) {
|
||||
jsonResponse(['error' => 'Order ID required'], 400);
|
||||
}
|
||||
|
||||
// Get order
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
jsonResponse(['error' => 'Order not found'], 404);
|
||||
}
|
||||
|
||||
if ($order['payment_status'] === 'paid') {
|
||||
jsonResponse(['error' => 'Order already paid'], 400);
|
||||
}
|
||||
|
||||
// Check if Stripe is configured
|
||||
if (!isStripeConfigured()) {
|
||||
// Demo mode - simulate successful payment
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'stripe_payment_intent' => 'demo_' . bin2hex(random_bytes(8))
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
jsonResponse([
|
||||
'demo_mode' => true,
|
||||
'message' => 'Payment simulated (Stripe not configured)',
|
||||
'redirect' => '/order-confirmation.php?order=' . $orderId
|
||||
]);
|
||||
}
|
||||
|
||||
// Create Stripe Payment Intent using cURL-based API
|
||||
try {
|
||||
$paymentIntent = stripe()->createPaymentIntent(
|
||||
$order['total'],
|
||||
'usd',
|
||||
[
|
||||
'metadata' => [
|
||||
'order_id' => $orderId,
|
||||
'order_number' => $order['order_number']
|
||||
],
|
||||
'receipt_email' => $order['customer_email'],
|
||||
'description' => 'Order #' . $order['order_number']
|
||||
]
|
||||
);
|
||||
|
||||
// Store payment intent ID
|
||||
db()->update('orders',
|
||||
['stripe_payment_intent' => $paymentIntent['id']],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
jsonResponse([
|
||||
'client_secret' => $paymentIntent['client_secret']
|
||||
]);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log('Stripe error: ' . $e->getMessage());
|
||||
jsonResponse(['error' => 'Payment initialization failed: ' . $e->getMessage()], 500);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Create Square Payment API
|
||||
* Accepts a Web Payments SDK card nonce (source_id) and charges it synchronously.
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/square.php';
|
||||
require_once __DIR__ . '/../includes/loyalty.php';
|
||||
require_once __DIR__ . '/../includes/email.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
|
||||
jsonResponse(['error' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
$input = json_decode(file_get_contents('php://input'), true);
|
||||
$orderId = $input['order_id'] ?? '';
|
||||
$sourceId = $input['source_id'] ?? '';
|
||||
|
||||
if (empty($orderId)) {
|
||||
jsonResponse(['error' => 'Order ID required'], 400);
|
||||
}
|
||||
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
jsonResponse(['error' => 'Order not found'], 404);
|
||||
}
|
||||
|
||||
if ($order['payment_status'] === 'paid') {
|
||||
jsonResponse(['error' => 'Order already paid'], 400);
|
||||
}
|
||||
|
||||
// Demo mode - Square not configured
|
||||
if (!isSquareConfigured()) {
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'square_payment_id' => 'demo_' . bin2hex(random_bytes(8)),
|
||||
'payment_method' => 'square',
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
jsonResponse([
|
||||
'demo_mode' => true,
|
||||
'message' => 'Payment simulated (Square not configured)',
|
||||
'redirect' => '/order-confirmation.php?order=' . $orderId
|
||||
]);
|
||||
}
|
||||
|
||||
if (empty($sourceId)) {
|
||||
jsonResponse(['error' => 'Card details required'], 400);
|
||||
}
|
||||
|
||||
try {
|
||||
$result = squareCreatePayment(
|
||||
$sourceId,
|
||||
(float) $order['total'],
|
||||
$orderId,
|
||||
['note' => 'Order #' . $order['order_number']]
|
||||
);
|
||||
$payment = $result['payment'] ?? [];
|
||||
$status = $payment['status'] ?? '';
|
||||
|
||||
if ($status === 'COMPLETED') {
|
||||
markSquarePaymentResult($payment['id'], $orderId, 'COMPLETED');
|
||||
jsonResponse([
|
||||
'success' => true,
|
||||
'redirect' => '/order-confirmation.php?order=' . $orderId
|
||||
]);
|
||||
}
|
||||
|
||||
// Store the payment id even if not yet completed, so the reconciliation
|
||||
// poll and webhook can find this order by square_payment_id.
|
||||
db()->update('orders',
|
||||
['square_payment_id' => $payment['id'] ?? null],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
jsonResponse(['error' => 'Payment was not completed (status: ' . $status . ')'], 400);
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log('Square payment error: ' . $e->getMessage());
|
||||
jsonResponse(['error' => 'Payment failed: ' . $e->getMessage()], 500);
|
||||
}
|
||||
+46
-110
@@ -1,157 +1,93 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Check Payment Status API
|
||||
* Polls Stripe for payment/checkout session status
|
||||
* Reconciliation-only fallback: Square payments complete synchronously in
|
||||
* create-square-payment.php, so this endpoint only matters if the browser
|
||||
* lost that response after Square had already accepted the charge. It shares
|
||||
* markSquarePaymentResult() with the webhook and the synchronous path so
|
||||
* loyalty points/emails are never duplicated no matter which path resolves first.
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/stripe.php';
|
||||
require_once __DIR__ . '/../includes/square.php';
|
||||
require_once __DIR__ . '/../includes/loyalty.php';
|
||||
require_once __DIR__ . '/../includes/email.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
// Only accept GET
|
||||
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
|
||||
jsonResponse(['error' => 'Method not allowed'], 405);
|
||||
}
|
||||
|
||||
$orderId = $_GET['order_id'] ?? '';
|
||||
$sessionId = $_GET['session_id'] ?? '';
|
||||
|
||||
if (empty($orderId) && empty($sessionId)) {
|
||||
jsonResponse(['error' => 'Order ID or Session ID required'], 400);
|
||||
if (empty($orderId)) {
|
||||
jsonResponse(['error' => 'Order ID required'], 400);
|
||||
}
|
||||
|
||||
// Get order by ID or session
|
||||
if (!empty($orderId)) {
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
);
|
||||
} else {
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE stripe_session_id = :session OR stripe_payment_intent = :session",
|
||||
['session' => $sessionId]
|
||||
);
|
||||
}
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
);
|
||||
|
||||
if (!$order) {
|
||||
jsonResponse(['error' => 'Order not found'], 404);
|
||||
}
|
||||
|
||||
// If already marked as paid, return success
|
||||
if ($order['payment_status'] === 'paid') {
|
||||
jsonResponse([
|
||||
'status' => 'complete',
|
||||
'status' => 'complete',
|
||||
'payment_status' => 'paid',
|
||||
'order_id' => $order['order_id'],
|
||||
'order_number' => $order['order_number'],
|
||||
'redirect' => '/order-confirmation.php?order=' . $order['order_id']
|
||||
'order_id' => $order['order_id'],
|
||||
'order_number' => $order['order_number'],
|
||||
'redirect' => '/order-confirmation.php?order=' . $order['order_id']
|
||||
]);
|
||||
}
|
||||
|
||||
// Check if Stripe is configured
|
||||
if (!isStripeConfigured()) {
|
||||
if (!isSquareConfigured()) {
|
||||
jsonResponse([
|
||||
'status' => 'demo_mode',
|
||||
'status' => 'demo_mode',
|
||||
'payment_status' => $order['payment_status'],
|
||||
'message' => 'Stripe not configured - running in demo mode'
|
||||
'message' => 'Square not configured - running in demo mode'
|
||||
]);
|
||||
}
|
||||
|
||||
if (empty($order['square_payment_id'])) {
|
||||
jsonResponse([
|
||||
'status' => 'pending',
|
||||
'payment_status' => $order['payment_status']
|
||||
]);
|
||||
}
|
||||
|
||||
try {
|
||||
// Check with Stripe
|
||||
if (!empty($order['stripe_session_id'])) {
|
||||
// Check checkout session status
|
||||
$session = stripe()->getCheckoutSession($order['stripe_session_id']);
|
||||
|
||||
if ($session['payment_status'] === 'paid') {
|
||||
// Update order
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'stripe_payment_intent' => $session['payment_intent'] ?? null
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $order['order_id']]
|
||||
);
|
||||
$result = squareGetPayment($order['square_payment_id']);
|
||||
$payment = $result['payment'] ?? [];
|
||||
$status = $payment['status'] ?? '';
|
||||
|
||||
// Award loyalty points
|
||||
if (!empty($order['customer_id'])) {
|
||||
loyalty()->awardPoints(
|
||||
$order['customer_id'],
|
||||
(float) $order['total'],
|
||||
'Order #' . $order['order_number'],
|
||||
$order['order_id']
|
||||
);
|
||||
}
|
||||
markSquarePaymentResult($order['square_payment_id'], $order['order_id'], $status);
|
||||
|
||||
jsonResponse([
|
||||
'status' => 'complete',
|
||||
'payment_status' => 'paid',
|
||||
'order_id' => $order['order_id'],
|
||||
'order_number' => $order['order_number'],
|
||||
'redirect' => '/order-confirmation.php?order=' . $order['order_id']
|
||||
]);
|
||||
}
|
||||
|
||||
$updated = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $order['order_id']]);
|
||||
|
||||
if ($updated['payment_status'] === 'paid') {
|
||||
jsonResponse([
|
||||
'status' => $session['status'],
|
||||
'payment_status' => $session['payment_status']
|
||||
]);
|
||||
|
||||
} elseif (!empty($order['stripe_payment_intent'])) {
|
||||
// Check payment intent status
|
||||
$paymentIntent = stripe()->getPaymentIntent($order['stripe_payment_intent']);
|
||||
|
||||
if ($paymentIntent['status'] === 'succeeded') {
|
||||
// Update order
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed'
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $order['order_id']]
|
||||
);
|
||||
|
||||
// Award loyalty points
|
||||
if (!empty($order['customer_id'])) {
|
||||
loyalty()->awardPoints(
|
||||
$order['customer_id'],
|
||||
(float) $order['total'],
|
||||
'Order #' . $order['order_number'],
|
||||
$order['order_id']
|
||||
);
|
||||
}
|
||||
|
||||
jsonResponse([
|
||||
'status' => 'complete',
|
||||
'payment_status' => 'paid',
|
||||
'order_id' => $order['order_id'],
|
||||
'order_number' => $order['order_number'],
|
||||
'redirect' => '/order-confirmation.php?order=' . $order['order_id']
|
||||
]);
|
||||
}
|
||||
|
||||
jsonResponse([
|
||||
'status' => $paymentIntent['status'],
|
||||
'payment_status' => 'pending'
|
||||
'status' => 'complete',
|
||||
'payment_status' => 'paid',
|
||||
'order_id' => $updated['order_id'],
|
||||
'order_number' => $updated['order_number'],
|
||||
'redirect' => '/order-confirmation.php?order=' . $updated['order_id']
|
||||
]);
|
||||
}
|
||||
|
||||
// No Stripe reference found
|
||||
|
||||
jsonResponse([
|
||||
'status' => 'pending',
|
||||
'payment_status' => $order['payment_status']
|
||||
'status' => $status,
|
||||
'payment_status' => $updated['payment_status']
|
||||
]);
|
||||
|
||||
|
||||
} catch (Exception $e) {
|
||||
error_log('Payment status check error: ' . $e->getMessage());
|
||||
error_log('Square payment status check error: ' . $e->getMessage());
|
||||
jsonResponse([
|
||||
'status' => 'error',
|
||||
'status' => 'error',
|
||||
'payment_status' => $order['payment_status'],
|
||||
'error' => 'Failed to check payment status'
|
||||
'error' => 'Failed to check payment status'
|
||||
]);
|
||||
}
|
||||
|
||||
+37
-80
@@ -1,107 +1,65 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Stripe Webhook Handler
|
||||
* Uses cURL-based Stripe integration (no Composer required)
|
||||
* Tom's Java Jive - Square Webhook Handler
|
||||
*/
|
||||
|
||||
require_once __DIR__ . '/../includes/functions.php';
|
||||
require_once __DIR__ . '/../includes/stripe.php';
|
||||
require_once __DIR__ . '/../includes/square.php';
|
||||
require_once __DIR__ . '/../includes/loyalty.php';
|
||||
require_once __DIR__ . '/../includes/email.php';
|
||||
|
||||
header('Content-Type: application/json');
|
||||
|
||||
$payload = file_get_contents('php://input');
|
||||
$sigHeader = $_SERVER['HTTP_STRIPE_SIGNATURE'] ?? '';
|
||||
$sigHeader = $_SERVER['HTTP_X_SQUARE_HMACSHA256_SIGNATURE'] ?? '';
|
||||
$notificationUrl = SITE_URL . '/api/webhook.php';
|
||||
|
||||
// Verify webhook signature (if secret is configured)
|
||||
if (!empty(STRIPE_WEBHOOK_SECRET) && STRIPE_WEBHOOK_SECRET !== 'whsec_your_webhook_secret') {
|
||||
try {
|
||||
stripe()->verifyWebhookSignature($payload, $sigHeader, STRIPE_WEBHOOK_SECRET);
|
||||
$event = json_decode($payload, true);
|
||||
} catch (Exception $e) {
|
||||
error_log('Stripe webhook signature verification failed: ' . $e->getMessage());
|
||||
http_response_code(400);
|
||||
exit();
|
||||
}
|
||||
} else {
|
||||
$event = json_decode($payload, true);
|
||||
if (!$event) {
|
||||
http_response_code(400);
|
||||
exit();
|
||||
}
|
||||
if (empty(SQUARE_WEBHOOK_SIGNATURE_KEY) || SQUARE_WEBHOOK_SIGNATURE_KEY === 'REPLACE_ME') {
|
||||
error_log('Square webhook signature key not configured - rejecting webhook');
|
||||
http_response_code(400);
|
||||
exit();
|
||||
}
|
||||
|
||||
if (!verifySquareWebhookSignature($payload, $sigHeader, $notificationUrl, SQUARE_WEBHOOK_SIGNATURE_KEY)) {
|
||||
error_log('Square webhook signature verification failed');
|
||||
http_response_code(400);
|
||||
exit();
|
||||
}
|
||||
|
||||
$event = json_decode($payload, true);
|
||||
if (!$event) {
|
||||
http_response_code(400);
|
||||
exit();
|
||||
}
|
||||
|
||||
$eventType = $event['type'] ?? '';
|
||||
$data = $event['data']['object'] ?? [];
|
||||
|
||||
switch ($eventType) {
|
||||
|
||||
case 'checkout.session.completed':
|
||||
// Stripe Checkout (hosted page) — metadata is on the session
|
||||
$orderId = $data['metadata']['order_id'] ?? '';
|
||||
$paymentIntentId = $data['payment_intent'] ?? '';
|
||||
if ($orderId && ($data['payment_status'] ?? '') === 'paid') {
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'stripe_payment_intent' => $paymentIntentId,
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
$order = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $orderId]);
|
||||
if ($order) {
|
||||
emailService()->sendOrderConfirmation($order);
|
||||
}
|
||||
case 'payment.updated':
|
||||
case 'payment.created':
|
||||
$payment = $event['data']['object']['payment'] ?? [];
|
||||
$paymentId = $payment['id'] ?? '';
|
||||
$status = $payment['status'] ?? '';
|
||||
$orderId = $payment['reference_id'] ?? null;
|
||||
if ($paymentId && $status) {
|
||||
markSquarePaymentResult($paymentId, $orderId, $status);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'payment_intent.succeeded':
|
||||
// Payment Intent flow (embedded/direct) - skip if already confirmed by checkout.session.completed
|
||||
$paymentIntentId = $data['id'] ?? '';
|
||||
$orderId = $data['metadata']['order_id'] ?? '';
|
||||
if ($orderId && ($data['status'] ?? '') === 'succeeded') {
|
||||
$order = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $orderId]);
|
||||
if ($order && $order['order_status'] !== 'confirmed') {
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'stripe_payment_intent' => $paymentIntentId,
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
$order = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $orderId]);
|
||||
if ($order) {
|
||||
emailService()->sendOrderConfirmation($order);
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'payment_intent.payment_failed':
|
||||
$orderId = $data['metadata']['order_id'] ?? '';
|
||||
if ($orderId) {
|
||||
db()->update('orders',
|
||||
['payment_status' => 'failed'],
|
||||
'order_id = :id',
|
||||
['id' => $orderId]
|
||||
);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'charge.refunded':
|
||||
$paymentIntentId = $data['payment_intent'] ?? '';
|
||||
if ($paymentIntentId) {
|
||||
case 'refund.updated':
|
||||
case 'refund.created':
|
||||
$refund = $event['data']['object']['refund'] ?? [];
|
||||
$paymentId = $refund['payment_id'] ?? '';
|
||||
$status = $refund['status'] ?? '';
|
||||
if ($status === 'COMPLETED' && $paymentId) {
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'refunded',
|
||||
'order_status' => 'refunded',
|
||||
],
|
||||
'stripe_payment_intent = :pi',
|
||||
['pi' => $paymentIntentId]
|
||||
'square_payment_id = :pid',
|
||||
['pid' => $paymentId]
|
||||
);
|
||||
}
|
||||
break;
|
||||
@@ -109,4 +67,3 @@ switch ($eventType) {
|
||||
|
||||
http_response_code(200);
|
||||
echo json_encode(['received' => true]);
|
||||
|
||||
|
||||
@@ -326,6 +326,8 @@ CREATE TABLE `orders` (
|
||||
`order_status` enum('pending','confirmed','processing','shipped','delivered','cancelled','refunded') DEFAULT 'pending',
|
||||
`stripe_session_id` varchar(255) DEFAULT NULL,
|
||||
`stripe_payment_intent` varchar(255) DEFAULT NULL,
|
||||
`square_payment_id` varchar(255) DEFAULT NULL,
|
||||
`square_order_id` varchar(255) DEFAULT NULL,
|
||||
`tracking_number` varchar(100) DEFAULT NULL,
|
||||
`tracking_url` varchar(500) DEFAULT NULL,
|
||||
`notes` text DEFAULT NULL,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Square Integration (cURL-based, no SDK required)
|
||||
*/
|
||||
|
||||
function squareApi(string $method, string $path, array $body = []): array {
|
||||
$base = (defined('SQUARE_ENV') && SQUARE_ENV === 'sandbox')
|
||||
? 'https://connect.squareupsandbox.com/v2'
|
||||
: 'https://connect.squareup.com/v2';
|
||||
|
||||
$ch = curl_init($base . $path);
|
||||
$opts = [
|
||||
CURLOPT_RETURNTRANSFER => true,
|
||||
CURLOPT_TIMEOUT => 30,
|
||||
CURLOPT_SSL_VERIFYPEER => true,
|
||||
CURLOPT_HTTPHEADER => [
|
||||
'Content-Type: application/json',
|
||||
'Authorization: Bearer ' . SQUARE_ACCESS_TOKEN,
|
||||
'Square-Version: 2024-01-18',
|
||||
],
|
||||
];
|
||||
if ($method !== 'GET') {
|
||||
$opts[CURLOPT_CUSTOMREQUEST] = $method;
|
||||
$opts[CURLOPT_POSTFIELDS] = json_encode($body ?: new stdClass());
|
||||
}
|
||||
curl_setopt_array($ch, $opts);
|
||||
|
||||
$resp = curl_exec($ch);
|
||||
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
|
||||
$err = curl_error($ch);
|
||||
curl_close($ch);
|
||||
|
||||
if ($err) {
|
||||
throw new Exception('Square API connection error: ' . $err);
|
||||
}
|
||||
|
||||
$decoded = json_decode($resp ?: '{}', true);
|
||||
|
||||
if (!empty($decoded['errors'])) {
|
||||
$msg = $decoded['errors'][0]['detail'] ?? ($decoded['errors'][0]['code'] ?? 'Unknown Square error');
|
||||
throw new Exception($msg);
|
||||
}
|
||||
|
||||
if ($httpCode >= 400) {
|
||||
throw new Exception('Square API error (HTTP ' . $httpCode . ')');
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a payment. $sourceId is the nonce from the Web Payments SDK's tokenize() call.
|
||||
*/
|
||||
function squareCreatePayment(string $sourceId, float $amount, string $referenceId, array $options = []): array {
|
||||
$body = [
|
||||
'source_id' => $sourceId,
|
||||
'idempotency_key' => $referenceId . '_' . bin2hex(random_bytes(8)),
|
||||
'amount_money' => [
|
||||
'amount' => (int) round($amount * 100),
|
||||
'currency' => 'USD',
|
||||
],
|
||||
'location_id' => SQUARE_LOCATION_ID,
|
||||
'autocomplete' => true,
|
||||
'reference_id' => $referenceId,
|
||||
];
|
||||
if (!empty($options['note'])) {
|
||||
$body['note'] = $options['note'];
|
||||
}
|
||||
return squareApi('POST', '/payments', $body);
|
||||
}
|
||||
|
||||
function squareGetPayment(string $paymentId): array {
|
||||
return squareApi('GET', '/payments/' . $paymentId);
|
||||
}
|
||||
|
||||
function isSquareConfigured(): bool {
|
||||
return defined('SQUARE_ACCESS_TOKEN') && defined('SQUARE_APP_ID') && defined('SQUARE_LOCATION_ID')
|
||||
&& !empty(SQUARE_ACCESS_TOKEN) && !empty(SQUARE_APP_ID) && !empty(SQUARE_LOCATION_ID)
|
||||
&& SQUARE_ACCESS_TOKEN !== 'REPLACE_ME';
|
||||
}
|
||||
|
||||
/**
|
||||
* Square's webhook signature: base64(HMAC-SHA256(notification_url . raw_body, signature_key)).
|
||||
* The notification URL must exactly match what's configured in the Square Dashboard subscription.
|
||||
*/
|
||||
function verifySquareWebhookSignature(string $payload, string $signature, string $notificationUrl, string $signatureKey): bool {
|
||||
if (empty($signatureKey) || empty($signature)) {
|
||||
return false;
|
||||
}
|
||||
$expected = base64_encode(hash_hmac('sha256', $notificationUrl . $payload, $signatureKey, true));
|
||||
return hash_equals($expected, $signature);
|
||||
}
|
||||
|
||||
/**
|
||||
* Single source of truth for "an order's Square payment resolved" — called from the
|
||||
* synchronous create-payment response, the webhook, and the reconciliation poll, so
|
||||
* loyalty points/emails are never awarded or sent more than once regardless of which
|
||||
* path resolves the order first.
|
||||
*/
|
||||
function markSquarePaymentResult(string $paymentId, ?string $orderId, string $status): void {
|
||||
$order = $orderId
|
||||
? db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $orderId])
|
||||
: db()->fetch("SELECT * FROM orders WHERE square_payment_id = :pid", ['pid' => $paymentId]);
|
||||
|
||||
if (!$order) {
|
||||
return;
|
||||
}
|
||||
|
||||
if ($status === 'COMPLETED') {
|
||||
if ($order['order_status'] !== 'confirmed') {
|
||||
db()->update('orders',
|
||||
[
|
||||
'payment_status' => 'paid',
|
||||
'order_status' => 'confirmed',
|
||||
'square_payment_id' => $paymentId,
|
||||
'payment_method' => 'square',
|
||||
],
|
||||
'order_id = :id',
|
||||
['id' => $order['order_id']]
|
||||
);
|
||||
|
||||
if (!empty($order['customer_id'])) {
|
||||
loyalty()->awardPoints(
|
||||
$order['customer_id'],
|
||||
(float) $order['total'],
|
||||
'Order #' . $order['order_number'],
|
||||
$order['order_id']
|
||||
);
|
||||
}
|
||||
|
||||
$updated = db()->fetch("SELECT * FROM orders WHERE order_id = :id", ['id' => $order['order_id']]);
|
||||
if ($updated) {
|
||||
emailService()->sendOrderConfirmation($updated);
|
||||
}
|
||||
}
|
||||
} elseif (in_array($status, ['FAILED', 'CANCELED'], true)) {
|
||||
db()->update('orders',
|
||||
['payment_status' => 'failed'],
|
||||
'order_id = :id',
|
||||
['id' => $order['order_id']]
|
||||
);
|
||||
}
|
||||
}
|
||||
+188
-111
@@ -1,13 +1,20 @@
|
||||
<?php
|
||||
/**
|
||||
* Tom's Java Jive - Payment Page (Stripe)
|
||||
* Supports both PaymentIntent (card element) and Checkout Session (redirect) flows
|
||||
* Tom's Java Jive - Payment Page
|
||||
* Supports Stripe (legacy) or Square, gated by the PAYMENT_PROCESSOR constant.
|
||||
*/
|
||||
|
||||
$pageTitle = "Payment - Tom's Java Jive";
|
||||
require_once __DIR__ . '/includes/functions.php';
|
||||
require_once __DIR__ . '/includes/auth.php';
|
||||
require_once __DIR__ . '/includes/stripe.php';
|
||||
|
||||
$processor = defined('PAYMENT_PROCESSOR') ? PAYMENT_PROCESSOR : 'stripe';
|
||||
|
||||
if ($processor === 'square') {
|
||||
require_once __DIR__ . '/includes/square.php';
|
||||
} else {
|
||||
require_once __DIR__ . '/includes/stripe.php';
|
||||
}
|
||||
|
||||
$orderId = $_GET['order'] ?? $_SESSION['pending_order_id'] ?? '';
|
||||
$cancelled = isset($_GET['cancelled']);
|
||||
@@ -16,7 +23,6 @@ if (empty($orderId)) {
|
||||
redirect('/cart.php');
|
||||
}
|
||||
|
||||
// Get order
|
||||
$order = db()->fetch(
|
||||
"SELECT * FROM orders WHERE order_id = :id",
|
||||
['id' => $orderId]
|
||||
@@ -26,16 +32,20 @@ if (!$order) {
|
||||
redirect('/cart.php');
|
||||
}
|
||||
|
||||
// If already paid, redirect to confirmation
|
||||
if ($order['payment_status'] === 'paid') {
|
||||
clearCart();
|
||||
redirect('/order-confirmation.php?order=' . $orderId);
|
||||
}
|
||||
|
||||
$stripePublishableKey = STRIPE_PUBLISHABLE_KEY;
|
||||
$stripeConfigured = isStripeConfigured();
|
||||
$total = $order['total'];
|
||||
|
||||
if ($processor === 'square') {
|
||||
$squareConfigured = isSquareConfigured();
|
||||
} else {
|
||||
$stripePublishableKey = STRIPE_PUBLISHABLE_KEY;
|
||||
$stripeConfigured = isStripeConfigured();
|
||||
}
|
||||
|
||||
require_once __DIR__ . '/includes/header.php';
|
||||
?>
|
||||
|
||||
@@ -51,7 +61,7 @@ require_once __DIR__ . '/includes/header.php';
|
||||
<i class="fas fa-exclamation-triangle"></i> Payment was cancelled. Please try again.
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
|
||||
|
||||
<div style="background: var(--color-background); padding: 1rem; border-radius: var(--radius-md); margin-bottom: 1.5rem;">
|
||||
<div style="display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
|
||||
<span>Order #<?= htmlspecialchars($order['order_number']) ?></span>
|
||||
@@ -61,47 +71,76 @@ require_once __DIR__ . '/includes/header.php';
|
||||
<?= htmlspecialchars($order['customer_email']) ?>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<?php if (!$stripeConfigured): ?>
|
||||
<!-- Demo Mode - No Stripe Keys -->
|
||||
<div class="alert alert-info mb-2">
|
||||
<i class="fas fa-info-circle"></i> <strong>Demo Mode:</strong> Stripe is not configured. Click below to simulate a successful payment.
|
||||
</div>
|
||||
<form id="demo-payment-form">
|
||||
<button type="submit" id="demo-submit" class="btn btn-primary btn-lg btn-block">
|
||||
<span id="demo-text">Complete Demo Payment <?= formatCurrency($total) ?></span>
|
||||
<span id="demo-spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<!-- Stripe Payment Options -->
|
||||
<div class="payment-options mb-2">
|
||||
<button type="button" id="checkout-btn" class="btn btn-primary btn-lg btn-block mb-1">
|
||||
<i class="fas fa-credit-card"></i> Pay with Stripe Checkout
|
||||
</button>
|
||||
<p class="text-muted text-center" style="font-size: 0.875rem;">or enter card details below</p>
|
||||
</div>
|
||||
|
||||
<form id="payment-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Card Details</label>
|
||||
<div id="card-element" style="padding: 0.75rem; border: 1px solid var(--color-border); border-radius: var(--radius-md);"></div>
|
||||
<div id="card-errors" class="form-error" style="margin-top: 0.5rem;"></div>
|
||||
|
||||
<?php if ($processor === 'square'): ?>
|
||||
<?php if (!$squareConfigured): ?>
|
||||
<div class="alert alert-info mb-2">
|
||||
<i class="fas fa-info-circle"></i> <strong>Demo Mode:</strong> Square is not configured. Click below to simulate a successful payment.
|
||||
</div>
|
||||
|
||||
<button type="submit" id="submit-button" class="btn btn-secondary btn-lg btn-block">
|
||||
<span id="button-text">Pay <?= formatCurrency($total) ?></span>
|
||||
<span id="spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<form id="demo-payment-form">
|
||||
<button type="submit" id="demo-submit" class="btn btn-primary btn-lg btn-block">
|
||||
<span id="demo-text">Complete Demo Payment <?= formatCurrency($total) ?></span>
|
||||
<span id="demo-spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<form id="payment-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Card Details</label>
|
||||
<div id="card-element" style="padding: 0.75rem; border: 1px solid var(--color-border); border-radius: var(--radius-md);"></div>
|
||||
<div id="card-errors" class="form-error" style="margin-top: 0.5rem;"></div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="submit-button" class="btn btn-secondary btn-lg btn-block">
|
||||
<span id="button-text">Pay <?= formatCurrency($total) ?></span>
|
||||
<span id="spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
<?php else: ?>
|
||||
<?php if (!$stripeConfigured): ?>
|
||||
<div class="alert alert-info mb-2">
|
||||
<i class="fas fa-info-circle"></i> <strong>Demo Mode:</strong> Stripe is not configured. Click below to simulate a successful payment.
|
||||
</div>
|
||||
<form id="demo-payment-form">
|
||||
<button type="submit" id="demo-submit" class="btn btn-primary btn-lg btn-block">
|
||||
<span id="demo-text">Complete Demo Payment <?= formatCurrency($total) ?></span>
|
||||
<span id="demo-spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<?php else: ?>
|
||||
<div class="payment-options mb-2">
|
||||
<button type="button" id="checkout-btn" class="btn btn-primary btn-lg btn-block mb-1">
|
||||
<i class="fas fa-credit-card"></i> Pay with Stripe Checkout
|
||||
</button>
|
||||
<p class="text-muted text-center" style="font-size: 0.875rem;">or enter card details below</p>
|
||||
</div>
|
||||
|
||||
<form id="payment-form">
|
||||
<div class="form-group">
|
||||
<label class="form-label">Card Details</label>
|
||||
<div id="card-element" style="padding: 0.75rem; border: 1px solid var(--color-border); border-radius: var(--radius-md);"></div>
|
||||
<div id="card-errors" class="form-error" style="margin-top: 0.5rem;"></div>
|
||||
</div>
|
||||
|
||||
<button type="submit" id="submit-button" class="btn btn-secondary btn-lg btn-block">
|
||||
<span id="button-text">Pay <?= formatCurrency($total) ?></span>
|
||||
<span id="spinner" style="display: none;">
|
||||
<span class="loading"></span> Processing...
|
||||
</span>
|
||||
</button>
|
||||
</form>
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
|
||||
|
||||
<div id="payment-message" style="display: none; margin-top: 1rem;"></div>
|
||||
|
||||
|
||||
<p class="text-muted text-center mt-2" style="font-size: 0.75rem;">
|
||||
<i class="fas fa-lock"></i> Your payment is secure and encrypted
|
||||
</p>
|
||||
@@ -110,9 +149,12 @@ require_once __DIR__ . '/includes/header.php';
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<?php if ($processor === 'square' && $squareConfigured): ?>
|
||||
<script src="<?= (defined('SQUARE_ENV') && SQUARE_ENV === 'sandbox') ? 'https://sandbox.web.squarecdn.com/v1/square.js' : 'https://web.squarecdn.com/v1/square.js' ?>"></script>
|
||||
<?php endif; ?>
|
||||
|
||||
<script>
|
||||
const orderId = '<?= $orderId ?>';
|
||||
const stripeConfigured = <?= $stripeConfigured ? 'true' : 'false' ?>;
|
||||
const messageEl = document.getElementById('payment-message');
|
||||
|
||||
function showMessage(message, type = 'info') {
|
||||
@@ -121,88 +163,132 @@ function showMessage(message, type = 'info') {
|
||||
messageEl.innerHTML = `<i class="fas fa-${type === 'error' ? 'exclamation-circle' : 'check-circle'}"></i> ${message}`;
|
||||
}
|
||||
|
||||
<?php if (!$stripeConfigured): ?>
|
||||
// Demo mode payment
|
||||
const demoForm = document.getElementById('demo-payment-form');
|
||||
demoForm.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const btn = document.getElementById('demo-submit');
|
||||
const text = document.getElementById('demo-text');
|
||||
const spinner = document.getElementById('demo-spinner');
|
||||
|
||||
btn.disabled = true;
|
||||
text.style.display = 'none';
|
||||
spinner.style.display = 'inline';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/create-payment-intent.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order_id: orderId })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.demo_mode && data.redirect) {
|
||||
showMessage('Payment simulated successfully! Redirecting...', 'success');
|
||||
setTimeout(() => window.location.href = data.redirect, 1000);
|
||||
} else if (data.error) {
|
||||
showMessage(data.error, 'error');
|
||||
function wireDemoForm(endpoint) {
|
||||
const demoForm = document.getElementById('demo-payment-form');
|
||||
demoForm.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
const btn = document.getElementById('demo-submit');
|
||||
const text = document.getElementById('demo-text');
|
||||
const spinner = document.getElementById('demo-spinner');
|
||||
btn.disabled = true;
|
||||
text.style.display = 'none';
|
||||
spinner.style.display = 'inline';
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order_id: orderId })
|
||||
});
|
||||
const data = await response.json();
|
||||
if (data.demo_mode && data.redirect) {
|
||||
showMessage('Payment simulated successfully! Redirecting...', 'success');
|
||||
setTimeout(() => window.location.href = data.redirect, 1000);
|
||||
} else if (data.error) {
|
||||
showMessage(data.error, 'error');
|
||||
btn.disabled = false;
|
||||
text.style.display = 'inline';
|
||||
spinner.style.display = 'none';
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage('Payment failed. Please try again.', 'error');
|
||||
btn.disabled = false;
|
||||
text.style.display = 'inline';
|
||||
spinner.style.display = 'none';
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
<?php if ($processor === 'square'): ?>
|
||||
<?php if (!$squareConfigured): ?>
|
||||
wireDemoForm('/api/create-square-payment.php');
|
||||
<?php else: ?>
|
||||
// Square Web Payments SDK
|
||||
let squareCard;
|
||||
(async function initSquare() {
|
||||
const payments = window.Square.payments('<?= SQUARE_APP_ID ?>', '<?= SQUARE_LOCATION_ID ?>');
|
||||
squareCard = await payments.card();
|
||||
await squareCard.attach('#card-element');
|
||||
})();
|
||||
|
||||
const form = document.getElementById('payment-form');
|
||||
const submitButton = document.getElementById('submit-button');
|
||||
const buttonText = document.getElementById('button-text');
|
||||
const spinner = document.getElementById('spinner');
|
||||
|
||||
form.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
submitButton.disabled = true;
|
||||
buttonText.style.display = 'none';
|
||||
spinner.style.display = 'inline';
|
||||
document.getElementById('card-errors').textContent = '';
|
||||
|
||||
try {
|
||||
const tokenResult = await squareCard.tokenize();
|
||||
if (tokenResult.status !== 'OK') {
|
||||
const msg = (tokenResult.errors && tokenResult.errors[0] && tokenResult.errors[0].message) || 'Card validation failed';
|
||||
document.getElementById('card-errors').textContent = msg;
|
||||
submitButton.disabled = false;
|
||||
buttonText.style.display = 'inline';
|
||||
spinner.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await fetch('/api/create-square-payment.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order_id: orderId, source_id: tokenResult.token })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.demo_mode && data.redirect) {
|
||||
window.location.href = data.redirect;
|
||||
return;
|
||||
}
|
||||
if (data.error) {
|
||||
showMessage(data.error, 'error');
|
||||
submitButton.disabled = false;
|
||||
buttonText.style.display = 'inline';
|
||||
spinner.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
if (data.success && data.redirect) {
|
||||
showMessage('Payment successful! Redirecting...', 'success');
|
||||
setTimeout(() => window.location.href = data.redirect, 1000);
|
||||
}
|
||||
} catch (err) {
|
||||
showMessage('Payment failed. Please try again.', 'error');
|
||||
btn.disabled = false;
|
||||
text.style.display = 'inline';
|
||||
console.error(err);
|
||||
submitButton.disabled = false;
|
||||
buttonText.style.display = 'inline';
|
||||
spinner.style.display = 'none';
|
||||
}
|
||||
});
|
||||
<?php endif; ?>
|
||||
<?php else: ?>
|
||||
<?php if (!$stripeConfigured): ?>
|
||||
wireDemoForm('/api/create-payment-intent.php');
|
||||
<?php else: ?>
|
||||
// Stripe initialized
|
||||
const stripe = Stripe('<?= $stripePublishableKey ?>');
|
||||
const elements = stripe.elements();
|
||||
const cardElement = elements.create('card', {
|
||||
style: {
|
||||
base: {
|
||||
fontSize: '16px',
|
||||
color: '#1B1B1B',
|
||||
'::placeholder': { color: '#9CA3AF' }
|
||||
}
|
||||
}
|
||||
style: { base: { fontSize: '16px', color: '#1B1B1B', '::placeholder': { color: '#9CA3AF' } } }
|
||||
});
|
||||
|
||||
cardElement.mount('#card-element');
|
||||
|
||||
// Handle validation errors
|
||||
cardElement.on('change', function(event) {
|
||||
const displayError = document.getElementById('card-errors');
|
||||
if (event.error) {
|
||||
displayError.textContent = event.error.message;
|
||||
} else {
|
||||
displayError.textContent = '';
|
||||
}
|
||||
displayError.textContent = event.error ? event.error.message : '';
|
||||
});
|
||||
|
||||
// Stripe Checkout button (redirect to hosted page)
|
||||
document.getElementById('checkout-btn').addEventListener('click', async function() {
|
||||
this.disabled = true;
|
||||
this.innerHTML = '<span class="loading"></span> Redirecting to Stripe...';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/create-checkout-session.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
order_id: orderId,
|
||||
origin_url: window.location.origin
|
||||
})
|
||||
body: JSON.stringify({ order_id: orderId, origin_url: window.location.origin })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.demo_mode && data.redirect) {
|
||||
window.location.href = data.redirect;
|
||||
} else if (data.url) {
|
||||
@@ -219,7 +305,6 @@ document.getElementById('checkout-btn').addEventListener('click', async function
|
||||
}
|
||||
});
|
||||
|
||||
// PaymentIntent form (inline card element)
|
||||
const form = document.getElementById('payment-form');
|
||||
const submitButton = document.getElementById('submit-button');
|
||||
const buttonText = document.getElementById('button-text');
|
||||
@@ -227,25 +312,20 @@ const spinner = document.getElementById('spinner');
|
||||
|
||||
form.addEventListener('submit', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
submitButton.disabled = true;
|
||||
buttonText.style.display = 'none';
|
||||
spinner.style.display = 'inline';
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/create-payment-intent.php', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ order_id: orderId })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.demo_mode && data.redirect) {
|
||||
window.location.href = data.redirect;
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.error) {
|
||||
showMessage(data.error, 'error');
|
||||
submitButton.disabled = false;
|
||||
@@ -253,8 +333,6 @@ form.addEventListener('submit', async function(e) {
|
||||
spinner.style.display = 'none';
|
||||
return;
|
||||
}
|
||||
|
||||
// Confirm payment with Stripe
|
||||
const { error, paymentIntent } = await stripe.confirmCardPayment(data.client_secret, {
|
||||
payment_method: {
|
||||
card: cardElement,
|
||||
@@ -264,14 +342,12 @@ form.addEventListener('submit', async function(e) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (error) {
|
||||
showMessage(error.message, 'error');
|
||||
} else if (paymentIntent.status === 'succeeded') {
|
||||
showMessage('Payment successful! Redirecting...', 'success');
|
||||
setTimeout(() => window.location.href = '/order-confirmation.php?order=' + orderId, 1000);
|
||||
}
|
||||
|
||||
} catch (err) {
|
||||
showMessage('Payment failed. Please try again.', 'error');
|
||||
console.error(err);
|
||||
@@ -282,6 +358,7 @@ form.addEventListener('submit', async function(e) {
|
||||
}
|
||||
});
|
||||
<?php endif; ?>
|
||||
<?php endif; ?>
|
||||
</script>
|
||||
|
||||
<?php require_once __DIR__ . '/includes/footer.php'; ?>
|
||||
|
||||
Reference in New Issue
Block a user