@pplethai/cli 0.20.0 → 0.22.0

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.
Files changed (35) hide show
  1. package/README.md +5 -3
  2. package/dist/bin.js +132 -131
  3. package/package.json +1 -1
  4. package/templates/golden-path/CLAUDE.md +6 -2
  5. package/templates/golden-path/README.md +4 -1
  6. package/templates/golden-path/src/email.ts +4 -179
  7. package/templates/golden-path/src/index.ts +6 -0
  8. package/templates/golden-path/src/party-email.ts +183 -0
  9. package/templates/golden-path/src/payment.ts +162 -29
  10. package/templates/golden-path/test/fixtures/overlay/platform/payments/entry.md +1 -1
  11. package/templates/golden-path/test/fixtures/overlay/platform/payments/mocks/responses.json +27 -0
  12. package/templates/golden-path/test/payment-app.test.ts +1 -0
  13. package/templates/golden-path/test/payment.test.ts +107 -0
  14. package/templates/payment-bridge/.github/workflows/ci.yml +21 -0
  15. package/templates/payment-bridge/CLAUDE.md +9 -0
  16. package/templates/payment-bridge/README.md +57 -0
  17. package/templates/payment-bridge/docs/verify-webhook.md +80 -0
  18. package/templates/payment-bridge/docs/verify-webhook.ts +29 -0
  19. package/templates/payment-bridge/gitignore +5 -0
  20. package/templates/payment-bridge/package-lock.json +4198 -0
  21. package/templates/payment-bridge/package.json +21 -0
  22. package/templates/payment-bridge/src/bridge-key.ts +18 -0
  23. package/templates/payment-bridge/src/env.ts +14 -0
  24. package/templates/payment-bridge/src/index.ts +39 -0
  25. package/templates/payment-bridge/src/platform.ts +49 -0
  26. package/templates/payment-bridge/src/webhook.ts +86 -0
  27. package/templates/payment-bridge/test/docs.test.ts +9 -0
  28. package/templates/payment-bridge/test/fixtures/payments-responses.json +98 -0
  29. package/templates/payment-bridge/test/harness.ts +78 -0
  30. package/templates/payment-bridge/test/inbound.test.ts +138 -0
  31. package/templates/payment-bridge/test/webhook.test.ts +174 -0
  32. package/templates/payment-bridge/tsconfig.json +22 -0
  33. package/templates/payment-bridge/vitest.config.ts +8 -0
  34. package/templates/payment-bridge/wrangler.jsonc +15 -0
  35. package/templates/payment-bridge.version +1 -0
@@ -1,6 +1,6 @@
1
1
  // Payments (docs/adr/0037). The helpers below wrap the Private Platform Service
2
2
  // `platform/payments`: `createPayment`, `getPayment`, `issueReceipt`,
3
- // `rejectPayment`, `createCheckoutPass`, `verifyPaymentEvent` and `paymentHandler`. Each answers
3
+ // `rejectPayment`, `createCheckoutPass`, `acceptPayment`, `verifyPaymentEvent` and `paymentHandler`. Each answers
4
4
  // `{ ok: true, … }` or `{ ok: false, reason }`. Offline (`npm run dev` with a
5
5
  // Persona) they answer from the entry's mocks. The rest of this comment is the
6
6
  // outcome the platform sends you.
@@ -24,9 +24,12 @@
24
24
  // type you do not handle: later outcomes arrive as new types.
25
25
  //
26
26
  // A paid Payment has a Payment Voucher, which is not a receipt. The legal
27
- // Receipt is issued when YOU ask: `POST platform/payments/<id>/receipt`, from
28
- // this handler or after your own checks. Asking twice is safe. The platform
29
- // then calls you with `payment.receipt_issued`.
27
+ // Receipt comes when the Payment's `receiptTiming` says. With
28
+ // `receiptTiming: "on_payment"` the platform issues it the moment the Payment is
29
+ // paid (and you cannot reject it then). Otherwise (`"later"`, the default) it
30
+ // is issued when YOU ask: `POST platform/payments/<id>/receipt`, from this
31
+ // handler or after your own checks. Asking twice is safe. Either way the
32
+ // platform then calls you with `payment.receipt_issued`.
30
33
  //
31
34
  // The event carries what the Receipt will print and no more: the Payer's full
32
35
  // name and a masked citizen ID. You never receive the full citizen ID, and you
@@ -58,9 +61,38 @@
58
61
  // the Replacement, whose `receipt.replaces` names the Receipt it replaces. The
59
62
  // Payment stays `paid`; its lookup's `receipt` is now the Replacement.
60
63
  //
