From 747a3f86e81b7cf664418c0ff3ba7bfff1591cfd Mon Sep 17 00:00:00 2001 From: Jaafar Date: Wed, 18 Nov 2026 11:38:25 +0200 Subject: [PATCH] fix: verify the card-token webhooks, and surface the card they carry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `card_token.created` and `card_token.failed` were unverifiable. The server signs by opt-out — PaymentIntegrationWebhookJob copies the payload and unsets a fixed exclusion list before hashing — so the tokenisation block it writes for these two events is signed in full: `tokenization_id`, `external_reference`, and, once the card is vaulted, `card_token`, `card_brand`, `card_last4`, `card_exp_month` and `card_exp_year`. This SDK signed none of them, so every card-token webhook failed verification. Both events are on by default for every integration, because a hosted tokenisation has no other way to deliver its token, so this reached anyone saving cards. The signed values are now rebuilt the way the server assembles them, a block at a time: a block is gated on its own leading field, and a key keeps the position it was first written at. That ordering is the whole of it — the signature is a separator-less concatenation, and on an event with no mandate `external_reference` is signed after `tokenization_id`, not at the slot it holds on a subscription event. The card is also readable off WebhookEvent now, appended after `raw` so that positional construction of an event written before these properties existed still works. Two golden vectors cover the vaulted card and a failed tokenisation that carries no card at all; they are the same vectors the other SDKs verify against. --- CHANGELOG.md | 16 ++++++ src/Core/Version.php | 2 +- src/Core/Webhook/WebhookEvent.php | 11 +++++ src/Core/Webhook/WebhookEventType.php | 2 + src/Core/Webhooks.php | 69 +++++++++++++++++++++----- tests/WebhooksTest.php | 71 +++++++++++++++++++++++++++ tests/fixtures/golden-signatures.json | 60 ++++++++++++++++++++++ 7 files changed, 217 insertions(+), 14 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bc12e20..c306031 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to this package are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [0.3.0] - 2026-11-18 + +### Fixed + +- `webhooks->verify()` now accepts `card_token.created` and `card_token.failed`. Both carry the + tokenisation and the card it produced, and the server signs all of those fields; this SDK signed + none of them, so every card-token webhook failed verification. Both events are on by default for + every integration, so any integrator saving cards was receiving webhooks it could not verify. + +### Added + +- `CardTokenCreated` and `CardTokenFailed` on `WebhookEventType`. +- The saved card on `WebhookEvent`: `tokenizationId`, `cardToken`, `cardBrand`, `cardLast4`, + `cardExpMonth` and `cardExpYear`. They are appended after `raw`, so positional construction of an + event written before they existed still works. + ## [0.2.0] - 2026-08-06 ### Added diff --git a/src/Core/Version.php b/src/Core/Version.php index 860e100..e26f990 100644 --- a/src/Core/Version.php +++ b/src/Core/Version.php @@ -10,5 +10,5 @@ */ final class Version { - public const VALUE = '0.2.0'; + public const VALUE = '0.3.0'; } diff --git a/src/Core/Webhook/WebhookEvent.php b/src/Core/Webhook/WebhookEvent.php index 388bc19..1dd95cb 100644 --- a/src/Core/Webhook/WebhookEvent.php +++ b/src/Core/Webhook/WebhookEvent.php @@ -7,6 +7,11 @@ /** * A verified webhook event with camelCase fields; `raw` holds the full decoded * payload. Compare `event` against {@see WebhookEventType} to branch by type. + * + * The card properties are filled only on `card_token.created`, and only once the + * card was actually vaulted: a `card_token.failed` event carries the tokenisation + * and nothing else. They sit after `raw` so that positional construction of an + * event built before they existed still works. */ final class WebhookEvent { @@ -26,6 +31,12 @@ public function __construct( public readonly ?string $externalReference, public readonly ?string $subscriptionStatus, public readonly array $raw, + public readonly ?string $tokenizationId = null, + public readonly ?string $cardToken = null, + public readonly ?string $cardBrand = null, + public readonly ?string $cardLast4 = null, + public readonly ?string $cardExpMonth = null, + public readonly ?string $cardExpYear = null, ) {} /** Resolve the raw event string to a {@see WebhookEventType}, or null if unknown. */ diff --git a/src/Core/Webhook/WebhookEventType.php b/src/Core/Webhook/WebhookEventType.php index 5dc85d0..7fa2a02 100644 --- a/src/Core/Webhook/WebhookEventType.php +++ b/src/Core/Webhook/WebhookEventType.php @@ -31,4 +31,6 @@ enum WebhookEventType: string case VccPaymentFailed = 'vcc.payment_failed'; case CardTokenChargeSucceeded = 'card_token.charge_succeeded'; case CardTokenChargeFailed = 'card_token.charge_failed'; + case CardTokenCreated = 'card_token.created'; + case CardTokenFailed = 'card_token.failed'; } diff --git a/src/Core/Webhooks.php b/src/Core/Webhooks.php index ed9076c..950063f 100644 --- a/src/Core/Webhooks.php +++ b/src/Core/Webhooks.php @@ -23,13 +23,37 @@ final class Webhooks private const ALWAYS_SIGNED = ['success', 'invoice_id', 'invoice_status', 'message']; /** - * Optionally-signed fields, appended in this order only when the payload - * carries the key. This mirrors the server's opt-OUT signing: a field is - * signed when present, so `auth_code` (added after the signature is computed + * The fields a recurring mandate adds, in the order the server adds them. + * + * This mirrors the server's opt-OUT signing: a field is signed when the block + * that writes it runs, so `auth_code` (added after the signature is computed * server-side) is deliberately absent here. Getting membership backwards * breaks verification for every webhook carrying the field. */ - private const OPTIONAL_SIGNED = ['mandate_id', 'external_reference', 'subscription_status']; + private const MANDATE_SIGNED = ['mandate_id', 'external_reference', 'subscription_status']; + + /** + * The fields a card-token event adds, in the order the server adds them. + * + * `card_token.created` and `card_token.failed` are the only events that carry + * a tokenisation, and both are on by default for every integration. The + * server writes `tokenization_id` and `external_reference` first, then the + * card's details — and only when the card was actually vaulted, so a failed + * tokenisation signs the first two alone. + * + * Order matters because the signature is a separator-less concatenation: on + * an event with no mandate, `external_reference` is signed AFTER + * `tokenization_id`, not at the position it holds on a subscription event. + */ + private const TOKENIZATION_SIGNED = [ + 'tokenization_id', + 'external_reference', + 'card_token', + 'card_brand', + 'card_last4', + 'card_exp_month', + 'card_exp_year', + ]; public function __construct(private readonly Config $config) {} @@ -91,25 +115,38 @@ public function isValid(array | string $payload, ?string $hashToken = null): boo } /** - * Rebuild the expected signature from the payload's always- and (present) - * optional-signed fields. + * Rebuild the expected signature the way the server assembles it. + * + * `PaymentIntegrationWebhookJob` appends a whole block at a time — the + * mandate fields when the invoice belongs to one, the tokenisation fields + * when the event is about a card — and PHP keeps a key at the position it + * was first written. A block is therefore gated on its own leading field + * rather than on the individual fields inside it: `external_reference` + * belongs to whichever block introduced it, and is never signed twice. * * @param array $payload */ private function computeSignature(array $payload, string $hashToken): string { - $values = []; + $keys = self::ALWAYS_SIGNED; - foreach (self::ALWAYS_SIGNED as $key) { - $values[] = Coerce::toString($payload[$key] ?? null); - } + foreach ([self::MANDATE_SIGNED, self::TOKENIZATION_SIGNED] as $block) { + if (! array_key_exists($block[0], $payload)) { + continue; + } - foreach (self::OPTIONAL_SIGNED as $key) { - if (array_key_exists($key, $payload)) { - $values[] = Coerce::toString($payload[$key]); + foreach ($block as $key) { + if (array_key_exists($key, $payload) && ! in_array($key, $keys, true)) { + $keys[] = $key; + } } } + $values = array_map( + static fn (string $key): string => Coerce::toString($payload[$key] ?? null), + $keys, + ); + return Signature::build($values, $hashToken); } @@ -160,6 +197,12 @@ private function toEvent(array $payload): WebhookEvent externalReference: isset($payload['external_reference']) ? (string) $payload['external_reference'] : null, subscriptionStatus: isset($payload['subscription_status']) ? (string) $payload['subscription_status'] : null, raw: $payload, + tokenizationId: isset($payload['tokenization_id']) ? (string) $payload['tokenization_id'] : null, + cardToken: isset($payload['card_token']) ? (string) $payload['card_token'] : null, + cardBrand: isset($payload['card_brand']) ? (string) $payload['card_brand'] : null, + cardLast4: isset($payload['card_last4']) ? (string) $payload['card_last4'] : null, + cardExpMonth: isset($payload['card_exp_month']) ? (string) $payload['card_exp_month'] : null, + cardExpYear: isset($payload['card_exp_year']) ? (string) $payload['card_exp_year'] : null, ); } } diff --git a/tests/WebhooksTest.php b/tests/WebhooksTest.php index fda0799..189850e 100644 --- a/tests/WebhooksTest.php +++ b/tests/WebhooksTest.php @@ -39,6 +39,37 @@ function paidWebhook(string $hashToken): array return $payload; } +/** + * A `card_token.created` payload signed the way the server signs one: the + * tokenisation block follows the always-signed four, and `external_reference` + * sits after `tokenization_id` rather than in the slot a mandate gives it. + * + * @return array + */ +function cardTokenWebhook(string $hashToken): array +{ + $payload = [ + 'event' => 'card_token.created', 'event_triggered_at' => '2026-11-18T09:15:00+02:00', + 'timezone' => 'EET', 'success' => 1, 'invoice_id' => 7781, 'invoice_status' => 'REVERSED', + 'message' => 'Card stored for future payments.', 'tokenization_id' => 'TKZ-4f21', + 'external_reference' => 'cust-42', 'card_token' => 'CRD-9a07', 'card_brand' => 'VISA', + 'card_last4' => '4242', 'card_exp_month' => '12', 'card_exp_year' => '2029', + ]; + + $values = array_map( + static fn (string $key): string => Coerce::toString($payload[$key] ?? null), + [ + 'success', 'invoice_id', 'invoice_status', 'message', 'tokenization_id', + 'external_reference', 'card_token', 'card_brand', 'card_last4', + 'card_exp_month', 'card_exp_year', + ], + ); + + $payload['signature'] = Signature::build($values, $hashToken); + + return $payload; +} + it('verifies a valid webhook and maps camelCase fields', function (): void { $event = makeClient(new FakeTransport)->webhooks->verify(paidWebhook('secret')); @@ -76,3 +107,43 @@ function paidWebhook(string $hashToken): array expect($webhooks->isValid($payload))->toBeFalse() ->and($webhooks->isValid($payload, 'other-integration-secret'))->toBeTrue(); }); + +it('verifies a card_token.created webhook and exposes the saved card', function (): void { + $event = makeClient(new FakeTransport)->webhooks->verify(cardTokenWebhook('secret')); + + expect($event->type())->toBe(WebhookEventType::CardTokenCreated) + ->and($event->tokenizationId)->toBe('TKZ-4f21') + ->and($event->cardToken)->toBe('CRD-9a07') + ->and($event->cardBrand)->toBe('VISA') + ->and($event->cardLast4)->toBe('4242') + ->and($event->cardExpMonth)->toBe('12') + ->and($event->cardExpYear)->toBe('2029') + ->and($event->externalReference)->toBe('cust-42'); +}); + +it('rejects a card_token webhook whose card was tampered with', function (): void { + $payload = cardTokenWebhook('secret'); + $payload['card_last4'] = '1111'; + + expect(makeClient(new FakeTransport)->webhooks->isValid($payload))->toBeFalse(); +}); + +it('verifies a card_token.failed webhook, which carries no card at all', function (): void { + $payload = [ + 'event' => 'card_token.failed', 'success' => 0, 'invoice_id' => 7782, + 'invoice_status' => 'UNPAID', 'message' => 'The card could not be stored for future payments.', + 'tokenization_id' => 'TKZ-4f22', 'external_reference' => 'cust-43', + ]; + $values = array_map( + static fn (string $key): string => Coerce::toString($payload[$key] ?? null), + ['success', 'invoice_id', 'invoice_status', 'message', 'tokenization_id', 'external_reference'], + ); + $payload['signature'] = Signature::build($values, 'secret'); + + $event = makeClient(new FakeTransport)->webhooks->verify($payload); + + expect($event->type())->toBe(WebhookEventType::CardTokenFailed) + ->and($event->tokenizationId)->toBe('TKZ-4f22') + ->and($event->cardToken)->toBeNull() + ->and($event->success)->toBeFalse(); +}); diff --git a/tests/fixtures/golden-signatures.json b/tests/fixtures/golden-signatures.json index ee98469..ec05704 100644 --- a/tests/fixtures/golden-signatures.json +++ b/tests/fixtures/golden-signatures.json @@ -414,6 +414,66 @@ ], "hashToken": "test_hash_token_abc123", "expected": "rk5BFKdp6JRLCX70/iPThwaybLuHV9t/AXaBRPA/J2E=" + }, + { + "name": "webhook card_token.created (card vaulted)", + "endpoint": "WEBHOOK", + "input": { + "event": "card_token.created", + "event_triggered_at": "2026-11-18T09:15:00+02:00", + "timezone": "EET", + "success": 1, + "invoice_id": 7781, + "invoice_status": "REVERSED", + "message": "Card stored for future payments.", + "tokenization_id": "TKZ-4f21", + "external_reference": "cust-42", + "card_token": "CRD-9a07", + "card_brand": "VISA", + "card_last4": "4242", + "card_exp_month": "12", + "card_exp_year": "2029" + }, + "values": [ + "1", + "7781", + "REVERSED", + "Card stored for future payments.", + "TKZ-4f21", + "cust-42", + "CRD-9a07", + "VISA", + "4242", + "12", + "2029" + ], + "hashToken": "test_hash_token_abc123", + "expected": "07XJec3X2wXLRX0S5ybJzaXv4oLCjEyY/WqomIAqi6o=" + }, + { + "name": "webhook card_token.failed (no card vaulted)", + "endpoint": "WEBHOOK", + "input": { + "event": "card_token.failed", + "event_triggered_at": "2026-11-18T09:16:00+02:00", + "timezone": "EET", + "success": 0, + "invoice_id": 7782, + "invoice_status": "UNPAID", + "message": "The card could not be stored for future payments.", + "tokenization_id": "TKZ-4f22", + "external_reference": "cust-43" + }, + "values": [ + "0", + "7782", + "UNPAID", + "The card could not be stored for future payments.", + "TKZ-4f22", + "cust-43" + ], + "hashToken": "test_hash_token_abc123", + "expected": "Fm/7wiUagH2Q82ld+dI63zSM8rkGQkQ0GXf4RAdTb/w=" } ] }