Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion src/Core/Version.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,5 @@
*/
final class Version
{
public const VALUE = '0.2.0';
public const VALUE = '0.3.0';
}
11 changes: 11 additions & 0 deletions src/Core/Webhook/WebhookEvent.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand All @@ -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. */
Expand Down
2 changes: 2 additions & 0 deletions src/Core/Webhook/WebhookEventType.php
Original file line number Diff line number Diff line change
Expand Up @@ -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';
}
69 changes: 56 additions & 13 deletions src/Core/Webhooks.php
Original file line number Diff line number Diff line change
Expand Up @@ -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) {}

Expand Down Expand Up @@ -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<string, mixed> $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);
}

Expand Down Expand Up @@ -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,
);
}
}
71 changes: 71 additions & 0 deletions tests/WebhooksTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, mixed>
*/
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'));

Expand Down Expand Up @@ -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();
});
60 changes: 60 additions & 0 deletions tests/fixtures/golden-signatures.json
Original file line number Diff line number Diff line change
Expand Up @@ -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="
}
]
}
Loading