61
- // A `paid` event with `mode: "test"` is a sandbox payment from a Draft or Beta
62
- // app. No money moved and no legal Receipt will exist for it. Only a Live
63
- // app's Payments are `live`.
64
+ // A Payment that expires. If your app holds something for the Payer while they
65
+ // pay (stock, a ticket, a slot), give `createPayment` an `expiresAt` (10 minutes
66
+ // to 30 days ahead, with an explicit offset). The Checkout Page then shows the
67
+ // Payer a deadline (a time, not a countdown), starts no payment within 2
68
+ // minutes of it, and every Charge is cut to end by it; a Checkout Pass
69
+ // asked for after it is `not_payable`. The Payment turns `expired` and you get
70
+ // `payment.expired` once nothing opened before `expiresAt` can still be paid:
71
+ // usually within one sweep (minutes) of `expiresAt`, never more than about 60
72
+ // minutes after it. So run your OWN timer for your hold, and release it at
73
+ // `expiresAt` without waiting for the event; treat the event as the platform's
74
+ // confirmation that no payment is pending.
75
+ //
76
+ // `expired` is final. Money the Gateway confirms AFTER `expiresAt` (a QR paid at
77
+ // the last second, a notification delayed past the deadline) does not pay the
78
+ // Payment: it becomes a **Late Payment**, state `late`, with no Payment Voucher
79
+ // yet, and you hear `payment.late` (payer name, `paidAt`). Your hold may be gone,
80
+ // so decide: `acceptPayment(id)` if you can still serve it (the Payment is `paid`,
81
+ // the Voucher is issued and you hear `payment.paid`), or `rejectPayment(id)` if you
82
+ // cannot (a card is refunded; a QR payment becomes a Refund Owed). Check your hold
83
+ // in your `payment.late` handler and answer one or the other. A Late Payment counts
84
+ // toward the Payer's yearly cap while it waits. Say nothing and it reaches the
85
+ // Finance Officer as Undecided after the party's deadline; nothing is refunded
86
+ // automatically. You hear exactly one of `payment.paid` (on time, or a Late Payment
87
+ // you accepted) or `payment.expired`; `payment.late` comes first for a late
88
+ // `payment.paid` or `payment.rejected`.
89
+ //
90
+ // A `paid` event with `mode: "test"` is a sandbox payment. No money moved and
91
+ // no legal Receipt will exist for it. A Draft or Beta app's Payments are always
92
+ // `test`; a Live app's are `live` unless it created the Payment with
93
+ // `test: true`, to try its payment flow in production. So check `payment.mode`
94
+ // (the verified payment from `verifyPaymentEvent`, not just the event) before you
95
+ // hand over anything real (a membership, goods, access) for a Payment.
64
96
 
65
97
  import { callService, platformError, type CallServiceEnv, type PlatformErrorCode } from "./call-service";
66
98
  import type { Env } from "./env";
@@ -107,10 +139,40 @@ interface PaymentInputBase {
107
139
  reference: string;
108
140
  /** Where the Checkout Page sends the Payer afterwards. `https` (`http://localhost` locally). */
109
141
  returnUrl: string;
142
+ /**
143
+ * Ask for a test Payment: sandbox Gateway, `TEST-…` Receipt, no real money. Allowed
144
+ * in every tier, so a Live app can test its flow in production. Leave it out (or
145
+ * `false`) for the tier's own mode: `live` at Live, `test` in Draft and Beta (a
146
+ * `false` never makes a Draft or Beta Payment live). Check `payment.mode` before
147
+ * handing over anything real.
148
+ */
149
+ test?: boolean;
150
+ /**
151
+ * Optional: when the payable window closes, if your app holds something for the
152
+ * Payer while they pay (stock, a ticket, a slot). An ISO 8601 string with an
153
+ * explicit offset (`2026-12-01T14:30:00+07:00`, or `Z`) or a `Date`. It must be
154
+ * at least 10 minutes and at most 30 days from now, or the platform answers
155
+ * `invalid_payment` with `field: "expiresAt"`. Fixed at creation: there is no way to
156
+ * extend it, so create a new Payment when the Payer needs more time. See
157
+ * "A Payment that expires" at the top of this file.
158
+ */
159
+ expiresAt?: string | Date;
160
+ /**
161
+ * Optional: who issues the legal Receipt. `"later"` (the default): you do, with
162
+ * `issueReceipt`, at once or after your own checks, and you may `rejectPayment`
163
+ * until then. `"on_payment"`: the platform issues it the moment the Payment is
164
+ * paid, so there is nothing to call, and it cannot be rejected after (only a
165
+ * Finance Officer can refund it). A payment that took the Payer over the yearly
166
+ * cap is the exception: it is left for you or the Finance Officer to decide.
167
+ */
168
+ receiptTiming?: ReceiptTiming;
110
169
  }
111
170
 
