Skip to content
Open
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
15 changes: 15 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,21 @@ All notable changes to this project are documented here.
The format follows [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

- `CARD_TOKEN_CREATED` and `CARD_TOKEN_FAILED` on `WebhookEventType`.
- The saved card on `WebhookEvent`: `tokenization_id`, `card_token`, `card_brand`, `card_last4`,
`card_exp_month` and `card_exp_year`.

## [0.2.0]

### Added
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "hatchling.build"

[project]
name = "getpayin"
version = "0.2.0"
version = "0.3.0"
description = "Official server-side Python SDK for the GetPayIn / GetPayIn payment integration API (checkouts, payment operations, card tokens, recurring mandates, webhook verification)."
readme = "README.md"
requires-python = ">=3.8"
Expand Down
2 changes: 1 addition & 1 deletion src/getpayin/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@
``pyproject.toml`` (see CONTRIBUTING.md).
"""

__version__ = "0.2.0"
__version__ = "0.3.0"
15 changes: 14 additions & 1 deletion src/getpayin/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,8 @@ class WebhookEventType:
VCC_PAYMENT_FAILED = "vcc.payment_failed"
CARD_TOKEN_CHARGE_SUCCEEDED = "card_token.charge_succeeded"
CARD_TOKEN_CHARGE_FAILED = "card_token.charge_failed"
CARD_TOKEN_CREATED = "card_token.created"
CARD_TOKEN_FAILED = "card_token.failed"


@dataclass(frozen=True)
Expand Down Expand Up @@ -142,7 +144,12 @@ class MandateActionResult:

@dataclass(frozen=True)
class WebhookEvent:
"""A verified webhook event with snake_case fields; ``raw`` holds the body."""
"""A verified webhook event with snake_case fields; ``raw`` holds the body.

The card fields 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.
"""

event: str
success: bool
Expand All @@ -156,3 +163,9 @@ class WebhookEvent:
subscription_status: Optional[str] = None
event_triggered_at: Optional[str] = None
timezone: Optional[str] = None
tokenization_id: Optional[str] = None
card_token: Optional[str] = None
card_brand: Optional[str] = None
card_last4: Optional[str] = None
card_exp_month: Optional[str] = None
card_exp_year: Optional[str] = None
55 changes: 47 additions & 8 deletions src/getpayin/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,7 @@
#: Always-signed webhook fields, in concatenation order (``None`` renders as '').
_ALWAYS_SIGNED = ("success", "invoice_id", "invoice_status", "message")

# Optionally-signed fields, appended in this order only when the payload carries
# them.
# The fields a recurring mandate adds, in the order the server adds them.
#
# Membership here is an EITHER/OR, not an additive safety net. The server signs
# by opt-OUT: ``PaymentIntegrationWebhookJob`` copies the whole payload and
Expand All @@ -27,7 +26,28 @@
# deliberately absent here. For any new field: if the server signs it, it MUST be
# listed here in the server's order; if the server sends it unsigned, it MUST NOT
# be listed. See CONTRIBUTING.md.
_OPTIONAL_SIGNED = ("mandate_id", "external_reference", "subscription_status")
_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.
_TOKENIZATION_SIGNED = (
"tokenization_id",
"external_reference",
"card_token",
"card_brand",
"card_last4",
"card_exp_month",
"card_exp_year",
)

WebhookInput = Union[Mapping[str, Any], str, bytes]

Expand Down Expand Up @@ -70,13 +90,26 @@ def is_valid(self, payload: WebhookInput, *, hash_token: Optional[str] = None) -
return False

def _compute_signature(self, payload: Mapping[str, Any], hash_token: str) -> str:
values = [coerce_to_string(payload.get(key)) for key in _ALWAYS_SIGNED]
"""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.
"""
keys = list(_ALWAYS_SIGNED)

for block in (_MANDATE_SIGNED, _TOKENIZATION_SIGNED):
if block[0] not in payload:
continue

for key in _OPTIONAL_SIGNED:
if key in payload:
values.append(coerce_to_string(payload.get(key)))
for key in block:
if key in payload and key not in keys:
keys.append(key)

return build_signature(values, hash_token)
return build_signature([coerce_to_string(payload.get(key)) for key in keys], hash_token)

def _parse(self, payload: WebhookInput) -> Dict[str, Any]:
if isinstance(payload, Mapping):
Expand Down Expand Up @@ -108,6 +141,12 @@ def _to_event(self, payload: Mapping[str, Any]) -> WebhookEvent:
external_reference=payload.get("external_reference"),
subscription_status=payload.get("subscription_status"),
raw=dict(payload),
tokenization_id=payload.get("tokenization_id"),
card_token=payload.get("card_token"),
card_brand=payload.get("card_brand"),
card_last4=payload.get("card_last4"),
card_exp_month=payload.get("card_exp_month"),
card_exp_year=payload.get("card_exp_year"),
)


Expand Down
60 changes: 60 additions & 0 deletions tests/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="
}
]
}
97 changes: 97 additions & 0 deletions tests/test_webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from getpayin import GetpayinClient
from getpayin.errors import GetpayinError, GetpayinSignatureError
from getpayin.signature import build_signature
from getpayin.types import WebhookEventType

HASH = "test_hash_token_abc123"

Expand All @@ -21,6 +22,46 @@ def _signed(payload: dict, hash_token: str = HASH) -> dict:
return dict(payload, signature=build_signature(values, hash_token))


def _signed_card_token(payload: dict, hash_token: str = HASH) -> dict:
"""Sign a card-token payload 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.
"""
keys = ["success", "invoice_id", "invoice_status", "message"]
keys += [
key
for key in (
"tokenization_id",
"external_reference",
"card_token",
"card_brand",
"card_last4",
"card_exp_month",
"card_exp_year",
)
if key in payload
]
values = ["" if payload.get(key) is None else str(payload.get(key)) for key in keys]
return dict(payload, signature=build_signature(values, hash_token))


CARD_TOKEN_CREATED = {
"event": "card_token.created",
"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",
}

class WebhooksTest(unittest.TestCase):
def setUp(self) -> None:
self.client = GetpayinClient(public_token="p", hash_token=HASH)
Expand Down Expand Up @@ -90,6 +131,62 @@ def test_invalid_json_raises_getpayin_error(self) -> None:
with self.assertRaises(GetpayinError):
self.client.webhooks.verify("{not json")

def test_card_token_created_exposes_the_saved_card(self) -> None:
event = self.client.webhooks.verify(_signed_card_token(CARD_TOKEN_CREATED))

self.assertEqual(event.event, WebhookEventType.CARD_TOKEN_CREATED)
self.assertEqual(event.tokenization_id, "TKZ-4f21")
self.assertEqual(event.card_token, "CRD-9a07")
self.assertEqual(event.card_brand, "VISA")
self.assertEqual(event.card_last4, "4242")
self.assertEqual(event.card_exp_month, "12")
self.assertEqual(event.card_exp_year, "2029")
self.assertEqual(event.external_reference, "cust-42")

def test_card_token_failed_carries_no_card(self) -> None:
payload = _signed_card_token(
{
"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",
}
)
event = self.client.webhooks.verify(payload)

self.assertEqual(event.event, WebhookEventType.CARD_TOKEN_FAILED)
self.assertFalse(event.success)
self.assertEqual(event.tokenization_id, "TKZ-4f22")
self.assertIsNone(event.card_token)

def test_tampered_card_is_rejected(self) -> None:
payload = _signed_card_token(CARD_TOKEN_CREATED)
payload["card_last4"] = "1111"

self.assertFalse(self.client.webhooks.is_valid(payload))

def test_external_reference_is_not_signed_in_the_mandate_slot(self) -> None:
payload = _signed_card_token(CARD_TOKEN_CREATED)
mandate_order = [
"1",
"7781",
"REVERSED",
"Card stored for future payments.",
"cust-42",
"TKZ-4f21",
"CRD-9a07",
"VISA",
"4242",
"12",
"2029",
]

self.assertNotEqual(payload["signature"], build_signature(mandate_order, HASH))
self.assertTrue(self.client.webhooks.is_valid(payload))


if __name__ == "__main__":
unittest.main()
Loading