@cardonjs/payments 0.0.0-stage → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/llms.txt ADDED
@@ -0,0 +1,151 @@
1
+ # @cardonjs/payments
2
+
3
+ The payments interface of Cardón: the `PaymentProvider` type every payment adapter returns (hosted
4
+ checkout, webhook signals, payment snapshots, refunds), the input checks adapters run before any
5
+ I/O, the status rules that decide which snapshot may replace a stored one, the shared contract
6
+ suite for adapters and a test-only in-memory provider. Business logic receives a `PaymentProvider`
7
+ through the context and never touches a provider SDK. Standard web APIs only (Workers, Node, Bun,
8
+ Deno); it does not depend on `hono`.
9
+
10
+ Full documentation: README.md in this package.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @cardonjs/payments @cardonjs/core
16
+ ```
17
+
18
+ `@cardonjs/core` is a required peer (`Money`, errors, HMAC). `@cardonjs/testing` is an optional peer,
19
+ only needed by `@cardonjs/payments/contract` (in adapter tests).
20
+
21
+ ## Exports
22
+
23
+ ### `@cardonjs/payments`
24
+ - `PaymentProvider` (type): `createCheckout(input: CheckoutInput): Promise<Checkout>`,
25
+ `verifyWebhook(request: Request): Promise<WebhookResult>`,
26
+ `getPayment(paymentId: string): Promise<PaymentSnapshot | null>` (`null`: unknown id),
27
+ `refund(paymentId: string, input: RefundInput): Promise<{ readonly refundId: string }>`.
28
+ `Checkout` is `{ id, redirectUrl }` (an https URL on the provider).
29
+ - `PAYMENT_STATUSES`: frozen array of every `PaymentStatus`: `pending`, `approved`, `rejected`,
30
+ `cancelled`, `refunded`, `in_dispute`, `charged_back`.
31
+ - `canTransition(current, next)`: true when a snapshot with status `next` may replace a stored one
32
+ with `current`. `pending` → every other status; `approved` → `in_dispute`, `refunded`,
33
+ `charged_back`; `in_dispute` → `approved`, `refunded`, `charged_back`; the rest are final. The
34
+ same status and unknown values are `false`.
35
+ - `isNewerSnapshot(stored: PaymentSnapshot | null, next)`: the check to store a snapshot. `true`
36
+ when `stored` is `null`; `false` when `next.updatedAt` is earlier; otherwise `true` when
37
+ `canTransition` allows it, or the status is the same and `next.refunded.amount` grew. Throws a
38
+ `TypeError` when the ids differ.
39
+ - `validCheckoutInput(input)` (a frozen copy, read once) / `assertValidCheckoutInput(input)`.
40
+ - `isValidPaymentId(id)` / `assertValidPaymentId(id)`: `^[A-Za-z0-9_-]{1,64}$`.
41
+ - `validRefundInput(input, payment?)` / `assertValidRefundInput(input, payment?)`: the shape, and
42
+ with `payment` (`{ amount }`) also that the amount has the payment's currency.
43
+ - `checkoutTotal(input)`: the sum of `quantity × unitPrice`, as `Money`.
44
+ - `isHttpsUrlString(value)`: true for an https URL (printable ASCII, no credentials).
45
+ - The validation helpers throw a `TypeError` whose message never includes a value.
46
+ - Types: `Checkout`, `CheckoutInput`, `CheckoutItem`, `PaymentSignal`, `PaymentSnapshot`,
47
+ `PaymentStatus`, `RefundInput`, `RefundablePayment`, `WebhookResult`.
48
+
49
+ Shapes:
50
+ - `CheckoutInput`: `reference` (your order id, 1 to 256 characters of `A-Z a-z 0-9 _ - : .`),
51
+ `items` (1 to 100, one currency; each with optional `id`, `title` of 1 to 256 characters,
52
+ integer `quantity` 1 to 10 000, `unitPrice: Money` > 0), `returnUrl` (https), optional
53
+ `payerEmail`, optional `expiresAt` (a `Date` in the future), `idempotencyKey` (1 to 64
54
+ characters of `A-Z a-z 0-9 _ - : .`).
55
+ - `PaymentSnapshot`: `id`, `reference` (`string | null`), `status`, `amount`, `refunded` (same
56
+ currency, 0 when none), `live`, `createdAt`, `approvedAt` (`null` until approved), `updatedAt`,
57
+ `providerStatus` (the provider's raw status).
58
+ - `WebhookResult`: `{ valid: false }` or `{ valid: true, signal }`, where `signal` is
59
+ `{ kind: "payment", paymentId }` or `null` (a topic the app ignores).
60
+ - `RefundInput`: optional `amount` (omitted: refund the rest) and `idempotencyKey`.
61
+
62
+ ### `@cardonjs/payments/contract`
63
+ - `paymentsContract`: the shared contract cases every adapter must pass; run each with
64
+ `c.run(harness)` under its `c.name` in the adapter's test runner. Needs `@cardonjs/testing`.
65
+ - `PaymentsContractHarness` (type): `create()`, `seedPayment({ reference, status, amount })`
66
+ (status `"approved" | "pending"`; returns the payment id), `signedWebhook(paymentId)`,
67
+ `forgedWebhooks(paymentId)`, `ignoredWebhooks()`.
68
+
69
+ ### `@cardonjs/payments/testing`
70
+ - `fakePayments({ webhookSecret?, live? })`: test-only in-memory `PaymentProvider` that passes the
71
+ contract, plus controls. `webhookSecret` defaults to `"fake-webhook-secret"`, `live` to `false`.
72
+ - `settle(checkoutId, status)`: the buyer pays (or not); creates a payment with the checkout's
73
+ total and returns its id. Call it again for another attempt (a new payment id).
74
+ - `setStatus(paymentId, status)`: the provider changes a payment (`refunded` refunds it all).
75
+ - `webhookFor(paymentId)`: a `Promise` of a signed `POST` `Request` (`?data.id=…&type=payment`,
76
+ `x-request-id`, `x-signature: ts=…,v1=…`).
77
+ - `checkouts()`: the validated inputs of the checkouts created, in order.
78
+ - Types: `FakePayments`, `FakePaymentsOptions`.
79
+
80
+ ## Minimal example
81
+
82
+ ```ts
83
+ import { ServiceUnavailableError, UnauthorizedError } from "@cardonjs/core";
84
+ import { isNewerSnapshot, type PaymentProvider, type PaymentSnapshot } from "@cardonjs/payments";
85
+
86
+ /** Your payments table: one row per payment id. */
87
+ interface StoredPayments {
88
+ get(id: string): Promise<PaymentSnapshot | null>;
89
+ /** Inserts when `expected` is null, else a compare-and-set on the row read. */
90
+ save(expected: PaymentSnapshot | null, next: PaymentSnapshot): Promise<boolean>;
91
+ }
92
+
93
+ /** The core of a webhook route: call it with `c.var.adapters.payments` and `c.req.raw`. */
94
+ export async function receiveWebhook(
95
+ payments: PaymentProvider,
96
+ stored: StoredPayments,
97
+ request: Request,
98
+ ): Promise<void> {
99
+ const result = await payments.verifyWebhook(request);
100
+ if (!result.valid) throw new UnauthorizedError("Invalid signature."); // 401
101
+ if (result.signal === null) return; // a topic we ignore: answer 200
102
+ // The webhook only says "payment X changed": the provider says what it is now.
103
+ const payment = await payments.getPayment(result.signal.paymentId);
104
+ if (payment === null) throw new ServiceUnavailableError("The payment is not readable yet.");
105
+ const current = await stored.get(payment.id);
106
+ if (!isNewerSnapshot(current, payment)) return; // out of order or duplicated
107
+ if (!(await stored.save(current, payment))) {
108
+ throw new ServiceUnavailableError("The payment changed concurrently."); // delivered again
109
+ }
110
+ }
111
+ ```
112
+
113
+ ## Rules and common mistakes
114
+
115
+ - Never take an amount, price, currency or reference from the client. Build `CheckoutInput` from
116
+ the server's own order. Amounts are core `Money` values (integer minor units).
117
+ - A return URL never marks anything as paid: its query string comes from the browser.
118
+ - A webhook is a signal, never data. `verifyWebhook` reads only the URL and headers, never the
119
+ body. Status, amount and reference come from `getPayment`.
120
+ - Invalid signature: answer 401 and log at `info`. `signal: null`: answer 200. A signed signal
121
+ whose payment `getPayment` does not return yet (`null`): answer 503, so it is delivered again.
122
+ - Make the webhook route public in the guard (e.g. `public: ["POST /v1/webhooks/payments"]`); the
123
+ signature is its authentication. The checkout route loads the order with the authenticated
124
+ identity: another buyer's order id is a 404.
125
+ - Store one row per payment id, never one per order. One checkout can produce several payments.
126
+ - Store a snapshot only when `isNewerSnapshot(stored, next)` is true, with a compare-and-set on
127
+ the row read (status, refunded, updated_at). When it matches no row, answer 503, never 200.
128
+ - An order is paid when one of its payments is `approved`, `live` in production, with exactly the
129
+ order's total and currency. Reject `live: false` in production (`live` is the provider's own
130
+ test-mode flag, not proof that the accounts are real: see the adapter's notes on testing). Log an approved payment that
131
+ does not match at `error`.
132
+ - A second approved payment of the same order is flagged for a refund, never ignored.
133
+ - Keep one open checkout per order: store the `Checkout` on the order and reuse it. Keep every
134
+ value of the input stable across retries of one idempotency key (an `expiresAt` of
135
+ "now + 30 minutes" is not).
136
+ - Refunds: persist the idempotency key with the refund request and reuse it after a timeout. The
137
+ same key and input return the same `refundId` and refund once; the same key with another input
138
+ is a `ConflictError`.
139
+ - Errors: input checkable without the provider is a `TypeError`; provider unreachable, timeout,
140
+ 5xx or rejected credentials is `ServiceUnavailableError`; a refund the provider refuses is
141
+ `ConflictError`; a refund of an unknown payment is `NotFoundError`.
142
+ - Never show `providerStatus` to buyers; it is for support and logs.
143
+ - `fakePayments` is test-only: nothing is charged and payments live in memory. The signature of
144
+ `webhookFor` does not cover the path: send its query and headers to your own route.
145
+
146
+ ## Out of scope
147
+
148
+ - No provider implementation: adapters such as `@cardonjs/payments-mercadopago` provide it.
149
+ - No routes, no order storage and no payments table: those are the app's.
150
+ - No webhook inbox (store, answer 200, process in a job): that comes with `@cardonjs/jobs`.
151
+ - Whether a refund amount fits what is left is the provider's to decide (`ConflictError`).
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@cardonjs/payments",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.11",
4
+ "description": "Payments interface for Cardón apps: PaymentProvider (hosted checkout, webhook signals, payment snapshots, refunds), input validation, status transitions, the shared adapter contract suite and a test-only fake.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/cardonjs/cardon.git",
9
+ "directory": "packages/payments"
10
+ },
11
+ "homepage": "https://github.com/cardonjs/cardon/tree/main/packages/payments#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/cardonjs/cardon/issues"
14
+ },
15
+ "type": "module",
16
+ "sideEffects": false,
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "default": "./dist/index.js"
21
+ },
22
+ "./contract": {
23
+ "types": "./dist/contract.d.ts",
24
+ "default": "./dist/contract.js"
25
+ },
26
+ "./testing": {
27
+ "types": "./dist/testing.d.ts",
28
+ "default": "./dist/testing.js"
29
+ }
30
+ },
31
+ "files": [
32
+ "dist",
33
+ "llms.txt"
34
+ ],
35
+ "publishConfig": {
36
+ "access": "public"
37
+ },
38
+ "peerDependencies": {
39
+ "@cardonjs/core": "^0.5.1",
40
+ "@cardonjs/testing": "^0.7.0"
41
+ },
42
+ "peerDependenciesMeta": {
43
+ "@cardonjs/testing": {
44
+ "optional": true
45
+ }
46
+ },
47
+ "devDependencies": {
48
+ "@hono/zod-openapi": "1.6.3",
49
+ "@scalar/hono-api-reference": "0.12.20",
50
+ "hono": "4.13.18",
51
+ "typescript": "7.0.2",
52
+ "vitest": "5.1.0",
53
+ "zod": "4.6.7",
54
+ "@cardonjs/auth": "0.2.7",
55
+ "@cardonjs/config": "0.0.0",
56
+ "@cardonjs/core": "0.5.1",
57
+ "@cardonjs/testing": "0.7.0"
58
+ },
59
+ "scripts": {
60
+ "build": "tsc -p tsconfig.build.json",
61
+ "typecheck": "tsc -p tsconfig.json --noEmit",
62
+ "test": "vitest run"
63
+ }
6
64
  }