From 0a64c09066d7cbbd70b8c3f922b9df34c7afb490 Mon Sep 17 00:00:00 2001 From: Pauljd Date: Wed, 9 Sep 2026 20:32:51 +0100 Subject: [PATCH] Fixdd additonal issues identified by Davidson CI --- lib/head.php | 2 +- receive-purchase.php | 25 ++++++++++++++++++------- 2 files changed, 19 insertions(+), 8 deletions(-) diff --git a/lib/head.php b/lib/head.php index c474bb6..9875b9e 100644 --- a/lib/head.php +++ b/lib/head.php @@ -35,7 +35,7 @@ function openCheckout(items){ Paddle.Checkout.open({ items: items, - customData: JSON.stringify({user_id: ""}) + customData: {user_id: ""} }); } diff --git a/receive-purchase.php b/receive-purchase.php index cfaccb2..608c5e5 100644 --- a/receive-purchase.php +++ b/receive-purchase.php @@ -84,17 +84,28 @@ $pdo->exec('CREATE TABLE IF NOT EXISTS transactions ( )'); $pdo->exec('CREATE INDEX IF NOT EXISTS idx_transactions_user_id ON transactions (user_id)'); -$existingStmt = $pdo->prepare('SELECT 1 FROM processed_webhook_events WHERE event_id = :event_id'); -$existingStmt->execute(['event_id' => $eventId]); -if ($existingStmt->fetch()) { - respond(200, ['status' => 'already_processed']); -} - $creditsPerPrice = [ 'pri_01m1v28mknf5pjm5c99cvxa5k4' => 20, 'pri_01m1v2aegbrdvwhw1jf7b0s6va' => 50, ]; +$pdo->beginTransaction(); + +try { + // Claim the event ID first, inside the transaction: SQLite's unique constraint + // makes this the atomic compare-and-set that decides whether this delivery is + // the one that gets to apply credits. A losing concurrent delivery fails here + // before touching the user's balance. + $claimStmt = $pdo->prepare('INSERT INTO processed_webhook_events (event_id) VALUES (:event_id)'); + $claimStmt->execute(['event_id' => $eventId]); +} catch (PDOException $e) { + $pdo->rollBack(); + if (str_contains($e->getMessage(), 'UNIQUE constraint failed')) { + respond(200, ['status' => 'already_processed']); + } + throw $e; +} + if (($event['event_type'] ?? '') === 'transaction.completed') { $data = $event['data'] ?? []; $ticket = $data['custom_data']['user_id'] ?? null; @@ -123,6 +134,6 @@ if (($event['event_type'] ?? '') === 'transaction.completed') { } } -$pdo->prepare('INSERT INTO processed_webhook_events (event_id) VALUES (:event_id)')->execute(['event_id' => $eventId]); +$pdo->commit(); respond(200, ['status' => 'ok']);