mirror of
https://github.com/myronblair/tomsjavajive
synced 2026-07-27 16:52:36 -05:00
11edf3394f
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.
144 lines
5.0 KiB
PHP
144 lines
5.0 KiB
PHP
<?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']]
|
|
);
|
|
}
|
|
}
|