diff --git a/CHANGELOG.md b/CHANGELOG.md index 7ebc8f4..2015b88 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 0.5.0 + +### Added + +- Stripe adapter, `halvorai_ingest.stripe`, matching the Node.js and Go SDKs. `halvor.stripe(event)` maps a verified Stripe webhook event and queues it. PaymentIntent, refund and dispute events go on the `stripe` rail. Issuing authorization and transaction events go on the `card` rail. `map_stripe_event`, `stripe_webhook_handler` and `STRIPE_HANDLED_TYPES` are also exported. The adapter does not depend on the Stripe library. +- `tag_payment_intent` and `tag_issuing_card` write `metadata.halvor_*` from `agent_context` or from keyword overrides. These keys are agent id, name and framework, owner id and type, and instruction id. The name is cut to 128 characters and the framework to 64, so card payments show the agent's name. For the same webhook, the mapping gives the same event as `@halvorai/ingest/stripe`; the tests check this against the Node.js output for every shared fixture. + ## 0.4.1 ### Fixed diff --git a/README.md b/README.md index 8bd3d5a..47621dc 100644 --- a/README.md +++ b/README.md @@ -113,7 +113,29 @@ To keep a custom transport, pass it as `inner`: `HalvorX402Transport(halvor, inn Each 402 challenge becomes a `payment.requested` event. The payment that answers it becomes `payment.authorized`, linked to the challenge with `related.previous_event_id`, and the settlement becomes `payment.settled` or `payment.failed` with the same `payment_id`. A challenge without a network or token address is reported as `invalid_event` and not recorded. -Stripe, MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js). Guides for each: [docs.halvorai.com](https://docs.halvorai.com). +## Stripe + +Pass each verified Stripe webhook event to `halvor.stripe(event)`. PaymentIntents, refunds and disputes are recorded on the `stripe` rail. Stripe Issuing authorizations and transactions are recorded on the `card` rail. Any other event type returns `None` and is ignored. The adapter does not import the Stripe library, and it accepts a plain dict or a `stripe.Event`. + +```python +import stripe + +from halvorai_ingest import agent_context +from halvorai_ingest.stripe import tag_issuing_card, tag_payment_intent + +# Tag what the agent creates, so its webhooks map back to the agent, owner and instruction. +with agent_context(agent={"id": "agt_travel_12", "name": "Travel agent"}, owner={"id": "own_4410", "type": "business"}): + card = stripe.issuing.Card.create(**tag_issuing_card({"cardholder": "ich_...", "currency": "usd", "type": "virtual"})) + intent = stripe.PaymentIntent.create(**tag_payment_intent({"amount": 41200, "currency": "usd"})) + +# In your webhook endpoint, after Stripe's own signature check: +event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) +halvor.stripe(event) +``` + +The tags are `metadata.halvor_*` keys, taken from `agent_context` or from keyword overrides (`agent_id`, `agent_name`, `framework`, `owner_id`, `owner_type`, `instruction_id`). Put them on the card for Issuing: card webhooks carry no other agent name. An event without tags is recorded as `unattributed`. `map_stripe_event(event)` returns the event without queuing it. The mapping is the same as in the Node.js and Go SDKs. + +MPP and MCP adapters are in the Node.js SDK, [`@halvorai/ingest`](https://github.com/halvorAI/ingest-js). Guides for each: [docs.halvorai.com](https://docs.halvorai.com). ## Develop diff --git a/halvorai_ingest/client.py b/halvorai_ingest/client.py index a7e50a5..93b1f70 100644 --- a/halvorai_ingest/client.py +++ b/halvorai_ingest/client.py @@ -268,6 +268,21 @@ def emit(self, input_event: Any) -> str: self.notify({"code": "invalid_event", "message": str(exc) or "emit failed", "eventId": event_id}) return event_id + def stripe(self, event: Any) -> str | None: + """ + Map a Stripe webhook event (after your own signature check) and queue it. Returns the + event id, or `None` for a type the adapter does not handle. Never raises. + """ + try: + from .stripe.map import map_stripe_event + + mapped = map_stripe_event(event) + except Exception as exc: + self._count("emitted", "dropped_invalid") + self.notify({"code": "invalid_event", "message": f"stripe: {exc}" if str(exc) else "stripe mapping failed"}) + return None + return None if mapped is None else self.emit(mapped) + def flush(self, timeout: float | None = None, *, replay_spool: bool = True) -> dict[str, bool]: """ Send everything queued and wait for it. Without `timeout` this waits for the full retry diff --git a/halvorai_ingest/stripe/__init__.py b/halvorai_ingest/stripe/__init__.py new file mode 100644 index 0000000..e88dc78 --- /dev/null +++ b/halvorai_ingest/stripe/__init__.py @@ -0,0 +1,35 @@ +"""Stripe adapter: map Stripe and Stripe Issuing webhooks to APE events. + + from halvorai_ingest.stripe import tag_issuing_card + + event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret) # your check + halvor.stripe(event) + +`halvor.stripe(event)` maps the event and queues it, returning the event id, or `None` for a +type the adapter does not handle. `map_stripe_event` returns the partial APE event without +queuing it. Verify the Stripe signature yourself first; the adapter trusts what it is given. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Callable + +from .map import STRIPE_HANDLED_TYPES, map_stripe_event +from .tag import tag_issuing_card, tag_payment_intent + +if TYPE_CHECKING: + from ..client import HalvorClient + + +def stripe_webhook_handler(client: HalvorClient) -> Callable[[Any], str | None]: + """Return a handler that maps Stripe events through `client`. Use after your own signature check.""" + return client.stripe + + +__all__ = [ + "STRIPE_HANDLED_TYPES", + "map_stripe_event", + "tag_payment_intent", + "tag_issuing_card", + "stripe_webhook_handler", +] diff --git a/halvorai_ingest/stripe/map.py b/halvorai_ingest/stripe/map.py new file mode 100644 index 0000000..83a07fa --- /dev/null +++ b/halvorai_ingest/stripe/map.py @@ -0,0 +1,356 @@ +"""Map Stripe webhook events to partial APE events, the same way as the Node.js and Go SDKs. + +Handled types (anything else maps to `None`): + +- `payment_intent.amount_capturable_updated`, `payment_intent.succeeded`, + `payment_intent.payment_failed`, `charge.refunded`, `charge.dispute.created` (rail `stripe`) +- `issuing_authorization.created`, `issuing_authorization.updated`, + `issuing_transaction.created` (rail `card`, adapter `stripe-issuing`) + +Attribution comes from `metadata.halvor_*` on the object, and for Issuing also on the card, +as written by `tag_payment_intent` and `tag_issuing_card`. Missing metadata maps to +`unattributed`. No Stripe SDK dependency: events are plain dicts, or Stripe objects that +convert to one (`stripe.Event` has `to_dict()`). +""" + +from __future__ import annotations + +import re +from datetime import datetime, timezone +from typing import Any, Mapping + +from ..hash import evidence_sha256, hash_instruction + +STRIPE_HANDLED_TYPES: tuple[str, ...] = ( + "payment_intent.amount_capturable_updated", + "payment_intent.succeeded", + "payment_intent.payment_failed", + "charge.refunded", + "charge.dispute.created", + "issuing_authorization.created", + "issuing_authorization.updated", + "issuing_transaction.created", +) + +_CURRENCY = re.compile(r"^[A-Z]{3}$") +_COUNTRY = re.compile(r"^[A-Za-z]{2}$") +_MCC = re.compile(r"^[0-9]{4}$") +_URL = re.compile(r"^https?://", re.IGNORECASE) + + +def _as_dict(value: Any) -> dict[str, Any] | None: + if isinstance(value, Mapping): + return dict(value) + to_dict = getattr(value, "to_dict", None) # stripe.StripeObject + if callable(to_dict): + converted = to_dict() + if isinstance(converted, Mapping): + return dict(converted) + return None + + +def _str(value: Any) -> str | None: + return value if isinstance(value, str) and value != "" else None + + +def _num(value: Any) -> int | float | None: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + if isinstance(value, float) and (value != value or value in (float("inf"), float("-inf"))): + return None + return value + + +def _currency(raw: Any) -> str: + c = _str(raw) + c = c.upper() if c is not None else None + return c if c is not None and _CURRENCY.match(c) else "USD" + + +def _minor(amount: int | float, currency: str) -> dict[str, str]: + return {"value": str(int(amount)), "unit": "minor", "currency": currency} + + +def _occurred_at(event: Mapping[str, Any]) -> str | None: + created = _num(event.get("created")) + if created is None: + return None + dt = datetime.fromtimestamp(created, tz=timezone.utc) + return dt.strftime("%Y-%m-%dT%H:%M:%S.") + f"{dt.microsecond // 1000:03d}Z" + + +def _metadata(obj: Mapping[str, Any]) -> dict[str, str]: + meta = _as_dict(obj.get("metadata")) + if meta is None: + return {} + return {k: v for k, v in meta.items() if isinstance(v, str)} + + +def _card_metadata(obj: Mapping[str, Any]) -> dict[str, str]: + card = _as_dict(obj.get("card")) + return {} if card is None else _metadata(card) + + +def _attribution(meta: Mapping[str, str]) -> dict[str, Any]: + agent: dict[str, Any] = {"id": meta.get("halvor_agent_id", "unattributed")} + name = meta.get("halvor_agent_name") + framework = meta.get("halvor_agent_framework") + if name: + agent["name"] = name[:128] + if framework: + agent["framework"] = framework[:64] + out: dict[str, Any] = { + "agent": agent, + "owner": { + "id": meta.get("halvor_owner_id", "unattributed"), + "type": "person" if meta.get("halvor_owner_type") == "person" else "business", + }, + } + instruction_id = meta.get("halvor_instruction_id") + if instruction_id is not None: + # Webhooks carry only the id; hash a stable local stand-in so APE validation passes. + out["instruction"] = {"id": instruction_id, "hash": hash_instruction(f"stripe-meta:{instruction_id}")} + return out + + +def _payee_from_connect(obj: Mapping[str, Any]) -> dict[str, Any]: + transfer = _as_dict(obj.get("transfer_data")) + destination = (_str(transfer.get("destination")) if transfer else None) or _str(obj.get("on_behalf_of")) + if destination is not None: + return {"type": "merchant", "id": destination} + description = _str(obj.get("description")) + if description is not None: + return {"type": "merchant", "name": description[:256]} + return {"type": "merchant", "name": "Stripe merchant"} + + +def _payee_from_merchant_data(obj: Mapping[str, Any]) -> dict[str, Any]: + md = _as_dict(obj.get("merchant_data")) + if md is None: + return {"type": "merchant", "name": "Card merchant"} + payee: dict[str, Any] = {"type": "merchant"} + name = _str(md.get("name")) + pid = _str(md.get("network_id")) + country = _str(md.get("country")) + mcc = _str(md.get("category_code")) + url = _str(md.get("url")) + if name is not None: + payee["name"] = name + if pid is not None: + payee["id"] = pid + if country is not None and _COUNTRY.match(country): + payee["country"] = country.upper() + if mcc is not None and _MCC.match(mcc): + payee["mcc"] = mcc + if url is not None and _URL.match(url): + payee["website"] = url + if "name" not in payee and "id" not in payee: + payee["name"] = "Card merchant" + return payee + + +def _evidence(obj: dict[str, Any]) -> list[dict[str, Any]]: + return [{"kind": "stripe.object", "format": "json", "value": obj, "sha256": evidence_sha256(obj)}] + + +def _shared_payment_token(obj: Mapping[str, Any]) -> str | None: + meta = _metadata(obj) + return meta.get("shared_payment_token") or meta.get("halvor_shared_payment_token") or _str( + obj.get("shared_payment_token") + ) + + +def _finish( + event: Mapping[str, Any], + etype: str, + adapter: str, + attr: dict[str, Any], + payment: dict[str, Any], + payee: dict[str, Any], + obj: dict[str, Any], +) -> dict[str, Any]: + mapped: dict[str, Any] = { + "type": etype, + "source": {"adapter": adapter}, + "agent": attr["agent"], + "owner": attr["owner"], + "payment": payment, + "payee": payee, + "evidence": _evidence(obj), + } + at = _occurred_at(event) + if at is not None: + mapped["occurred_at"] = at + if "instruction" in attr: + mapped["instruction"] = attr["instruction"] + return mapped + + +def _payment_intent(event: Mapping[str, Any], obj: dict[str, Any], etype: str, status: str) -> dict[str, Any]: + pid = _str(obj.get("id")) or "pi_unknown" + attr = _attribution(_metadata(obj)) + rail_ref: dict[str, Any] = {"payment_intent": pid} + payment: dict[str, Any] = { + "payment_id": pid, + "rail": "stripe", + "amount": _minor(_num(obj.get("amount")) or 0, _currency(obj.get("currency"))), + "status": status, + "rail_ref": rail_ref, + } + description = _str(obj.get("description")) + if description is not None: + payment["description"] = description[:256] + if status == "failed": + err = _as_dict(obj.get("last_payment_error")) + code = _str(err.get("code")) if err else None + payment["failure_reason"] = (code or "payment_failed")[:128] + spt = _shared_payment_token(obj) + if spt is not None: + rail_ref["shared_payment_token"] = spt + account = _str(obj.get("on_behalf_of")) + if account is not None: + rail_ref["account"] = account + mapped = _finish(event, etype, "stripe", attr, payment, _payee_from_connect(obj), obj) + if spt is not None: + mapped["instrument"] = {"type": "stripe_spt"} + return mapped + + +def _charge_refunded(event: Mapping[str, Any], obj: dict[str, Any]) -> dict[str, Any]: + charge_id = _str(obj.get("id")) or "ch_unknown" + pi = _str(obj.get("payment_intent")) + amount = _num(obj.get("amount_refunded")) + if amount is None: + amount = _num(obj.get("amount")) or 0 + rail_ref: dict[str, Any] = {"charge": charge_id} + if pi is not None: + rail_ref["payment_intent"] = pi + payment: dict[str, Any] = { + "payment_id": pi or charge_id, + "rail": "stripe", + "amount": _minor(amount, _currency(obj.get("currency"))), + "status": "refunded", + "rail_ref": rail_ref, + } + description = _str(obj.get("description")) + if description is not None: + payment["description"] = description[:256] + attr = _attribution(_metadata(obj)) + return _finish(event, "payment.refunded", "stripe", attr, payment, _payee_from_connect(obj), obj) + + +def _dispute(event: Mapping[str, Any], obj: dict[str, Any]) -> dict[str, Any]: + dispute_id = _str(obj.get("id")) or "dp_unknown" + pi = _str(obj.get("payment_intent")) + charge = _str(obj.get("charge")) + rail_ref: dict[str, Any] = {"dispute": dispute_id} + if pi is not None: + rail_ref["payment_intent"] = pi + if charge is not None: + rail_ref["charge"] = charge + payment: dict[str, Any] = { + "payment_id": pi or charge or dispute_id, + "rail": "stripe", + "amount": _minor(_num(obj.get("amount")) or 0, _currency(obj.get("currency"))), + "status": "disputed", + "rail_ref": rail_ref, + } + reason = _str(obj.get("reason")) + if reason is not None: + payment["description"] = reason[:256] + attr = _attribution(_metadata(obj)) + payee = {"type": "merchant", "name": "Stripe dispute"} + return _finish(event, "payment.disputed", "stripe", attr, payment, payee, obj) + + +def _card_payment(payment: dict[str, Any], merchant: Mapping[str, Any]) -> None: + mcc = _str(merchant.get("mcc")) + if mcc is not None: + payment["category"] = f"mcc:{mcc}" + name = _str(merchant.get("name")) + if name is not None: + payment["description"] = name[:256] + + +def _issuing_authorization(event: Mapping[str, Any], obj: dict[str, Any], failed: bool) -> dict[str, Any]: + aid = _str(obj.get("id")) or "iauth_unknown" + attr = _attribution({**_metadata(obj), **_card_metadata(obj)}) + merchant = _payee_from_merchant_data(obj) + payment: dict[str, Any] = { + "payment_id": aid, + "rail": "card", + "amount": _minor(_num(obj.get("amount")) or 0, _currency(obj.get("currency"))), + "status": "failed" if failed else "authorized", + "rail_ref": {"authorization_id": aid, "processor": "stripe-issuing"}, + } + if failed: + payment["failure_reason"] = "issuing_authorization_declined" + _card_payment(payment, merchant) + etype = "payment.failed" if failed else "payment.authorized" + mapped = _finish(event, etype, "stripe-issuing", attr, payment, merchant, obj) + card = _as_dict(obj.get("card")) + if card is not None: + instrument: dict[str, Any] = {"type": "card", "issuer": "Stripe Issuing"} + last4 = _str(card.get("last4")) + brand = _str(card.get("brand")) + if last4 is not None and _MCC.match(last4): + instrument["last4"] = last4 + if brand is not None: + instrument["network"] = brand.lower() + mapped["instrument"] = instrument + return mapped + + +def _issuing_transaction(event: Mapping[str, Any], obj: dict[str, Any]) -> dict[str, Any]: + tid = _str(obj.get("id")) or "ipi_unknown" + refunded = (_str(obj.get("type")) or "capture") == "refund" + attr = _attribution({**_metadata(obj), **_card_metadata(obj)}) + merchant = _payee_from_merchant_data(obj) + rail_ref: dict[str, Any] = {"transaction_id": tid, "processor": "stripe-issuing"} + auth = _str(obj.get("authorization")) + if auth is not None: + rail_ref["authorization_id"] = auth + payment: dict[str, Any] = { + "payment_id": tid, + "rail": "card", + "amount": _minor(abs(_num(obj.get("amount")) or 0), _currency(obj.get("currency"))), + "status": "refunded" if refunded else "settled", + "rail_ref": rail_ref, + } + _card_payment(payment, merchant) + etype = "payment.refunded" if refunded else "payment.settled" + return _finish(event, etype, "stripe-issuing", attr, payment, merchant, obj) + + +def map_stripe_event(event: Any) -> dict[str, Any] | None: + """ + Map a Stripe webhook event to a partial APE event for `HalvorClient.emit`. + Returns `None` for types the adapter does not handle. + """ + ev = _as_dict(event) + if ev is None: + return None + etype = ev.get("type") + if etype not in STRIPE_HANDLED_TYPES: + return None + data = _as_dict(ev.get("data")) + obj = _as_dict(data.get("object")) if data else None + if obj is None: + return None + + if etype == "payment_intent.amount_capturable_updated": + return _payment_intent(ev, obj, "payment.authorized", "authorized") + if etype == "payment_intent.succeeded": + return _payment_intent(ev, obj, "payment.settled", "settled") + if etype == "payment_intent.payment_failed": + return _payment_intent(ev, obj, "payment.failed", "failed") + if etype == "charge.refunded": + return _charge_refunded(ev, obj) + if etype == "charge.dispute.created": + return _dispute(ev, obj) + if etype == "issuing_authorization.created": + return _issuing_authorization(ev, obj, obj.get("approved") is False) + if etype == "issuing_authorization.updated": + status = _str(obj.get("status")) + return _issuing_authorization(ev, obj, obj.get("approved") is False or status in ("reversed", "expired")) + return _issuing_transaction(ev, obj) diff --git a/halvorai_ingest/stripe/tag.py b/halvorai_ingest/stripe/tag.py new file mode 100644 index 0000000..8e19719 --- /dev/null +++ b/halvorai_ingest/stripe/tag.py @@ -0,0 +1,102 @@ +"""Write `metadata.halvor_*` on Stripe objects so their webhooks map back to the agent.""" + +from __future__ import annotations + +from typing import Any, Literal, Mapping + +from ..context import current_context + + +def _merge( + existing: Mapping[str, Any] | None, + *, + agent_id: str | None, + agent_name: str | None, + framework: str | None, + owner_id: str | None, + owner_type: Literal["person", "business"] | None, + instruction_id: str | None, +) -> dict[str, Any]: + ctx: Mapping[str, Any] = current_context() or {} + agent: Mapping[str, Any] = ctx.get("agent") or {} + owner: Mapping[str, Any] = ctx.get("owner") or {} + instruction: Mapping[str, Any] = ctx.get("instruction") or {} + meta: dict[str, Any] = dict(existing or {}) + + agent_id = agent_id if agent_id is not None else agent.get("id") + agent_name = agent_name if agent_name is not None else agent.get("name") + framework = framework if framework is not None else agent.get("framework") + owner_id = owner_id if owner_id is not None else owner.get("id") + owner_type = owner_type if owner_type is not None else owner.get("type") + instruction_id = instruction_id if instruction_id is not None else instruction.get("id") + + if agent_id is not None: + meta["halvor_agent_id"] = agent_id + # Cut to the APE limits, which also keeps them inside Stripe's 500-character metadata values. + if agent_name is not None: + meta["halvor_agent_name"] = agent_name[:128] + if framework is not None: + meta["halvor_agent_framework"] = framework[:64] + if owner_id is not None: + meta["halvor_owner_id"] = owner_id + if owner_type is not None: + meta["halvor_owner_type"] = owner_type + if instruction_id is not None: + meta["halvor_instruction_id"] = instruction_id + return meta + + +def tag_payment_intent( + params: Mapping[str, Any], + *, + agent_id: str | None = None, + agent_name: str | None = None, + framework: str | None = None, + owner_id: str | None = None, + owner_type: Literal["person", "business"] | None = None, + instruction_id: str | None = None, +) -> dict[str, Any]: + """ + Return a copy of the PaymentIntent create params with `metadata.halvor_*` written from the + current `agent_context`, or from the keyword overrides, which win over the context. + + stripe.PaymentIntent.create(**tag_payment_intent({"amount": 500, "currency": "usd"})) + """ + out = dict(params) + out["metadata"] = _merge( + params.get("metadata"), + agent_id=agent_id, + agent_name=agent_name, + framework=framework, + owner_id=owner_id, + owner_type=owner_type, + instruction_id=instruction_id, + ) + return out + + +def tag_issuing_card( + params: Mapping[str, Any], + *, + agent_id: str | None = None, + agent_name: str | None = None, + framework: str | None = None, + owner_id: str | None = None, + owner_type: Literal["person", "business"] | None = None, + instruction_id: str | None = None, +) -> dict[str, Any]: + """ + The same tagging for Issuing card creates (one card per agent is recommended). The agent + name and framework are stored on the card, since card webhooks carry no other agent name. + + stripe.issuing.Card.create(**tag_issuing_card({"currency": "usd", "type": "virtual", ...})) + """ + return tag_payment_intent( + params, + agent_id=agent_id, + agent_name=agent_name, + framework=framework, + owner_id=owner_id, + owner_type=owner_type, + instruction_id=instruction_id, + ) diff --git a/pyproject.toml b/pyproject.toml index 92f29cd..149594a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "halvorai-ingest" -version = "0.4.1" +version = "0.5.0" description = "Signed, attributed payment events for AI agents. Never in the payment path." readme = "README.md" requires-python = ">=3.10" diff --git a/tests/fixtures/stripe/charge.dispute.created.json b/tests/fixtures/stripe/charge.dispute.created.json new file mode 100644 index 0000000..a718d0c --- /dev/null +++ b/tests/fixtures/stripe/charge.dispute.created.json @@ -0,0 +1,22 @@ +{ + "id": "evt_1DP_created", + "type": "charge.dispute.created", + "created": 1729168000, + "livemode": false, + "data": { + "object": { + "id": "dp_1QxDispute", + "object": "dispute", + "amount": 41200, + "currency": "usd", + "reason": "fraudulent", + "charge": "ch_3QxRefunded", + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + } +} diff --git a/tests/fixtures/stripe/charge.refunded.json b/tests/fixtures/stripe/charge.refunded.json new file mode 100644 index 0000000..083d4e0 --- /dev/null +++ b/tests/fixtures/stripe/charge.refunded.json @@ -0,0 +1,24 @@ +{ + "id": "evt_1CH_refunded", + "type": "charge.refunded", + "created": 1729167000, + "livemode": false, + "data": { + "object": { + "id": "ch_3QxRefunded", + "object": "charge", + "amount": 41200, + "amount_refunded": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "refunded": true, + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + }, + "on_behalf_of": "acct_1Nw0rTh" + } + } +} diff --git a/tests/fixtures/stripe/expected.json b/tests/fixtures/stripe/expected.json new file mode 100644 index 0000000..acca8a8 --- /dev/null +++ b/tests/fixtures/stripe/expected.json @@ -0,0 +1,846 @@ +{ + "charge.dispute.created.json": { + "type": "payment.disputed", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAbCdEfGhIjKlM", + "rail": "stripe", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "disputed", + "rail_ref": { + "dispute": "dp_1QxDispute", + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "charge": "ch_3QxRefunded" + }, + "description": "fraudulent" + }, + "payee": { + "type": "merchant", + "name": "Stripe dispute" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "dp_1QxDispute", + "object": "dispute", + "amount": 41200, + "currency": "usd", + "reason": "fraudulent", + "charge": "ch_3QxRefunded", + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + }, + "sha256": "sha256:542163d27ecbb620079506fd96361165de86b2828fe63bf0b0fedfa221e64429" + } + ], + "occurred_at": "2024-10-17T12:26:40.000Z" + }, + "charge.refunded.json": { + "type": "payment.refunded", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAbCdEfGhIjKlM", + "rail": "stripe", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "refunded", + "rail_ref": { + "charge": "ch_3QxRefunded", + "payment_intent": "pi_3QxAbCdEfGhIjKlM" + }, + "description": "Return flight SFO-AUS" + }, + "payee": { + "type": "merchant", + "id": "acct_1Nw0rTh" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "ch_3QxRefunded", + "object": "charge", + "amount": 41200, + "amount_refunded": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "refunded": true, + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + }, + "on_behalf_of": "acct_1Nw0rTh" + }, + "sha256": "sha256:e61b7766aa72c71a2e1b69b458ee00b499b098eb70b80d9d5093009f0f2e9fa1" + } + ], + "occurred_at": "2024-10-17T12:10:00.000Z" + }, + "issuing_authorization.created.json": { + "type": "payment.authorized", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "iauth_1QxYz2AbCdEfGh", + "rail": "card", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "authorized", + "rail_ref": { + "authorization_id": "iauth_1QxYz2AbCdEfGh", + "processor": "stripe-issuing" + }, + "category": "mcc:4511", + "description": "Example Airways" + }, + "payee": { + "type": "merchant", + "name": "Example Airways", + "id": "acq_000123456789", + "country": "US", + "mcc": "4511", + "website": "https://example-airways.com" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890" + } + } + }, + "sha256": "sha256:3d2c0d268ac048982978e286241642f6275aad04c5a1ebd9d8f7a32b9b46e47c" + } + ], + "occurred_at": "2024-10-17T10:40:00.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "card", + "issuer": "Stripe Issuing", + "last4": "4242", + "network": "visa" + } + }, + "issuing_authorization.updated.json": { + "type": "payment.failed", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "iauth_1QxDeclined", + "rail": "card", + "amount": { + "value": "9900", + "unit": "minor", + "currency": "USD" + }, + "status": "failed", + "rail_ref": { + "authorization_id": "iauth_1QxDeclined", + "processor": "stripe-issuing" + }, + "failure_reason": "issuing_authorization_declined", + "category": "mcc:7995", + "description": "Blocked Merchant" + }, + "payee": { + "type": "merchant", + "name": "Blocked Merchant", + "id": "acq_blocked", + "country": "US", + "mcc": "7995" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "iauth_1QxDeclined", + "object": "issuing.authorization", + "amount": 9900, + "currency": "usd", + "approved": false, + "status": "closed", + "merchant_data": { + "name": "Blocked Merchant", + "category_code": "7995", + "country": "US", + "network_id": "acq_blocked" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + }, + "sha256": "sha256:70d923c0cf1fecb61d863d578a1e9d81dfdceaeb34cc51e0ff6d3c629f9ef982" + } + ], + "occurred_at": "2024-10-17T10:41:00.000Z", + "instrument": { + "type": "card", + "issuer": "Stripe Issuing", + "last4": "4242", + "network": "visa" + } + }, + "issuing_transaction.created.json": { + "type": "payment.settled", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "ipi_1QxCapture", + "rail": "card", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "settled", + "rail_ref": { + "transaction_id": "ipi_1QxCapture", + "processor": "stripe-issuing", + "authorization_id": "iauth_1QxYz2AbCdEfGh" + }, + "category": "mcc:4511", + "description": "Example Airways" + }, + "payee": { + "type": "merchant", + "name": "Example Airways", + "id": "acq_000123456789", + "country": "US", + "mcc": "4511" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "ipi_1QxCapture", + "object": "issuing.transaction", + "amount": -41200, + "currency": "usd", + "type": "capture", + "authorization": "iauth_1QxYz2AbCdEfGh", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + }, + "sha256": "sha256:49e4a6cca5c0ec7025356ffbc6aa684ce275f83148b8ced78a8d9e59a42cd47c" + } + ], + "occurred_at": "2024-10-17T10:50:00.000Z" + }, + "issuing_transaction.refund.json": { + "type": "payment.refunded", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "ipi_1QxRefund", + "rail": "card", + "amount": { + "value": "5000", + "unit": "minor", + "currency": "USD" + }, + "status": "refunded", + "rail_ref": { + "transaction_id": "ipi_1QxRefund", + "processor": "stripe-issuing" + }, + "category": "mcc:4511", + "description": "Example Airways" + }, + "payee": { + "type": "merchant", + "name": "Example Airways", + "id": "acq_000123456789", + "country": "US", + "mcc": "4511" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "ipi_1QxRefund", + "object": "issuing.transaction", + "amount": 5000, + "currency": "usd", + "type": "refund", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789" + }, + "card": { + "id": "ic_1QxCard", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + }, + "sha256": "sha256:93c46228abd859ca4337b70841c82338cf5ffb1ca07250d45064a550442f4a3e" + } + ], + "occurred_at": "2024-10-17T11:03:20.000Z" + }, + "payment_intent.amount_capturable_updated.json": { + "type": "payment.authorized", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAuthHold", + "rail": "stripe", + "amount": { + "value": "5000", + "unit": "minor", + "currency": "USD" + }, + "status": "authorized", + "rail_ref": { + "payment_intent": "pi_3QxAuthHold" + } + }, + "payee": { + "type": "merchant", + "name": "Stripe merchant" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxAuthHold", + "object": "payment_intent", + "amount": 5000, + "currency": "usd", + "status": "requires_capture", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + }, + "sha256": "sha256:0ba163f9399be1d784c93ac41fa041a05698e272c5f12cd96f92069a5669e6a0" + } + ], + "occurred_at": "2024-10-17T11:36:40.000Z" + }, + "payment_intent.payment_failed.json": { + "type": "payment.failed", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_procure_03" + }, + "owner": { + "id": "own_acme_ltd", + "type": "business" + }, + "payment": { + "payment_id": "pi_3QxFailCardDeclined", + "rail": "stripe", + "amount": { + "value": "230000", + "unit": "minor", + "currency": "USD" + }, + "status": "failed", + "rail_ref": { + "payment_intent": "pi_3QxFailCardDeclined", + "account": "acct_1Nw0rTh" + }, + "description": "Northwind Office Supply", + "failure_reason": "card_declined" + }, + "payee": { + "type": "merchant", + "id": "acct_1Nw0rTh" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxFailCardDeclined", + "object": "payment_intent", + "amount": 230000, + "currency": "usd", + "description": "Northwind Office Supply", + "status": "requires_payment_method", + "last_payment_error": { + "code": "card_declined", + "message": "Your card was declined." + }, + "metadata": { + "halvor_agent_id": "agt_procure_03", + "halvor_owner_id": "own_acme_ltd" + }, + "on_behalf_of": "acct_1Nw0rTh" + }, + "sha256": "sha256:aff5e0397ad01568cffe874a076f690cc767c7d49b98c6489f27dc98335c2d10" + } + ], + "occurred_at": "2024-10-17T12:00:12.000Z" + }, + "payment_intent.succeeded.json": { + "type": "payment.settled", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAbCdEfGhIjKlM", + "rail": "stripe", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "settled", + "rail_ref": { + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "shared_payment_token": "spt_1QxNoPqRsTuV", + "account": "acct_1Nw0rTh" + }, + "description": "Return flight SFO-AUS" + }, + "payee": { + "type": "merchant", + "id": "acct_1Nw0rTh" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "spt_1QxNoPqRsTuV" + }, + "on_behalf_of": "acct_1Nw0rTh", + "transfer_data": { + "destination": "acct_1Nw0rTh" + } + }, + "sha256": "sha256:cc578dd0725b385d749ce7816525c1aca36d05e2a7629089bd3c219eea84394f" + } + ], + "occurred_at": "2024-10-17T11:40:12.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "stripe_spt" + } + }, + "unattributed.json": { + "type": "payment.settled", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "unattributed" + }, + "owner": { + "id": "unattributed", + "type": "business" + }, + "payment": { + "payment_id": "pi_3QxNoMeta", + "rail": "stripe", + "amount": { + "value": "100", + "unit": "minor", + "currency": "USD" + }, + "status": "settled", + "rail_ref": { + "payment_intent": "pi_3QxNoMeta" + } + }, + "payee": { + "type": "merchant", + "name": "Stripe merchant" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxNoMeta", + "object": "payment_intent", + "amount": 100, + "currency": "usd", + "status": "succeeded", + "metadata": {} + }, + "sha256": "sha256:ad600225b2e8e350da3b094a9aca984c39a920e08aa2298916be848f89f0e374" + } + ], + "occurred_at": "2024-10-17T12:43:20.000Z" + }, + "case:named-card": { + "input": { + "id": "evt_1IA_created", + "type": "issuing_authorization.created", + "created": 1729161600, + "livemode": false, + "data": { + "object": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "halvor_agent_name": "Travel booking agent", + "halvor_agent_framework": "errandly-agents" + } + } + } + } + }, + "output": { + "type": "payment.authorized", + "source": { + "adapter": "stripe-issuing" + }, + "agent": { + "id": "agt_travel_12", + "name": "Travel booking agent", + "framework": "errandly-agents" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "iauth_1QxYz2AbCdEfGh", + "rail": "card", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "authorized", + "rail_ref": { + "authorization_id": "iauth_1QxYz2AbCdEfGh", + "processor": "stripe-issuing" + }, + "category": "mcc:4511", + "description": "Example Airways" + }, + "payee": { + "type": "merchant", + "name": "Example Airways", + "id": "acq_000123456789", + "country": "US", + "mcc": "4511", + "website": "https://example-airways.com" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "halvor_agent_name": "Travel booking agent", + "halvor_agent_framework": "errandly-agents" + } + } + }, + "sha256": "sha256:1a0e41f151651f1fe2f3b672da623c10aaa1a4801085a6d0eaf3e053697ecf73" + } + ], + "occurred_at": "2024-10-17T10:40:00.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "card", + "issuer": "Stripe Issuing", + "last4": "4242", + "network": "visa" + } + } + }, + "case:connect-spt": { + "input": { + "id": "evt_1PI_succeeded", + "type": "payment_intent.succeeded", + "created": 1729165212, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "us", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "spt_123", + "halvor_agent_name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + "on_behalf_of": "acct_1Dest", + "transfer_data": { + "destination": "acct_1Dest" + } + } + } + }, + "output": { + "type": "payment.settled", + "source": { + "adapter": "stripe" + }, + "agent": { + "id": "agt_travel_12", + "name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + "owner": { + "id": "own_u_4410", + "type": "person" + }, + "payment": { + "payment_id": "pi_3QxAbCdEfGhIjKlM", + "rail": "stripe", + "amount": { + "value": "41200", + "unit": "minor", + "currency": "USD" + }, + "status": "settled", + "rail_ref": { + "payment_intent": "pi_3QxAbCdEfGhIjKlM", + "shared_payment_token": "spt_123", + "account": "acct_1Dest" + }, + "description": "Return flight SFO-AUS" + }, + "payee": { + "type": "merchant", + "id": "acct_1Dest" + }, + "evidence": [ + { + "kind": "stripe.object", + "format": "json", + "value": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "us", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "spt_123", + "halvor_agent_name": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + }, + "on_behalf_of": "acct_1Dest", + "transfer_data": { + "destination": "acct_1Dest" + } + }, + "sha256": "sha256:11860d1d40b183b73165b591fb9debbb88e7247c92630a69862fe60f4beab51a" + } + ], + "occurred_at": "2024-10-17T11:40:12.000Z", + "instruction": { + "id": "ins_8890", + "hash": "sha256:dbcbe4f4a4fe28f78818c73b81468cc094d14add4dd09ba8ab6b1d24b0494bcb" + }, + "instrument": { + "type": "stripe_spt" + } + } + } +} diff --git a/tests/fixtures/stripe/issuing_authorization.created.json b/tests/fixtures/stripe/issuing_authorization.created.json new file mode 100644 index 0000000..9914eb4 --- /dev/null +++ b/tests/fixtures/stripe/issuing_authorization.created.json @@ -0,0 +1,34 @@ +{ + "id": "evt_1IA_created", + "type": "issuing_authorization.created", + "created": 1729161600, + "livemode": false, + "data": { + "object": { + "id": "iauth_1QxYz2AbCdEfGh", + "object": "issuing.authorization", + "amount": 41200, + "currency": "usd", + "approved": true, + "status": "pending", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789", + "url": "https://example-airways.com" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890" + } + } + } + } +} diff --git a/tests/fixtures/stripe/issuing_authorization.updated.json b/tests/fixtures/stripe/issuing_authorization.updated.json new file mode 100644 index 0000000..a883689 --- /dev/null +++ b/tests/fixtures/stripe/issuing_authorization.updated.json @@ -0,0 +1,32 @@ +{ + "id": "evt_1IA_updated", + "type": "issuing_authorization.updated", + "created": 1729161660, + "livemode": false, + "data": { + "object": { + "id": "iauth_1QxDeclined", + "object": "issuing.authorization", + "amount": 9900, + "currency": "usd", + "approved": false, + "status": "closed", + "merchant_data": { + "name": "Blocked Merchant", + "category_code": "7995", + "country": "US", + "network_id": "acq_blocked" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + } + } +} diff --git a/tests/fixtures/stripe/issuing_transaction.created.json b/tests/fixtures/stripe/issuing_transaction.created.json new file mode 100644 index 0000000..e631a24 --- /dev/null +++ b/tests/fixtures/stripe/issuing_transaction.created.json @@ -0,0 +1,32 @@ +{ + "id": "evt_1IT_created", + "type": "issuing_transaction.created", + "created": 1729162200, + "livemode": false, + "data": { + "object": { + "id": "ipi_1QxCapture", + "object": "issuing.transaction", + "amount": -41200, + "currency": "usd", + "type": "capture", + "authorization": "iauth_1QxYz2AbCdEfGh", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789" + }, + "card": { + "id": "ic_1QxCard", + "last4": "4242", + "brand": "visa", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + } + } +} diff --git a/tests/fixtures/stripe/issuing_transaction.refund.json b/tests/fixtures/stripe/issuing_transaction.refund.json new file mode 100644 index 0000000..7201e94 --- /dev/null +++ b/tests/fixtures/stripe/issuing_transaction.refund.json @@ -0,0 +1,29 @@ +{ + "id": "evt_1IT_refund", + "type": "issuing_transaction.created", + "created": 1729163000, + "livemode": false, + "data": { + "object": { + "id": "ipi_1QxRefund", + "object": "issuing.transaction", + "amount": 5000, + "currency": "usd", + "type": "refund", + "merchant_data": { + "name": "Example Airways", + "category_code": "4511", + "country": "US", + "network_id": "acq_000123456789" + }, + "card": { + "id": "ic_1QxCard", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + } + } +} diff --git a/tests/fixtures/stripe/payment_intent.amount_capturable_updated.json b/tests/fixtures/stripe/payment_intent.amount_capturable_updated.json new file mode 100644 index 0000000..1a875ec --- /dev/null +++ b/tests/fixtures/stripe/payment_intent.amount_capturable_updated.json @@ -0,0 +1,20 @@ +{ + "id": "evt_1PI_capturable", + "type": "payment_intent.amount_capturable_updated", + "created": 1729165000, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxAuthHold", + "object": "payment_intent", + "amount": 5000, + "currency": "usd", + "status": "requires_capture", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person" + } + } + } +} diff --git a/tests/fixtures/stripe/payment_intent.payment_failed.json b/tests/fixtures/stripe/payment_intent.payment_failed.json new file mode 100644 index 0000000..586b090 --- /dev/null +++ b/tests/fixtures/stripe/payment_intent.payment_failed.json @@ -0,0 +1,25 @@ +{ + "id": "evt_1PI_failed", + "type": "payment_intent.payment_failed", + "created": 1729166412, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxFailCardDeclined", + "object": "payment_intent", + "amount": 230000, + "currency": "usd", + "description": "Northwind Office Supply", + "status": "requires_payment_method", + "last_payment_error": { + "code": "card_declined", + "message": "Your card was declined." + }, + "metadata": { + "halvor_agent_id": "agt_procure_03", + "halvor_owner_id": "own_acme_ltd" + }, + "on_behalf_of": "acct_1Nw0rTh" + } + } +} diff --git a/tests/fixtures/stripe/payment_intent.succeeded.json b/tests/fixtures/stripe/payment_intent.succeeded.json new file mode 100644 index 0000000..e9fb653 --- /dev/null +++ b/tests/fixtures/stripe/payment_intent.succeeded.json @@ -0,0 +1,25 @@ +{ + "id": "evt_1PI_succeeded", + "type": "payment_intent.succeeded", + "created": 1729165212, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxAbCdEfGhIjKlM", + "object": "payment_intent", + "amount": 41200, + "currency": "usd", + "description": "Return flight SFO-AUS", + "status": "succeeded", + "metadata": { + "halvor_agent_id": "agt_travel_12", + "halvor_owner_id": "own_u_4410", + "halvor_owner_type": "person", + "halvor_instruction_id": "ins_8890", + "shared_payment_token": "spt_1QxNoPqRsTuV" + }, + "on_behalf_of": "acct_1Nw0rTh", + "transfer_data": { "destination": "acct_1Nw0rTh" } + } + } +} diff --git a/tests/fixtures/stripe/unattributed.json b/tests/fixtures/stripe/unattributed.json new file mode 100644 index 0000000..296713d --- /dev/null +++ b/tests/fixtures/stripe/unattributed.json @@ -0,0 +1,16 @@ +{ + "id": "evt_1PI_unattr", + "type": "payment_intent.succeeded", + "created": 1729169000, + "livemode": false, + "data": { + "object": { + "id": "pi_3QxNoMeta", + "object": "payment_intent", + "amount": 100, + "currency": "usd", + "status": "succeeded", + "metadata": {} + } + } +} diff --git a/tests/test_stripe.py b/tests/test_stripe.py new file mode 100644 index 0000000..e5a4b53 --- /dev/null +++ b/tests/test_stripe.py @@ -0,0 +1,195 @@ +"""Stripe adapter, using the same fixtures as the Node.js SDK. + +tests/fixtures/stripe/*.json are copied from the Node.js SDK's Stripe fixtures, and expected.json +is what the Node.js `mapStripeEvent` returns for each of them, so both SDKs map Stripe alike. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from halvorai_ingest import HalvorClient, agent_context, generate_source_key +from halvorai_ingest.stripe import ( + STRIPE_HANDLED_TYPES, + map_stripe_event, + stripe_webhook_handler, + tag_issuing_card, + tag_payment_intent, +) +from halvorai_ingest.validate import validate_event + +FIXTURES = Path(__file__).resolve().parent / "fixtures" / "stripe" +EXPECTED: dict[str, Any] = json.loads((FIXTURES / "expected.json").read_text(encoding="utf-8")) +FILES = sorted(p.name for p in FIXTURES.glob("*.json") if p.name != "expected.json") + + +def load(name: str) -> dict[str, Any]: + data: dict[str, Any] = json.loads((FIXTURES / name).read_text(encoding="utf-8")) + return data + + +def client_with(sent: list[dict[str, Any]], errors: list[dict[str, Any]]) -> HalvorClient: + return HalvorClient(source_key=generate_source_key(), sink=sent.extend, on_error=errors.append, exit_hook=False) + + +@pytest.mark.parametrize("name", FILES) +def test_matches_the_node_sdk(name: str) -> None: + assert map_stripe_event(load(name)) == EXPECTED[name] + + +@pytest.mark.parametrize("case", [k for k in EXPECTED if k.startswith("case:")]) +def test_matches_the_node_sdk_edge_cases(case: str) -> None: + assert map_stripe_event(EXPECTED[case]["input"]) == EXPECTED[case]["output"] + + +@pytest.mark.parametrize( + ("name", "ape_type", "status", "adapter"), + [ + ("payment_intent.amount_capturable_updated.json", "payment.authorized", "authorized", "stripe"), + ("payment_intent.succeeded.json", "payment.settled", "settled", "stripe"), + ("payment_intent.payment_failed.json", "payment.failed", "failed", "stripe"), + ("charge.refunded.json", "payment.refunded", "refunded", "stripe"), + ("charge.dispute.created.json", "payment.disputed", "disputed", "stripe"), + ("issuing_authorization.created.json", "payment.authorized", "authorized", "stripe-issuing"), + ("issuing_authorization.updated.json", "payment.failed", "failed", "stripe-issuing"), + ("issuing_transaction.created.json", "payment.settled", "settled", "stripe-issuing"), + ("issuing_transaction.refund.json", "payment.refunded", "refunded", "stripe-issuing"), + ], +) +def test_types(name: str, ape_type: str, status: str, adapter: str) -> None: + mapped = map_stripe_event(load(name)) + assert mapped is not None + assert (mapped["type"], mapped["payment"]["status"], mapped["source"]["adapter"]) == (ape_type, status, adapter) + + +def test_ignores_unrelated_types_and_bad_input() -> None: + assert map_stripe_event({"type": "customer.created", "data": {"object": {"id": "cus_x"}}}) is None + assert map_stripe_event({"type": "payment_intent.succeeded", "data": {"object": "pi_x"}}) is None + assert map_stripe_event("not an event") is None + assert len(STRIPE_HANDLED_TYPES) == 8 + + +def test_unattributed_without_metadata() -> None: + mapped = map_stripe_event(load("unattributed.json")) + assert mapped is not None + assert mapped["agent"]["id"] == "unattributed" + assert mapped["owner"]["id"] == "unattributed" + + +def test_issuing_agent_name_and_framework_from_card_metadata() -> None: + event = load("issuing_authorization.created.json") + event["data"]["object"]["card"]["metadata"].update( + halvor_agent_name="Travel booking agent", halvor_agent_framework="errandly-agents" + ) + named = map_stripe_event(event) + assert named is not None + assert named["agent"] == {"id": "agt_travel_12", "name": "Travel booking agent", "framework": "errandly-agents"} + plain = map_stripe_event(load("issuing_authorization.created.json")) + assert plain is not None + assert plain["agent"] == {"id": "agt_travel_12"} + + +class _StripeObjectLike: + """Stands in for stripe.Event, which converts with to_dict().""" + + def __init__(self, data: dict[str, Any]) -> None: + self._data = data + + def to_dict(self) -> dict[str, Any]: + return self._data + + +def test_accepts_stripe_objects() -> None: + name = "payment_intent.succeeded.json" + assert map_stripe_event(_StripeObjectLike(load(name))) == EXPECTED[name] + + +@pytest.mark.parametrize("name", FILES) +def test_every_fixture_is_a_valid_signed_event(name: str) -> None: + sent: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + client = client_with(sent, errors) + event_id = client.stripe(load(name)) + client.flush(timeout=5) + client.close() + assert errors == [] + assert len(sent) == 1 + event = sent[0]["event"] + assert event["id"] == event_id + assert validate_event(event) == [] + assert event["source"]["adapter"] == EXPECTED[name]["source"]["adapter"] + + +def test_client_method_and_handler() -> None: + sent: list[dict[str, Any]] = [] + errors: list[dict[str, Any]] = [] + client = client_with(sent, errors) + handler = stripe_webhook_handler(client) + assert handler({"type": "invoice.paid", "data": {"object": {}}}) is None + event_id = handler(load("payment_intent.succeeded.json")) + assert isinstance(event_id, str) and event_id.startswith("evt_") + client.flush(timeout=5) + client.close() + assert errors == [] + payment = sent[0]["event"]["payment"] + assert sent[0]["event"]["type"] == "payment.settled" + assert payment["payment_id"] == "pi_3QxAbCdEfGhIjKlM" + assert payment["amount"] == {"value": "41200", "unit": "minor", "currency": "USD"} + + +def test_tag_payment_intent_from_context() -> None: + with agent_context( + agent={"id": "agt_ctx_1", "name": "Ctx"}, + owner={"id": "own_ctx_1", "type": "business"}, + instruction={"id": "ins_ctx_1", "text": "buy coffee"}, + ): + tagged = tag_payment_intent({"amount": 500, "currency": "usd", "metadata": {"order": "1"}}) + assert tagged["amount"] == 500 + assert tagged["metadata"] == { + "order": "1", + "halvor_agent_id": "agt_ctx_1", + "halvor_agent_name": "Ctx", + "halvor_owner_id": "own_ctx_1", + "halvor_owner_type": "business", + "halvor_instruction_id": "ins_ctx_1", + } + + +def test_tag_issuing_card_overrides_win_over_context() -> None: + params = {"currency": "usd", "type": "virtual"} + with agent_context(agent={"id": "agt_outer"}, owner={"id": "own_outer", "type": "person"}): + tagged = tag_issuing_card(params, agent_id="agt_override") + assert tagged["metadata"]["halvor_agent_id"] == "agt_override" + assert tagged["metadata"]["halvor_owner_id"] == "own_outer" + assert "metadata" not in params # the input is not changed + + +def test_tag_issuing_card_name_and_framework_within_ape_limits() -> None: + with agent_context( + agent={"id": "agt_ctx", "name": "Shopping agent", "framework": "errandly-agents"}, + owner={"id": "own_ctx", "type": "business"}, + ): + from_ctx = tag_issuing_card({"currency": "usd", "type": "virtual"}) + assert from_ctx["metadata"]["halvor_agent_name"] == "Shopping agent" + assert from_ctx["metadata"]["halvor_agent_framework"] == "errandly-agents" + + long = tag_issuing_card({"currency": "usd"}, agent_id="agt_x", agent_name="n" * 300, framework="f" * 100) + assert len(long["metadata"]["halvor_agent_name"]) == 128 + assert len(long["metadata"]["halvor_agent_framework"]) == 64 + assert all(len(k) <= 40 for k in long["metadata"]) + + +def test_tagged_card_round_trips_to_a_named_agent() -> None: + meta = tag_issuing_card( + {}, agent_id="agt_rt", agent_name="Round trip", framework="fw", owner_id="own_rt", owner_type="person" + )["metadata"] + event = load("issuing_transaction.created.json") + event["data"]["object"]["card"] = {"metadata": meta} + mapped = map_stripe_event(event) + assert mapped is not None + assert mapped["agent"] == {"id": "agt_rt", "name": "Round trip", "framework": "fw"} + assert mapped["owner"] == {"id": "own_rt", "type": "person"} diff --git a/uv.lock b/uv.lock index 7927e88..91d074b 100644 --- a/uv.lock +++ b/uv.lock @@ -323,7 +323,7 @@ wheels = [ [[package]] name = "halvorai-ingest" -version = "0.4.1" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "cryptography" },