@tofound/billing 1.2.0 → 1.4.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.
- package/CHANGELOG.md +44 -0
- package/README.md +28 -2
- package/dist/hostkit/index.d.ts +1 -1
- package/dist/hostkit/index.js +1 -1
- package/dist/hostkit/quote-wire.d.ts +42 -1
- package/dist/hostkit/quote-wire.js +52 -1
- package/dist/providers/port.d.ts +22 -0
- package/dist/providers/port.js +3 -0
- package/dist/providers/sepay/index.d.ts +4 -2
- package/dist/providers/sepay/index.js +9 -0
- package/dist/providers/sepay/order.d.ts +7 -0
- package/dist/providers/sepay/order.js +62 -13
- package/docs/API.md +18 -3
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,50 @@ All notable changes to `@tofound/billing`. Versions follow semver; 0.x minors
|
|
|
4
4
|
were additive. From 1.0.0 the public API is frozen: removing or narrowing
|
|
5
5
|
anything in the declaration snapshot is a major version.
|
|
6
6
|
|
|
7
|
+
## 1.4.0 — 2026-10-29
|
|
8
|
+
|
|
9
|
+
Additive to 1.3: every 1.3 export is unchanged (the public-api declaration
|
|
10
|
+
snapshot only grows). No schema change. `readOrder`, `verifyPurchase`,
|
|
11
|
+
`cancelOrder` and `confirm` behave exactly as in 1.3.0.
|
|
12
|
+
|
|
13
|
+
To adopt: pin `@tofound/billing@1.4.0`.
|
|
14
|
+
|
|
15
|
+
- **Read-only purchase lookup.** A new provider port, `PurchaseLookup<TProof>`
|
|
16
|
+
(`lookupPurchase(proof): Promise<PurchaseLookupResult>`). It reports what the
|
|
17
|
+
provider says about one purchase: `paid` (with `externalId`, `amount` and
|
|
18
|
+
`occurredAt`), `pending`, `cancelled`, `not_found`, or `unavailable` with a
|
|
19
|
+
short reason. It never applies anything and never throws. The guard
|
|
20
|
+
`isPurchaseLookup` is exported from the root entry.
|
|
21
|
+
- **SePay `lookupPurchase({ invoice })`.** One order-detail GET. `CAPTURED`
|
|
22
|
+
maps to `paid` (`externalId` = order id, else the invoice; `occurredAt` = the
|
|
23
|
+
lookup time), `AUTHENTICATION_NOT_NEEDED` to `pending` and `CANCELLED` to
|
|
24
|
+
`cancelled`. HTTP 404 or no data for the invoice is `not_found`. A timeout,
|
|
25
|
+
network error, other non-2xx or unparseable order is `unavailable` with the
|
|
26
|
+
reason `timeout`, `network`, `http_<n>` or `malformed`; missing merchant
|
|
27
|
+
credentials give `not_configured`. The new option
|
|
28
|
+
`SepayAdapterOptions.lookupTimeoutMs` sets the timeout (default 8 s);
|
|
29
|
+
`timeoutMs` still governs `readOrder`.
|
|
30
|
+
- **Docs:** README (SePay section).
|
|
31
|
+
|
|
32
|
+
## 1.3.0 — 2026-10-28
|
|
33
|
+
|
|
34
|
+
Additive to 1.2: every 1.2 export is unchanged (the public-api declaration
|
|
35
|
+
snapshot only grows). No schema change. Without `display`, the served quote is
|
|
36
|
+
byte-identical to 1.2.0's.
|
|
37
|
+
|
|
38
|
+
To adopt: pin `@tofound/billing@1.3.0`.
|
|
39
|
+
|
|
40
|
+
- **Tax and renewal facts on the wire.** `QuoteWireOptions.display`
|
|
41
|
+
(`DisplayTerms`) adds `taxBehavior` (`inclusive` | `exclusive`),
|
|
42
|
+
`displayAmountMinor`, `displayCurrency` (ISO 4217) and renewal `interval`
|
|
43
|
+
(`month` | `year`) to `serializeQuote` and `serializePlanQuote`, after the
|
|
44
|
+
1.2.0 keys. The host states them; the library computes no tax and changes no
|
|
45
|
+
price.
|
|
46
|
+
- **Offer wire.** New `serializeOffer(offer, { display? })` with types
|
|
47
|
+
`OfferWire`, `OfferWireOptions`, `DisplayTerms`, `TaxBehavior`,
|
|
48
|
+
`RenewalInterval`. A provider offer serves its own `interval`.
|
|
49
|
+
- **Docs:** API.md (display terms).
|
|
50
|
+
|
|
7
51
|
## 1.2.0 — 2026-10-25
|
|
8
52
|
|
|
9
53
|
Additive to 1.1: every 1.1 export is unchanged (the public-api declaration
|
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
products (2Novel first, the Lohi reader api last). Each host API embeds it on
|
|
5
5
|
its own database; there is no billing service.
|
|
6
6
|
|
|
7
|
-
1.
|
|
7
|
+
1.4 ships (the public API is frozen from 1.0.0 on; 1.1 to 1.4 only add):
|
|
8
8
|
|
|
9
9
|
- **The money core** (since 0.1): an idempotent, no-overdraft credit ledger
|
|
10
10
|
behind store ports, memory and Drizzle/Postgres stores, a Drizzle schema
|
|
@@ -23,7 +23,7 @@ its own database; there is no billing service.
|
|
|
23
23
|
(`@tofound/billing/providers/google`) adapters.
|
|
24
24
|
|
|
25
25
|
```sh
|
|
26
|
-
bun add @tofound/billing@1.
|
|
26
|
+
bun add @tofound/billing@1.4.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
```ts
|
|
@@ -64,6 +64,32 @@ It also opens checkouts (`createCheckout`) and customer portal sessions.
|
|
|
64
64
|
switches into one required value. `signPolarWebhook` signs test deliveries.
|
|
65
65
|
The full entry is in `docs/API.md`.
|
|
66
66
|
|
|
67
|
+
## SePay
|
|
68
|
+
|
|
69
|
+
`@tofound/billing/providers/sepay` verifies and normalizes SePay IPNs, signs
|
|
70
|
+
checkout forms and reads orders. `createSepayAdapter({ environment,
|
|
71
|
+
webhookKeys, merchantId, secretKey })` needs the environment passed explicitly
|
|
72
|
+
and refuses credentials of the other rail.
|
|
73
|
+
|
|
74
|
+
`lookupPurchase({ invoice })` (new in 1.4, the `PurchaseLookup` port) is a
|
|
75
|
+
read-only answer about one invoice. It makes one order-detail request, applies
|
|
76
|
+
nothing and never throws; `isPurchaseLookup(adapter)` tells whether an adapter
|
|
77
|
+
has it. It maps the order like this:
|
|
78
|
+
|
|
79
|
+
| SePay answers | Result |
|
|
80
|
+
|---|---|
|
|
81
|
+
| `CAPTURED` | `paid`: `externalId` = order id (else the invoice), `amount` in VND, `occurredAt` = the lookup time (the order body carries no paid time) |
|
|
82
|
+
| `AUTHENTICATION_NOT_NEEDED` | `pending` |
|
|
83
|
+
| `CANCELLED` | `cancelled` |
|
|
84
|
+
| HTTP 404, or no `data` for this invoice | `not_found` |
|
|
85
|
+
| timeout (`lookupTimeoutMs`, default 8 s), network error | `unavailable`, reason `timeout` / `network` |
|
|
86
|
+
| any other non-2xx (5xx, 401, 403 …) | `unavailable`, reason `http_<status>` |
|
|
87
|
+
| an unparseable body, or this invoice in another currency, amount or status | `unavailable`, reason `malformed` |
|
|
88
|
+
| no merchant credentials configured | `unavailable`, reason `not_configured` |
|
|
89
|
+
|
|
90
|
+
To credit a paid invoice, the host still goes through `verifyPurchase` or its
|
|
91
|
+
own apply path. `readOrder` and `verifyPurchase` are unchanged.
|
|
92
|
+
|
|
67
93
|
## Host kit
|
|
68
94
|
|
|
69
95
|
`@tofound/billing/hostkit` (new in 1.0) is for hosts that keep their own
|
package/dist/hostkit/index.d.ts
CHANGED
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
*/
|
|
7
7
|
export { createLegacyLedgerStore, LEGACY_KEY_PREFIX, type LegacyEntryRow, type LegacyLedgerCodec, type LegacyLedgerFields, type LegacyWalletDriver, } from './legacy-ledger.js';
|
|
8
8
|
export { createAdminAdjustments, type AdjustmentInput, type AdjustmentOverdraft, type AdjustmentResult, type AdminAdjustments, type AdminAdjustmentsOptions, } from './adjustments.js';
|
|
9
|
-
export { serializePlanQuote, serializeQuote, type FundingLineWire, type PlanQuoteWire, type QuoteLabeler, type QuoteWire, type QuoteWireOptions, } from './quote-wire.js';
|
|
9
|
+
export { serializeOffer, serializePlanQuote, serializeQuote, type DisplayTerms, type FundingLineWire, type OfferWire, type OfferWireOptions, type PlanQuoteWire, type QuoteLabeler, type QuoteWire, type QuoteWireOptions, type RenewalInterval, type TaxBehavior, } from './quote-wire.js';
|
package/dist/hostkit/index.js
CHANGED
|
@@ -6,4 +6,4 @@
|
|
|
6
6
|
*/
|
|
7
7
|
export { createLegacyLedgerStore, LEGACY_KEY_PREFIX, } from './legacy-ledger.js';
|
|
8
8
|
export { createAdminAdjustments, } from './adjustments.js';
|
|
9
|
-
export { serializePlanQuote, serializeQuote, } from './quote-wire.js';
|
|
9
|
+
export { serializeOffer, serializePlanQuote, serializeQuote, } from './quote-wire.js';
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PlanOffer } from '../catalog/catalog.js';
|
|
1
2
|
import type { FundingLine, Quote, QuoteReason, Settlement } from '../domain/types.js';
|
|
2
3
|
import type { PlanQuoteKind } from '../terms/decide.js';
|
|
3
4
|
import type { PlanQuote } from '../terms/plans.js';
|
|
@@ -16,7 +17,26 @@ export interface FundingLineWire {
|
|
|
16
17
|
remainingAfter: number | null;
|
|
17
18
|
label?: string;
|
|
18
19
|
}
|
|
19
|
-
|
|
20
|
+
/** Whether the displayed price already contains tax (JP 総額表示, EU price indication) or tax is added at checkout. */
|
|
21
|
+
export type TaxBehavior = 'inclusive' | 'exclusive';
|
|
22
|
+
/** How often a subscription renews. */
|
|
23
|
+
export type RenewalInterval = 'month' | 'year';
|
|
24
|
+
/**
|
|
25
|
+
* Facts a host serves next to a price so a client can print the tax label, the
|
|
26
|
+
* amount the customer sees and the renewal cadence. The library computes none
|
|
27
|
+
* of them (no tax, no currency conversion); the host states what its provider
|
|
28
|
+
* charges. Every field is optional and left out of the wire when unset, so a
|
|
29
|
+
* 1.2.0 consumer decodes the wire unchanged.
|
|
30
|
+
*/
|
|
31
|
+
export interface DisplayTerms {
|
|
32
|
+
taxBehavior?: TaxBehavior;
|
|
33
|
+
/** What the customer sees, in minor units of `displayCurrency`. Needs `displayCurrency`. */
|
|
34
|
+
displayAmountMinor?: number;
|
|
35
|
+
/** ISO 4217, three upper-case letters; wider than the ledger's `Currency`. Needs `displayAmountMinor`. */
|
|
36
|
+
displayCurrency?: string;
|
|
37
|
+
interval?: RenewalInterval;
|
|
38
|
+
}
|
|
39
|
+
export interface QuoteWire extends DisplayTerms {
|
|
20
40
|
originalPrice: number;
|
|
21
41
|
price: number;
|
|
22
42
|
currency: string;
|
|
@@ -67,7 +87,28 @@ export interface QuoteWireOptions {
|
|
|
67
87
|
* covered.
|
|
68
88
|
*/
|
|
69
89
|
coveredSources?: readonly string[];
|
|
90
|
+
/** Tax, display amount and renewal facts to serve with the quote; see `DisplayTerms`. */
|
|
91
|
+
display?: DisplayTerms;
|
|
92
|
+
}
|
|
93
|
+
/** A plan offer a host lists: what it is, and the same display facts a quote carries. */
|
|
94
|
+
export interface OfferWire extends DisplayTerms {
|
|
95
|
+
source: PlanOffer['source'];
|
|
96
|
+
market?: string;
|
|
97
|
+
/** The provider's product ref; absent for a credit offer. */
|
|
98
|
+
productRef?: string;
|
|
99
|
+
/** Credit offers only: the length bought. */
|
|
100
|
+
months?: number;
|
|
101
|
+
}
|
|
102
|
+
/** `serializeOffer` options. Unlike a quote, an offer's interval defaults to the provider offer's own. */
|
|
103
|
+
export interface OfferWireOptions {
|
|
104
|
+
display?: DisplayTerms;
|
|
70
105
|
}
|
|
71
106
|
export declare function serializeQuote(quote: Quote, options?: QuoteWireOptions): QuoteWire;
|
|
72
107
|
/** A plan quote (`createPlans().quote`): the purchase fields first, then the quote, then the period as ISO strings. */
|
|
73
108
|
export declare function serializePlanQuote(quote: PlanQuote, options?: QuoteWireOptions): PlanQuoteWire;
|
|
109
|
+
/**
|
|
110
|
+
* A plan offer as served: identity first, then the display facts. A provider
|
|
111
|
+
* offer's `interval` is served unless the host overrides it; a credit offer has
|
|
112
|
+
* none (its `months` is the length). Nothing here is a price.
|
|
113
|
+
*/
|
|
114
|
+
export declare function serializeOffer(offer: PlanOffer, options?: OfferWireOptions): OfferWire;
|
|
@@ -1,3 +1,33 @@
|
|
|
1
|
+
import { BillingError } from '../domain/errors.js';
|
|
2
|
+
import { assertMinor } from '../domain/money.js';
|
|
3
|
+
const TAX_BEHAVIORS = ['inclusive', 'exclusive'];
|
|
4
|
+
const INTERVALS = ['month', 'year'];
|
|
5
|
+
const ISO_CURRENCY = /^[A-Z]{3}$/;
|
|
6
|
+
/** Validates and orders the display facts; unset keys stay out, never `null`. */
|
|
7
|
+
function displayTerms(display) {
|
|
8
|
+
if (!display)
|
|
9
|
+
return {};
|
|
10
|
+
const { taxBehavior, displayAmountMinor, displayCurrency, interval } = display;
|
|
11
|
+
if (taxBehavior !== undefined && !TAX_BEHAVIORS.includes(taxBehavior)) {
|
|
12
|
+
throw new BillingError('invalid_input', `taxBehavior must be inclusive or exclusive, got ${String(taxBehavior)}`);
|
|
13
|
+
}
|
|
14
|
+
if (interval !== undefined && !INTERVALS.includes(interval)) {
|
|
15
|
+
throw new BillingError('invalid_input', `interval must be month or year, got ${String(interval)}`);
|
|
16
|
+
}
|
|
17
|
+
if ((displayAmountMinor === undefined) !== (displayCurrency === undefined)) {
|
|
18
|
+
throw new BillingError('invalid_input', 'displayAmountMinor and displayCurrency are served together');
|
|
19
|
+
}
|
|
20
|
+
if (displayAmountMinor !== undefined)
|
|
21
|
+
assertMinor(displayAmountMinor, 'displayAmountMinor');
|
|
22
|
+
if (displayCurrency !== undefined && !ISO_CURRENCY.test(displayCurrency)) {
|
|
23
|
+
throw new BillingError('invalid_input', `displayCurrency must be an ISO 4217 code, got ${String(displayCurrency)}`);
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
...(taxBehavior === undefined ? {} : { taxBehavior }),
|
|
27
|
+
...(displayAmountMinor === undefined || displayCurrency === undefined ? {} : { displayAmountMinor, displayCurrency }),
|
|
28
|
+
...(interval === undefined ? {} : { interval }),
|
|
29
|
+
};
|
|
30
|
+
}
|
|
1
31
|
export function serializeQuote(quote, options = {}) {
|
|
2
32
|
const labels = options.labels ?? {};
|
|
3
33
|
const reasonLabel = labels.reason?.(quote.reason, quote) ?? quote.reason.label;
|
|
@@ -33,18 +63,39 @@ export function serializeQuote(quote, options = {}) {
|
|
|
33
63
|
subscriptionCovered: quote.canSettle && quote.funding.length > 0 && quote.funding.every((l) => options.coveredSources.includes(l.source)),
|
|
34
64
|
}
|
|
35
65
|
: {}),
|
|
66
|
+
...displayTerms(options.display),
|
|
36
67
|
};
|
|
37
68
|
}
|
|
38
69
|
/** A plan quote (`createPlans().quote`): the purchase fields first, then the quote, then the period as ISO strings. */
|
|
39
70
|
export function serializePlanQuote(quote, options = {}) {
|
|
71
|
+
const { display, ...quoteOptions } = options;
|
|
40
72
|
return {
|
|
41
73
|
kind: quote.kind,
|
|
42
74
|
plan: quote.plan,
|
|
43
75
|
months: quote.months,
|
|
44
76
|
market: quote.market,
|
|
45
|
-
...serializeQuote(quote,
|
|
77
|
+
...serializeQuote(quote, quoteOptions),
|
|
46
78
|
periodStart: quote.periodStart?.toISOString() ?? null,
|
|
47
79
|
periodEnd: quote.periodEnd?.toISOString() ?? null,
|
|
48
80
|
scheduled: quote.scheduled,
|
|
81
|
+
// The display facts close the wire, after the period fields a 1.2.0 consumer reads.
|
|
82
|
+
...displayTerms(display),
|
|
49
83
|
};
|
|
50
84
|
}
|
|
85
|
+
/**
|
|
86
|
+
* A plan offer as served: identity first, then the display facts. A provider
|
|
87
|
+
* offer's `interval` is served unless the host overrides it; a credit offer has
|
|
88
|
+
* none (its `months` is the length). Nothing here is a price.
|
|
89
|
+
*/
|
|
90
|
+
export function serializeOffer(offer, options = {}) {
|
|
91
|
+
const own = offer.source === 'credit' ? undefined : offer.interval;
|
|
92
|
+
const terms = displayTerms({ ...options.display, interval: options.display?.interval ?? own });
|
|
93
|
+
return offer.source === 'credit'
|
|
94
|
+
? { source: offer.source, ...(offer.market === undefined ? {} : { market: offer.market }), months: offer.months, ...terms }
|
|
95
|
+
: {
|
|
96
|
+
source: offer.source,
|
|
97
|
+
...(offer.market === undefined ? {} : { market: offer.market }),
|
|
98
|
+
productRef: offer.productRef,
|
|
99
|
+
...terms,
|
|
100
|
+
};
|
|
101
|
+
}
|
package/dist/providers/port.d.ts
CHANGED
|
@@ -186,6 +186,27 @@ export interface PortalCapable {
|
|
|
186
186
|
export interface PurchaseVerifier<TProof = unknown> {
|
|
187
187
|
verifyPurchase(proof: TProof): Promise<VerifiedDelivery | null>;
|
|
188
188
|
}
|
|
189
|
+
/**
|
|
190
|
+
* What the provider says about one purchase right now. `paid.occurredAt` is
|
|
191
|
+
* the adapter's best time for the capture (SePay: the lookup time, since its
|
|
192
|
+
* order body carries none); `unavailable` is any answer the adapter could not
|
|
193
|
+
* vouch for, with a short code (`timeout`, `network`, `http_<n>`, `malformed` …).
|
|
194
|
+
*/
|
|
195
|
+
export type PurchaseLookupResult = {
|
|
196
|
+
state: 'paid';
|
|
197
|
+
externalId: string;
|
|
198
|
+
amount: Money;
|
|
199
|
+
occurredAt: Date;
|
|
200
|
+
} | {
|
|
201
|
+
state: 'pending' | 'cancelled' | 'not_found';
|
|
202
|
+
} | {
|
|
203
|
+
state: 'unavailable';
|
|
204
|
+
reason: string;
|
|
205
|
+
};
|
|
206
|
+
/** Read-only: what the provider says about one purchase. Never applies anything and never throws. */
|
|
207
|
+
export interface PurchaseLookup<TProof = unknown> {
|
|
208
|
+
lookupPurchase(proof: TProof): Promise<PurchaseLookupResult>;
|
|
209
|
+
}
|
|
189
210
|
export interface Reconcilable {
|
|
190
211
|
listChangesSince(cursor: string | null, limit: number): Promise<{
|
|
191
212
|
deliveries: VerifiedDelivery[];
|
|
@@ -200,6 +221,7 @@ export interface ConsumptionReporter {
|
|
|
200
221
|
}
|
|
201
222
|
export declare function isCheckoutCapable<T extends object>(adapter: T): adapter is T & CheckoutCapable;
|
|
202
223
|
export declare function isPurchaseVerifier<T extends object>(adapter: T): adapter is T & PurchaseVerifier;
|
|
224
|
+
export declare function isPurchaseLookup(adapter: unknown): adapter is PurchaseLookup;
|
|
203
225
|
/** `verify` refused a delivery: `unauthorized` → 401, `malformed` → 400. Nothing is stored. */
|
|
204
226
|
export declare class VerifyError extends Error {
|
|
205
227
|
readonly name = "VerifyError";
|
package/dist/providers/port.js
CHANGED
|
@@ -4,6 +4,9 @@ export function isCheckoutCapable(adapter) {
|
|
|
4
4
|
export function isPurchaseVerifier(adapter) {
|
|
5
5
|
return typeof adapter.verifyPurchase === 'function';
|
|
6
6
|
}
|
|
7
|
+
export function isPurchaseLookup(adapter) {
|
|
8
|
+
return typeof adapter === 'object' && adapter !== null && typeof adapter.lookupPurchase === 'function';
|
|
9
|
+
}
|
|
7
10
|
// ---------------------------------------------------------------------------
|
|
8
11
|
// Errors
|
|
9
12
|
// ---------------------------------------------------------------------------
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseVerifier } from '../port.js';
|
|
1
|
+
import { type CheckoutCapable, type IngestOutcome, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse, type PurchaseLookup, type PurchaseVerifier } from '../port.js';
|
|
2
2
|
import { type SepayOrderState } from './order.js';
|
|
3
3
|
export { parseSepayOrder, parseVnd, type SepayOrderState } from './order.js';
|
|
4
4
|
export { signCheckoutFields } from './signature.js';
|
|
@@ -17,12 +17,14 @@ export interface SepayAdapterOptions {
|
|
|
17
17
|
fetch?: typeof fetch;
|
|
18
18
|
/** Order API timeout. Default 10 s. */
|
|
19
19
|
timeoutMs?: number;
|
|
20
|
+
/** `lookupPurchase` timeout per call; past it the answer is `unavailable/timeout`. Default 8 s. */
|
|
21
|
+
lookupTimeoutMs?: number;
|
|
20
22
|
}
|
|
21
23
|
/** Poll proof: the checkout session id used as the SePay invoice. */
|
|
22
24
|
export interface SepayPurchaseProof {
|
|
23
25
|
invoice: string;
|
|
24
26
|
}
|
|
25
|
-
export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof> {
|
|
27
|
+
export interface SepayAdapter extends ProviderAdapter, CheckoutCapable, PurchaseVerifier<SepayPurchaseProof>, PurchaseLookup<SepayPurchaseProof> {
|
|
26
28
|
readonly id: 'sepay';
|
|
27
29
|
/** Current order state; `unknown` on any lookup failure. */
|
|
28
30
|
readOrder(invoice: string): Promise<SepayOrderState>;
|
|
@@ -154,6 +154,15 @@ export function createSepayAdapter(options) {
|
|
|
154
154
|
const now = new Date();
|
|
155
155
|
return deliveryOf(body, now, JSON.stringify(body));
|
|
156
156
|
},
|
|
157
|
+
async lookupPurchase(proof) {
|
|
158
|
+
// Read-only and never throws: missing merchant credentials are an answer too.
|
|
159
|
+
if (!merchantId || !secretKey)
|
|
160
|
+
return { state: 'unavailable', reason: 'not_configured' };
|
|
161
|
+
// No invoice names no order; a typed caller cannot pass one, an untyped one gets an answer, not a throw.
|
|
162
|
+
if (typeof proof?.invoice !== 'string' || proof.invoice === '')
|
|
163
|
+
return { state: 'not_found' };
|
|
164
|
+
return orderClient().lookup(proof.invoice, options.lookupTimeoutMs ?? 8_000);
|
|
165
|
+
},
|
|
157
166
|
readOrder: async (invoice) => orderClient().read(invoice),
|
|
158
167
|
cancelOrder: async (invoice) => orderClient().cancel(invoice),
|
|
159
168
|
};
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* cancellation, and another invoice or currency is never accepted as this
|
|
5
5
|
* purchase.
|
|
6
6
|
*/
|
|
7
|
+
import type { PurchaseLookupResult } from '../port.js';
|
|
7
8
|
export type SepayOrderState = {
|
|
8
9
|
state: 'unknown';
|
|
9
10
|
} | {
|
|
@@ -24,6 +25,12 @@ export interface SepayOrderClientOptions {
|
|
|
24
25
|
}
|
|
25
26
|
export declare function createSepayOrderClient(options: SepayOrderClientOptions): {
|
|
26
27
|
read: (invoice: string) => Promise<SepayOrderState>;
|
|
28
|
+
/**
|
|
29
|
+
* The read-only lookup over the same order-detail request: a missing
|
|
30
|
+
* order is `not_found`, anything the client cannot vouch for is
|
|
31
|
+
* `unavailable` with a short code, and it never throws.
|
|
32
|
+
*/
|
|
33
|
+
lookup(invoice: string, timeoutMs: number): Promise<PurchaseLookupResult>;
|
|
27
34
|
/**
|
|
28
35
|
* A 200 cancellation answer is not a state snapshot: re-read the order,
|
|
29
36
|
* so a capture racing the cancellation wins and is still settled.
|
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SePay order API (read, cancel), ported from Lohi `api/src/lib/sepay.ts` —
|
|
3
|
-
* the stricter of the two host copies: a lookup failure is never proof of
|
|
4
|
-
* cancellation, and another invoice or currency is never accepted as this
|
|
5
|
-
* purchase.
|
|
6
|
-
*/
|
|
7
1
|
/** Parse SePay's order body (`{data: {...}}`) for `invoice`. Anything off is `unknown`. */
|
|
8
2
|
export function parseSepayOrder(body, invoice) {
|
|
9
3
|
const data = body?.data;
|
|
@@ -31,20 +25,31 @@ export function parseVnd(raw) {
|
|
|
31
25
|
}
|
|
32
26
|
export function createSepayOrderClient(options) {
|
|
33
27
|
const authorization = `Basic ${Buffer.from(`${options.merchantId}:${options.secretKey}`).toString('base64')}`;
|
|
34
|
-
|
|
35
|
-
|
|
28
|
+
function call(path, signal, body) {
|
|
29
|
+
return options.fetch(`${options.apiBase}/${path}`, {
|
|
36
30
|
method: body ? 'POST' : 'GET',
|
|
37
31
|
headers: { Authorization: authorization, 'Content-Type': 'application/json' },
|
|
38
32
|
...(body ? { body: JSON.stringify(body) } : {}),
|
|
39
|
-
signal
|
|
33
|
+
signal,
|
|
40
34
|
});
|
|
35
|
+
}
|
|
36
|
+
/** Network errors and the timeout throw; everything the server answered is returned. */
|
|
37
|
+
async function detail(invoice, signal) {
|
|
38
|
+
const response = await call(`order/detail/${encodeURIComponent(invoice)}`, signal);
|
|
41
39
|
if (!response.ok)
|
|
42
|
-
return
|
|
43
|
-
|
|
40
|
+
return { status: response.status, json: false };
|
|
41
|
+
const text = await response.text();
|
|
42
|
+
try {
|
|
43
|
+
return { status: response.status, json: true, body: JSON.parse(text) };
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return { status: response.status, json: false };
|
|
47
|
+
}
|
|
44
48
|
}
|
|
45
49
|
async function read(invoice) {
|
|
46
50
|
try {
|
|
47
|
-
|
|
51
|
+
const answer = await detail(invoice, AbortSignal.timeout(options.timeoutMs));
|
|
52
|
+
return answer.json ? parseSepayOrder(answer.body, invoice) : { state: 'unknown' };
|
|
48
53
|
}
|
|
49
54
|
catch {
|
|
50
55
|
return { state: 'unknown' };
|
|
@@ -52,13 +57,35 @@ export function createSepayOrderClient(options) {
|
|
|
52
57
|
}
|
|
53
58
|
return {
|
|
54
59
|
read,
|
|
60
|
+
/**
|
|
61
|
+
* The read-only lookup over the same order-detail request: a missing
|
|
62
|
+
* order is `not_found`, anything the client cannot vouch for is
|
|
63
|
+
* `unavailable` with a short code, and it never throws.
|
|
64
|
+
*/
|
|
65
|
+
async lookup(invoice, timeoutMs) {
|
|
66
|
+
const signal = AbortSignal.timeout(timeoutMs);
|
|
67
|
+
let answer;
|
|
68
|
+
try {
|
|
69
|
+
answer = await detail(invoice, signal);
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return { state: 'unavailable', reason: signal.aborted ? 'timeout' : 'network' };
|
|
73
|
+
}
|
|
74
|
+
if (answer.status === 404)
|
|
75
|
+
return { state: 'not_found' };
|
|
76
|
+
if (answer.status < 200 || answer.status > 299)
|
|
77
|
+
return { state: 'unavailable', reason: `http_${answer.status}` };
|
|
78
|
+
if (!answer.json)
|
|
79
|
+
return { state: 'unavailable', reason: 'malformed' };
|
|
80
|
+
return lookupResultOf(answer.body, invoice, new Date());
|
|
81
|
+
},
|
|
55
82
|
/**
|
|
56
83
|
* A 200 cancellation answer is not a state snapshot: re-read the order,
|
|
57
84
|
* so a capture racing the cancellation wins and is still settled.
|
|
58
85
|
*/
|
|
59
86
|
async cancel(invoice) {
|
|
60
87
|
try {
|
|
61
|
-
await
|
|
88
|
+
await call('order/cancel', AbortSignal.timeout(options.timeoutMs), { order_invoice_number: invoice });
|
|
62
89
|
}
|
|
63
90
|
catch {
|
|
64
91
|
// The re-read below is the answer either way.
|
|
@@ -67,3 +94,25 @@ export function createSepayOrderClient(options) {
|
|
|
67
94
|
},
|
|
68
95
|
};
|
|
69
96
|
}
|
|
97
|
+
/**
|
|
98
|
+
* A 2xx order body as a lookup result. No `data` for this invoice is
|
|
99
|
+
* `not_found`; data for it that `parseSepayOrder` refuses (another currency,
|
|
100
|
+
* an unreadable amount or status) is `malformed`, never a guess. `paid` carries
|
|
101
|
+
* the lookup time: SePay's order body has no capture time.
|
|
102
|
+
*/
|
|
103
|
+
function lookupResultOf(body, invoice, now) {
|
|
104
|
+
const data = body?.data;
|
|
105
|
+
if (!data || typeof data !== 'object' || data['order_invoice_number'] !== invoice) {
|
|
106
|
+
return { state: 'not_found' };
|
|
107
|
+
}
|
|
108
|
+
const order = parseSepayOrder(body, invoice);
|
|
109
|
+
switch (order.state) {
|
|
110
|
+
case 'paid':
|
|
111
|
+
return { state: 'paid', externalId: order.orderId ?? invoice, amount: { currency: 'VND', amountMinor: order.amountVnd }, occurredAt: now };
|
|
112
|
+
case 'pending':
|
|
113
|
+
case 'cancelled':
|
|
114
|
+
return { state: order.state };
|
|
115
|
+
default:
|
|
116
|
+
return { state: 'unavailable', reason: 'malformed' };
|
|
117
|
+
}
|
|
118
|
+
}
|
package/docs/API.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
# @tofound/billing — API (1.
|
|
1
|
+
# @tofound/billing — API (1.3)
|
|
2
2
|
|
|
3
3
|
Part of the `billing.public-api` contract with `src/index.ts` and
|
|
4
|
-
`src/domain/types.ts`. 0.x minors were additive; 1.1.0 and 1.
|
|
4
|
+
`src/domain/types.ts`. 0.x minors were additive; 1.1.0, 1.2.0 and 1.3.0 are additive to 1.0.0. From 1.0.0 the API is
|
|
5
5
|
frozen: the declaration snapshot in `test/contract/public-api.test.ts` fails
|
|
6
6
|
on any change to these exports, and removing or narrowing one is a major
|
|
7
7
|
version. For task-oriented walkthroughs (packs, plans, failed renewals,
|
|
@@ -15,7 +15,7 @@ refunds, arming a provider) see [GUIDE.md](GUIDE.md).
|
|
|
15
15
|
| `@tofound/billing/providers/polar` | `createPolarAdapter`, `resolvePolarEnvironment`, `respondPolar`, `redactPolarPayload`, `signPolarWebhook`, `PolarApiError`, `POLAR_WEBHOOK_*` header names and tolerance; types `PolarAdapter`, `PolarAdapterOptions`, `PolarCheckoutRequest`, `PolarKeyDerivation` |
|
|
16
16
|
| `@tofound/billing/providers/apple` | `createAppleAdapter`, `respondApple`, `AppleApiError`, `APPLE_TRANSACTION_EVENT`, `APPLE_ROOT_CA_G3_PEM` / `_SHA256`, `APPLE_RECEIPT_SIGNING_OID`, `APPLE_WWDR_INTERMEDIATE_OID`; types `AppleAdapter`, `AppleAdapterOptions`, `AppleProduct`, `AppleServerApiCredentials`, `AppleTransactionProof` |
|
|
17
17
|
| `@tofound/billing/providers/google` | `createGoogleAdapter`, `respondGoogle`, `GooglePlayApiError`, `GOOGLE_RTDN_EVENT`, `GOOGLE_PURCHASE_EVENT`, `GOOGLE_VOIDED_EVENT`; types `GoogleAdapter`, `GoogleAdapterOptions`, `GoogleProduct`, `GooglePurchaseProof`, `PubSubAuth`, `ServiceAccount` |
|
|
18
|
-
| `@tofound/billing/hostkit` | `createLegacyLedgerStore`, `LEGACY_KEY_PREFIX`, `createAdminAdjustments`, `serializeQuote`, `serializePlanQuote`; types `LegacyWalletDriver`, `LegacyEntryRow`, `LegacyLedgerFields`, `LegacyLedgerCodec`, `AdjustmentInput`, `AdjustmentResult`, `AdjustmentOverdraft`, `AdminAdjustments`, `AdminAdjustmentsOptions`, `QuoteWire`, `PlanQuoteWire`, `FundingLineWire`, `QuoteLabeler`, `QuoteWireOptions` |
|
|
18
|
+
| `@tofound/billing/hostkit` | `createLegacyLedgerStore`, `LEGACY_KEY_PREFIX`, `createAdminAdjustments`, `serializeQuote`, `serializePlanQuote`, `serializeOffer`; types `LegacyWalletDriver`, `LegacyEntryRow`, `LegacyLedgerFields`, `LegacyLedgerCodec`, `AdjustmentInput`, `AdjustmentResult`, `AdjustmentOverdraft`, `AdminAdjustments`, `AdminAdjustmentsOptions`, `QuoteWire`, `PlanQuoteWire`, `FundingLineWire`, `QuoteLabeler`, `QuoteWireOptions`, `OfferWire`, `OfferWireOptions`, `DisplayTerms`, `TaxBehavior`, `RenewalInterval` |
|
|
19
19
|
| `@tofound/billing/testing` | `ledgerConformanceCases`, `assertLedgerInvariants`, `assertQuoteMatchesSettlement`, `ingestConformanceCases`, `termConformanceCases`, memory stores |
|
|
20
20
|
|
|
21
21
|
The library reads no env, logs nothing and has no runtime dependencies. Every
|
|
@@ -693,3 +693,18 @@ quote:
|
|
|
693
693
|
|
|
694
694
|
**`serializePlanQuote`** puts `kind, plan, months, market` first and
|
|
695
695
|
`periodStart, periodEnd` (ISO strings or `null`) and `scheduled` last.
|
|
696
|
+
|
|
697
|
+
**Display terms (1.3.0).** `serializeQuote`/`serializePlanQuote` take
|
|
698
|
+
`display?: DisplayTerms` and `serializeOffer(offer, { display? })` serves a
|
|
699
|
+
catalog offer (`source, market?, productRef?` or `months`) with the same
|
|
700
|
+
facts:
|
|
701
|
+
- `taxBehavior` (`'inclusive' | 'exclusive'`), `displayAmountMinor` and
|
|
702
|
+
`displayCurrency` (ISO 4217; served together) and `interval`
|
|
703
|
+
(`'month' | 'year'`; a provider offer's own interval by default);
|
|
704
|
+
- the host states them: the library computes no tax and converts nothing, and
|
|
705
|
+
`price` / `originalPrice` are untouched;
|
|
706
|
+
- unset facts are left out, never `null`, and they come last on the wire
|
|
707
|
+
(after `scheduled` on a plan quote), so without `display` the wire is
|
|
708
|
+
exactly 1.2.0's;
|
|
709
|
+
- a bad value throws `invalid_input` (`invalid_amount` for a negative or
|
|
710
|
+
non-integer amount).
|
package/package.json
CHANGED