171
+ /** When a Payment's Receipt is issued: by your app (`later`), or by the platform the moment it is paid (`on_payment`). */
172
+ export type ReceiptTiming = "later" | "on_payment";
173
+
112
174
  /**
113
- * What you send to create a Payment. Every field is required, and each kind
175
+ * What you send to create a Payment. Every field is required except `test`, `expiresAt` and `receiptTiming`, and each kind
114
176
  * carries what its receipt prints: a sale its 1 to 12 lines (which must add up to
115
177
  * `amountSatang` exactly), a fundraising its event, a membership its term. A
116
178
  * field of another kind is refused (`invalid_payment` naming it).
@@ -142,6 +204,7 @@ export type PaymentReason =
142
204
  | "invalid_payment"
143
205
  | "not_found"
144
206
  | "not_paid"
207
+ | "not_late"
145
208
  | "has_receipt"
146
209
  | "mismatch"
147
210
  | "user_token_invalid"
@@ -172,15 +235,20 @@ export interface PaymentRecord extends PaymentKindDetails {
172
235
  amountSatang: number;
173
236
  description: string;
174
237
  reference: string;
175
- state: "created" | "pending" | "paid" | "refused" | "rejected" | "refunding" | "refunded";
238
+ state: "created" | "pending" | "paid" | "refused" | "rejected" | "refunding" | "refunded" | "expired" | "late";
176
239
  mode: "live" | "test";
177
240
  payer: { name: string; maskedCitizenId: string } | null;
178
241
  voucher: { number: string; nameTh: string; isReceipt: false } | null;
179
242
  receipt: PaymentReceipt | null;
243
+ /** ISO 8601 (UTC): when the window you gave it closes; null when you gave none. */
244
+ expiresAt: string | null;
245
+ /** ISO 8601. When the Gateway says the Payer paid (the platform's own record time when it does not say). */
180
246
  paidAt: string | null;
181
247
  refusal: { code: string; reasonTh: string } | null;
182
248
  /** True for a paid Payment neither issued nor rejected within the party's deadline. You can still do either. */
183
249
  undecided: boolean;
250
+ /** As created: `later` unless you asked for `on_payment`. */
251
+ receiptTiming: ReceiptTiming;
184
252
  refund: { status: "refunded" | "owed" | "pending" } | null;
185
253
  }
186
254
 
@@ -198,10 +266,17 @@ export async function createPayment(
198
266
  input: CreatePaymentInput,
199
267
  fetchImpl?: typeof fetch,
200
268
  ): Promise<PaymentResult<{ id: string; checkoutUrl: string; state: "created" }>> {
269
+ const { expiresAt, ...rest } = input;
270
+ let sent: CreatePaymentInput = input;
271
+ if (expiresAt !== undefined) {
272
+ // A Date is sent as the instant it is; one that is not a time never leaves the app.
273
+ if (expiresAt instanceof Date && Number.isNaN(expiresAt.getTime())) return refused("invalid_payment", "expiresAt");
274
+ sent = { ...rest, expiresAt: expiresAt instanceof Date ? expiresAt.toISOString() : expiresAt } as CreatePaymentInput;
275
+ }
201
276
  const answer = await callPayments(env, "", fetchImpl, {
202
277
  method: "POST",
203
278
  headers: { "content-type": "application/json" },
204
- body: JSON.stringify(input),
279
+ body: JSON.stringify(sent),
205
280
  });
206
281
  if (!answer.ok) return answer;
207
282
  const { id, checkoutUrl } = answer.body;
@@ -209,6 +284,22 @@ export async function createPayment(
209
284
  return { ok: true, id, checkoutUrl, state: "created" };
210
285
  }
211
286
 
287
+ /**
288
+ * Accept a Late Payment (`payment.late`): you can still serve what the Payer paid
289
+ * for, so the Payment is `paid`, its Payment Voucher is issued and you hear
290
+ * `payment.paid` as usual. Safe to repeat: it answers the same Payment again. Anything
291
+ * that is not a Late Payment says `not_late` (to refuse it, use `rejectPayment`).
292
+ */
293
+ export async function acceptPayment(
294
+ env: PaymentsEnv,
295
+ id: string,
296
+ fetchImpl?: typeof fetch,
297
+ ): Promise<PaymentResult<{ payment: PaymentRecord }>> {
298
+ const answer = await callPayments(env, `/${encodeURIComponent(id)}/accept`, fetchImpl, { method: "POST" });
299
+ if (!answer.ok) return answer;
300
+ return { ok: true, payment: answer.body as unknown as PaymentRecord };
301
+ }
302
+
212
303
  /** Read a Payment back. The platform's answer, not an event, is the truth about its state. */
213
304
  export async function getPayment(
214
305
  env: PaymentsEnv,
@@ -270,8 +361,9 @@ export async function rejectPayment(
270
361
  * `createPayment`'s `checkoutUrl`: the Payer signs in on the Checkout Page.
271
362
  * - `not_your_payment` (`409`): the Payment already belongs to another Payer.
272
363
  * Do not retry: create a new Payment for this Payer, or tell them it is not theirs.
273
- * - `not_payable`: the Payment is already paid or cancelled. Read it with
274
- * `getPayment` and show its state.
364
+ * - `not_payable`: the Payment can no longer be paid: it is paid, late, refused,
365
+ * rejected, refunding, refunded or expired, or its `expiresAt` has passed.
366
+ * Read it with `getPayment` and show its state.
275
367
  * - `not_found`: no such Payment of yours.
276
368
  */
277
369
  export async function createCheckoutPass(
@@ -299,6 +391,9 @@ export async function createCheckoutPass(
299
391
  /** The states a Payment can be in once the platform has sent an event of that type, and any time after. */
300
392
  const STATES_AFTER: Record<string, readonly PaymentRecord["state"][]> = {
301
393
  "payment.paid": ["paid", "rejected", "refunding", "refunded"],
394
+ "payment.expired": ["expired"],
395
+ // A Late Payment waits for you to accept or reject it, then moves on.
396
+ "payment.late": ["late", "paid", "rejected", "refunding", "refunded"],
302
397
  // A Finance Officer can refund a Payment after its Receipt (`refunding`, then `refunded`).
303
398
  "payment.receipt_issued": ["paid", "refunding", "refunded"],
304
399
  "payment.receipt_voided": ["refunding", "refunded", "paid"],
@@ -384,7 +479,7 @@ function platformReason(code: PlatformErrorCode | null): PaymentReason {
384
479
  }
385
480
 
386
481
  /** The Service's own answers, by `error` in the body. */
387
- const SERVICE_REASONS = ["invalid_payment", "not_found", "not_paid", "has_receipt", "checkout_unavailable"] as const;
482
+ const SERVICE_REASONS = ["invalid_payment", "not_found", "not_paid", "not_late", "has_receipt", "checkout_unavailable"] as const;
388
483
 
389
484
  async function callPayments(
390
485
  env: PaymentsEnv,
@@ -430,24 +525,60 @@ async function callPayments(
430
525
  return { ok: true, status: res.status, body };
431
526
  }
432
527
 
528
+ /** The Payment as an event carries it. */
529
+ export type PaymentEventPayment = PaymentKindDetails & {
530
+ id: string;
531
+ kind: PaymentKind;
532
+ /** 100 satang is 1 baht. */
533
+ amountSatang: number;
534
+ description: string;
535
+ /** Your own id, as you sent it. */
536
+ reference: string;
537
+ mode: "live" | "test";
538
+ };
539
+
433
540
  export interface PaymentPaidEvent {
434
541
  type: "payment.paid";
435
542
  /** The same on every delivery of this outcome. */
436
543
  id: string;
437
- payment: PaymentKindDetails & {
438
- id: string;
439
- kind: PaymentKind;
440
- /** 100 satang is 1 baht. */
441
- amountSatang: number;
442
- description: string;
443
- /** Your own id, as you sent it. */
444
- reference: string;
445
- mode: "live" | "test";
446
- };
544
+ /** With the `expiresAt` you gave it (null when none). */
545
+ payment: PaymentEventPayment & { expiresAt: string | null };
447
546
  payer: { name: string; maskedCitizenId: string } | null;
448
547
  /** The platform's acknowledgement that the money arrived. Not a receipt. */
449
548
  voucher: { number: string; nameTh: string; isReceipt: false } | null;
549
+ /** ISO 8601. When the Gateway says the Payer paid; the time the platform recorded it when the Gateway does not say. */
550
+ paidAt: string | null;
551
+ }
552
+
553
+ /**
554
+ * The `expiresAt` you gave the Payment passed and nothing was paid, and no Charge opened
555
+ * before it can still be paid. Release what you held. You hear it up to about 60 minutes
556
+ * after `expiresAt` (usually within one sweep, a few minutes), so run your own timer for the
557
+ * hold. `expired` is final.
558
+ */
559
+ export interface PaymentExpiredEvent {
560
+ type: "payment.expired";
561
+ /** The same on every delivery of this outcome. */
562
+ id: string;
563
+ payment: PaymentPaidEvent["payment"];
450
564
  /** ISO 8601. */
565
+ expiredAt: string | null;
566
+ }
567
+
568
+ /**
569
+ * The Gateway confirmed money for the Payment AFTER its `expiresAt`: a Late Payment. It is
570
+ * held, neither paid nor refunded, and has no Payment Voucher yet. Check your hold and answer
571
+ * with `acceptPayment(id)` (you can still serve it) or `rejectPayment(id)` (you cannot). It
572
+ * counts toward the Payer's yearly cap meanwhile. Unanswered, it goes to the Finance Officer
573
+ * as Undecided after the party's deadline.
574
+ */
575
+ export interface PaymentLateEvent {
576
+ type: "payment.late";
577
+ /** The same on every delivery of this outcome. */
578
+ id: string;
579
+ payment: PaymentPaidEvent["payment"];
580
+ payer: { name: string; maskedCitizenId: string } | null;
581
+ /** ISO 8601. When the Gateway says the Payer paid (before or after `expiresAt`; it was confirmed after). */
451
582
  paidAt: string | null;
452
583
  }
453
584
 
@@ -460,7 +591,7 @@ export interface PaymentRefusedEvent {
460
591
  type: "payment.refused";
461
592
  /** The same on every delivery of this outcome. */
462
593
  id: string;
463
- payment: PaymentPaidEvent["payment"];
594
+ payment: PaymentEventPayment;
464
595
  /** `reasonTh` is for the Payer: show it as is. */
465
596
  refusal: { code: "below_minimum" | "above_maximum" | "over_yearly_cap"; reasonTh: string } | null;
466
597
  /** ISO 8601. */
@@ -475,13 +606,13 @@ export interface PaymentReceiptIssuedEvent {
475
606
  type: "payment.receipt_issued";
476
607
  /** The same on every delivery of this Receipt's event. */
477
608
  id: string;
478
- payment: PaymentPaidEvent["payment"];
609
+ payment: PaymentEventPayment;
479
610
  payer: { name: string; maskedCitizenId: string };
480
611
  receipt: {
481
612
  id: string;
482
613
  /** The Issuer's own number, e.g. `2569-000123`. A test Receipt is `TEST-2569-000001`. */
483
614
  number: string;
484
- /** True for a Draft or Beta app's Receipt: watermarked, never a legal number. */
615
+ /** True for a test Payment's Receipt: watermarked, never a legal number. */
485
616
  isTest: boolean;
486
617
  /** ISO 8601. */
487
618
  issuedAt: string;
@@ -495,7 +626,7 @@ export interface PaymentRejectedEvent {
495
626
  type: "payment.rejected";
496
627
  /** The same on every delivery of this outcome. */
497
628
  id: string;
498
- payment: PaymentPaidEvent["payment"];
629
+ payment: PaymentEventPayment;
499
630
  /** ISO 8601. */
500
631
  rejectedAt: string | null;
501
632
  }
@@ -505,7 +636,7 @@ export interface PaymentRefundedEvent {
505
636
  type: "payment.refunded";
506
637
  /** The same on every delivery of this outcome. */
507
638
  id: string;
508
- payment: PaymentPaidEvent["payment"];
639
+ payment: PaymentEventPayment;
509
640
  /** ISO 8601. */
510
641
  refundedAt: string | null;
511
642
  }
@@ -521,7 +652,7 @@ export interface PaymentReceiptVoidedEvent {
521
652
  type: "payment.receipt_voided";
522
653
  /** The same on every delivery of this Receipt's event. */
523
654
  id: string;
524
- payment: PaymentPaidEvent["payment"];
655
+ payment: PaymentEventPayment;
525
656
  receipt: PaymentReceiptIssuedEvent["receipt"] & {
526
657
  /** ISO 8601. */
527
658
  voidedAt: string | null;
@@ -530,6 +661,8 @@ export interface PaymentReceiptVoidedEvent {
530
661
 
531
662
  export type PaymentEvent =
532
663
  | PaymentPaidEvent
664
+ | PaymentExpiredEvent
665
+ | PaymentLateEvent
533
666
  | PaymentRefusedEvent
534
667
  | PaymentReceiptIssuedEvent
535
668
  | PaymentReceiptVoidedEvent
@@ -2,7 +2,7 @@
2
2
  kind: service
3
3
  visibility: private
4
4
  userToken: optional
5
- description: รับเงินบริจาค ค่าสินค้า/บริการ ค่าจัดกิจกรรมระดมทุน และค่าบำรุงพรรคผ่านหน้าชำระเงินของแพลตฟอร์ม
5
+ description: รับเงินบริจาค ค่าสินค้า/บริการ กิจกรรมระดมทุน และค่าบำรุงพรรคผ่านหน้าชำระเงินของแพลตฟอร์ม
6
6
  ---
7
7
 
8
8
  # Payments
@@ -30,9 +30,11 @@
30
30
  "reference": "offline-mock",
31
31
  "state": "paid",
32
32
  "mode": "test",
33
+ "receiptTiming": "later",
33
34
  "payer": { "name": "บุคคลทดสอบ หนึ่ง", "maskedCitizenId": "x-xxxx-xxxxx-xx-0" },
34
35
  "voucher": { "number": "TEST-PV-000001", "nameTh": "หลักฐานการรับชำระเงิน (ไม่ใช่ใบเสร็จรับเงิน)", "isReceipt": false },
35
36
  "receipt": null,
37
+ "expiresAt": null,
36
38
  "paidAt": "2026-01-01T00:00:00.000Z",
37
39
  "refusal": null,
38
40
  "undecided": false,
@@ -59,13 +61,38 @@
59
61
  "reference": "offline-mock",
60
62
  "state": "refunded",
61
63
  "mode": "test",
64
+ "receiptTiming": "later",
62
65
  "payer": { "name": "บุคคลทดสอบ หนึ่ง", "maskedCitizenId": "x-xxxx-xxxxx-xx-0" },
63
66
  "voucher": { "number": "TEST-PV-000001", "nameTh": "หลักฐานการรับชำระเงิน (ไม่ใช่ใบเสร็จรับเงิน)", "isReceipt": false },
64
67
  "receipt": null,
68
+ "expiresAt": null,
65
69
  "paidAt": "2026-01-01T00:00:00.000Z",
66
70
  "refusal": null,
67
71
  "undecided": false,
68
72
  "refund": { "status": "refunded" }
69
73
  }
74
+ },
75
+ {
76
+ "method": "POST",
77
+ "path": "/pay_offline-mock/accept",
78
+ "status": 200,
79
+ "body": {
80
+ "id": "pay_offline-mock",
81
+ "kind": "donation",
82
+ "amountSatang": 50000,
83
+ "description": "รายการทดสอบ",
84
+ "reference": "offline-mock",
85
+ "state": "paid",
86
+ "mode": "test",
87
+ "receiptTiming": "later",
88
+ "payer": { "name": "บุคคลทดสอบ หนึ่ง", "maskedCitizenId": "x-xxxx-xxxxx-xx-0" },
89
+ "voucher": { "number": "TEST-PV-000001", "nameTh": "หลักฐานการรับชำระเงิน (ไม่ใช่ใบเสร็จรับเงิน)", "isReceipt": false },
90
+ "receipt": null,
91
+ "expiresAt": "2025-12-31T23:30:00.000Z",
92
+ "paidAt": "2026-01-01T00:00:00.000Z",
93
+ "refusal": null,
94
+ "undecided": false,
95
+ "refund": null
96
+ }
70
97
  }
71
98
  ]
@@ -31,6 +31,7 @@ const PAID_EVENT: PaymentPaidEvent = {
31
31
  amountSatang: 50_000,
32
32
  description: "รายการทดสอบ",
33
33
  reference: "offline-mock",
34
+ expiresAt: null,
34
35
  mode: "test",
35
36
  },
36
37
  payer: { name: "บุคคลทดสอบ หนึ่ง", maskedCitizenId: "x-xxxx-xxxxx-xx-0" },
@@ -10,6 +10,7 @@ import {
10
10
  createPayment,
11
11
  getPayment,
12
12
  issueReceipt,
13
+ acceptPayment,
13
14
  paymentHandler,
14
15
  rejectPayment,
15
16
  verifyPaymentEvent,
@@ -59,6 +60,86 @@ describe("createPayment", () => {
59
60
  ]);
60
61
  expect(body).toEqual(INPUT);
61
62
  });
63
+
64
+ it("sends the optional `test` flag through, so a Live app can ask for a test Payment", async () => {
65
+ let body: unknown;
66
+ const h = makeHarness(
67
+ {
68
+ services: async (req) => {
69
+ body = await req.json();
70
+ return Response.json({ id: "pay_2", checkoutUrl: "https://pay.example.test/pay_2", state: "created" }, { status: 201 });
71
+ },
72
+ },
73
+ SERVICES,
74
+ );
75
+ const result = await createPayment(h.testEnv, { ...INPUT, test: true }, h.fetchImpl);
76
+ expect(result).toMatchObject({ ok: true, id: "pay_2" });
77
+ expect(body).toEqual({ ...INPUT, test: true });
78
+ });
79
+
80
+ describe("expiresAt (#467)", () => {
81
+ const sent = async (expiresAt: string | Date) => {
82
+ let body: Record<string, unknown> = {};
83
+ const h = makeHarness(
84
+ {
85
+ services: async (req) => {
86
+ body = (await req.json()) as Record<string, unknown>;
87
+ return Response.json({ id: "pay_1", checkoutUrl: "https://pay.example.test/pay_1", state: "created" }, { status: 201 });
88
+ },
89
+ },
90
+ SERVICES,
91
+ );
92
+ const result = await createPayment(h.testEnv, { ...INPUT, expiresAt }, h.fetchImpl);
93
+ return { result, body };
94
+ };
95
+
96
+ it("sends a string with its offset as written", async () => {
97
+ const { result, body } = await sent("2026-12-01T14:30:00+07:00");
98
+ expect(result).toMatchObject({ ok: true });
99
+ expect(body.expiresAt).toBe("2026-12-01T14:30:00+07:00");
100
+ });
101
+
102
+ it("sends a Date as an ISO 8601 instant", async () => {
103
+ const { body } = await sent(new Date("2026-12-01T07:30:00.000Z"));
104
+ expect(body.expiresAt).toBe("2026-12-01T07:30:00.000Z");
105
+ });
106
+
107
+ it("leaves expiresAt out when none is given", async () => {
108
+ let body: Record<string, unknown> = {};
109
+ const h = makeHarness(
110
+ { services: async (req) => ((body = (await req.json()) as Record<string, unknown>), Response.json({ id: "pay_1", checkoutUrl: "https://pay.example.test/pay_1" }, { status: 201 })) },
111
+ SERVICES,
112
+ );
113
+ await createPayment(h.testEnv, INPUT, h.fetchImpl);
114
+ expect("expiresAt" in body).toBe(false);
115
+ });
116
+
117
+ it("refuses an invalid Date without calling the platform, naming the field", async () => {
118
+ const h = makeHarness({ services: () => Response.json({}, { status: 500 }) }, SERVICES);
119
+ const result = await createPayment(h.testEnv, { ...INPUT, expiresAt: new Date("nope") }, h.fetchImpl);
120
+ expect(result).toEqual({ ok: false, reason: "invalid_payment", field: "expiresAt" });
121
+ expect(h.calls.services).toEqual([]);
122
+ });
123
+ });
124
+ });
125
+
126
+ describe("acceptPayment", () => {
127
+ it("asks the platform to accept a Late Payment and answers the Payment, now paid", async () => {
128
+ const h = makeHarness({ services: () => Response.json({ ...LATE, state: "paid" }) }, SERVICES);
129
+
130
+ const result = await acceptPayment(h.testEnv, "pay_1", h.fetchImpl);
131
+
132
+ expect(result).toMatchObject({ ok: true, payment: { state: "paid" } });
133
+ expect(h.calls.services).toEqual([expect.objectContaining({ path: "/platform/payments/pay_1/accept", method: "POST" })]);
134
+ });
135
+
136
+ it("says not_late for a Payment that is not a Late Payment, and not_found for another app's", async () => {
137
+ const notLate = makeHarness({ services: () => Response.json({ error: "not_late" }, { status: 409 }) }, SERVICES);
138
+ const missing = makeHarness({ services: () => Response.json({ error: "not_found" }, { status: 404 }) }, SERVICES);
139
+
140
+ expect(await acceptPayment(notLate.testEnv, "pay_1", notLate.fetchImpl)).toEqual({ ok: false, reason: "not_late" });
141
+ expect(await acceptPayment(missing.testEnv, "pay_1", missing.fetchImpl)).toEqual({ ok: false, reason: "not_found" });
142
+ });
62
143
  });
63
144
 
64
145
  const PAID: PaymentRecord = {
@@ -69,9 +150,11 @@ const PAID: PaymentRecord = {
69
150
  reference: "order-1",
70
151
  state: "paid",
71
152
  mode: "test",
153
+ receiptTiming: "later",
72
154
  payer: { name: "นางสาวสมหญิง ใจดี", maskedCitizenId: "1-1037-xxxxx-56-1" },
73
155
  voucher: { number: "TEST-PV-000001", nameTh: "หลักฐานการรับชำระเงิน", isReceipt: false },
74
156
  receipt: null,
157
+ expiresAt: null,
75
158
  paidAt: "2026-11-15T09:00:00.000Z",
76
159
  refusal: null,
77
160
  undecided: false,
@@ -278,12 +361,16 @@ const PAID_EVENT: PaymentPaidEvent = {
278
361
  description: "บริจาคสนับสนุนพรรค",
279
362
  reference: "order-1",
280
363
  mode: "test",
364
+ expiresAt: null,
281
365
  },
282
366
  payer: PAID.payer,
283
367
  voucher: PAID.voucher,
284
368
  paidAt: PAID.paidAt,
285
369
  };
286
370
 
371
+ /** A Payment whose money was confirmed after its expiresAt, held for the app. */
372
+ const LATE: PaymentRecord = { ...PAID, state: "late", voucher: null, expiresAt: "2026-11-15T08:55:00.000Z" };
373
+
287
374
  describe("verifyPaymentEvent", () => {
288
375
  // The platform authenticates the delivery itself (the wrapper's own secret
289
376
  // never reaches your code), and your handler is handed the parsed event only.
@@ -324,6 +411,8 @@ describe("verifyPaymentEvent", () => {
324
411
 
325
412
  it.each([
326
413
  ["payment.refused", ["refused"], ["paid", "created"]],
414
+ ["payment.expired", ["expired"], ["created", "pending", "refused", "paid", "late"]],
415
+ ["payment.late", ["late", "paid", "rejected", "refunding", "refunded"], ["created", "pending", "refused", "expired"]],
327
416
  ["payment.rejected", ["rejected", "refunded"], ["paid"]],
328
417
  ["payment.refunded", ["refunded"], ["rejected", "paid"]],
329
418
  ["payment.receipt_issued", ["paid", "refunding", "refunded"], ["created", "refused"]],
@@ -365,6 +454,24 @@ describe("paymentHandler", () => {
365
454
  expect(seen).toEqual(["payment.paid:TEST-PV-000001"]);
366
455
  });
367
456
 
457
+ it("hands over a payment.expired event and a payment.late event, each typed for it", async () => {
458
+ const seen: string[] = [];
459
+ const handler = paymentHandler({
460
+ "payment.expired": (event) => {
461
+ seen.push(`expired ${event.payment.id} ${event.expiredAt}`);
462
+ },
463
+ "payment.late": (event) => {
464
+ seen.push(`late ${event.payment.id} ${event.payer?.name} ${event.paidAt}`);
465
+ },
466
+ });
467
+ const expired = { type: "payment.expired", id: "evt_expired_pay_1", payment: PAID_EVENT.payment, expiredAt: "2026-11-15T10:00:00.000Z" } satisfies PaymentEvent;
468
+ const late = { type: "payment.late", id: "evt_late_pay_1", payment: PAID_EVENT.payment, payer: PAID.payer, paidAt: "2026-11-15T09:00:00.000Z" } satisfies PaymentEvent;
469
+
470
+ expect(await handler(expired, env, ctx)).toBeUndefined();
471
+ expect(await handler(late, env, ctx)).toBeUndefined();
472
+ expect(seen).toEqual(["expired pay_1 2026-11-15T10:00:00.000Z", "late pay_1 นางสาวสมหญิง ใจดี 2026-11-15T09:00:00.000Z"]);
473
+ });
474
+
368
475
  it("hands over a Replacement Receipt's event with the Receipt it replaces", async () => {
369
476
  const seen: string[] = [];
370
477
  const handler = paymentHandler({
@@ -0,0 +1,21 @@
1
+ # CI for a Payment Bridge. Runs on every push and pull request: type-checks the
2
+ # Worker, runs its tests in the Workers runtime, and builds the deployable bundle.
3
+ name: CI
4
+
5
+ on:
6
+ push:
7
+ pull_request:
8
+
9
+ jobs:
10
+ check:
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - uses: actions/setup-node@v4
15
+ with:
16
+ node-version: 22
17
+ cache: npm
18
+ - run: npm ci
19
+ - run: npm run typecheck
20
+ - run: npm test
21
+ - run: npm run build
@@ -0,0 +1,9 @@
1
+ # Payment Bridge
2
+
3
+ Made and kept by the platform (docs/adr/0045). Deploy it unchanged; do not add
4
+ routes, pages, storage, logging or retries. A Bridge whose code drifts from the
5
+ template is flagged in its Code Review. Read README.md first.
6
+
7
+ Two things must stay true of any change: the Bridge never sends its App Key
8
+ anywhere but `platform/payments`, and it never logs a request body, an event or
9
+ a key.
@@ -0,0 +1,57 @@
1
+ # Payment Bridge
2
+
3
+ A Builder App that lets one system outside the platform (an **External System**)
4
+ take Payments exactly as a Builder App does (docs/adr/0045). **Deploy it
5
+ unchanged.** It has no pages, no database, no files and no queue. A Bridge whose
6
+ code drifts from this template is flagged in its Code Review.
7
+
8
+ ```
9
+ External System ──/api/* + Bridge Key──▶ Bridge ──+ App Key──▶ platform/payments
10
+ External System ◀── signed webhook ─────── Bridge ◀── payment(event) ── platform
11
+ ```
12
+
13
+ ## Inbound: `/api/*`
14
+
15
+ Call the Bridge with `Authorization: Bearer <Bridge Key>`. The Bridge makes the
16
+ same call on `platform/payments` with its App Key, and hands the platform's answer
17
+ back as it came (status, body and `x-pple-error` included). What it carries on:
18
+ the method, everything after `/api` and the query, the body, `content-type`,
19
+ `accept`, and the Payer's PPLE ID token. So the platform's payments docs apply
20
+ to you word for word, with one difference: send the token as `pple-user-token`,
21
+ not `x-pple-user-token` (the platform strips every `x-pple-*` header before it
22
+ reaches the Bridge, and the Bridge renames it on the way out).
23
+ `POST /api` is `POST platform/payments`, and `POST /api/<id>/checkout-pass` with
24
+ the Payer's PPLE ID token in `pple-user-token` is a Checkout Pass.
25
+
26
+ A missing or wrong Bridge Key is a `401`. A platform that cannot be reached is a
27
+ `502`. Every other path is a `404`.
28
+
29
+ ## Outbound: the webhook
30
+
31
+ When the platform has an outcome for one of your Payments, it calls the Bridge's
32
+ `payment(event)`. The Bridge `POST`s that event, unchanged, to `WEBHOOK_URL` at
33
+ once, and answers the platform with your status: any `2xx` is delivered; anything
34
+ else, an error or no answer within seven seconds is not, and the platform sends
35
+ the event again with the same id. The Bridge keeps nothing between attempts.
36
+
37
+ Each webhook is signed. See [docs/verify-webhook.md](docs/verify-webhook.md) for
38
+ what to check on your side.
39
+
40
+ ## Config
41
+
42
+ Set in the platform (App Environment), never in this repo:
43
+
44
+ | Key | Kind | |
45
+ | --- | --- | --- |
46
+ | `BRIDGE_KEY` | secret | What your External System calls `/api/*` with. |
47
+ | `WEBHOOK_SECRET` | secret | Signs every webhook. Not the Bridge Key. |
48
+ | `WEBHOOK_URL` | variable | Where events are `POST`ed. An `https` address. With none, every event is answered `503` and the platform sends it again later. |
49
+
50
+ The App Key and the services address are bound by the platform; the Bridge never
51
+ puts the App Key on anything it sends out and never logs a body.
52
+
53
+ ## Develop
54
+
55
+ `npm run typecheck`, `npm test`, `npm run build`. There is no offline mode:
56
+ test against your deployed Bridge at Beta, on the Gateway's sandbox (a Draft Bridge's calls are refused
57
+ with `needs_beta`).