@tofound/billing 1.1.0 → 1.3.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 +50 -0
- package/README.md +2 -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/inbox/ingest.d.ts +6 -0
- package/dist/inbox/ingest.js +3 -0
- package/dist/providers/polar/events.d.ts +6 -0
- package/dist/providers/polar/events.js +32 -7
- package/dist/providers/polar/index.d.ts +15 -0
- package/dist/providers/polar/index.js +45 -4
- package/dist/providers/port.d.ts +6 -0
- package/docs/API.md +81 -5
- package/docs/GUIDE.md +2 -1
- package/docs/MIGRATION-LOHI.md +55 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,56 @@ 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.3.0 — 2026-10-28
|
|
8
|
+
|
|
9
|
+
Additive to 1.2: every 1.2 export is unchanged (the public-api declaration
|
|
10
|
+
snapshot only grows). No schema change. Without `display`, the served quote is
|
|
11
|
+
byte-identical to 1.2.0's.
|
|
12
|
+
|
|
13
|
+
To adopt: pin `@tofound/billing@1.3.0`.
|
|
14
|
+
|
|
15
|
+
- **Tax and renewal facts on the wire.** `QuoteWireOptions.display`
|
|
16
|
+
(`DisplayTerms`) adds `taxBehavior` (`inclusive` | `exclusive`),
|
|
17
|
+
`displayAmountMinor`, `displayCurrency` (ISO 4217) and renewal `interval`
|
|
18
|
+
(`month` | `year`) to `serializeQuote` and `serializePlanQuote`, after the
|
|
19
|
+
1.2.0 keys. The host states them; the library computes no tax and changes no
|
|
20
|
+
price.
|
|
21
|
+
- **Offer wire.** New `serializeOffer(offer, { display? })` with types
|
|
22
|
+
`OfferWire`, `OfferWireOptions`, `DisplayTerms`, `TaxBehavior`,
|
|
23
|
+
`RenewalInterval`. A provider offer serves its own `interval`.
|
|
24
|
+
- **Docs:** API.md (display terms).
|
|
25
|
+
|
|
26
|
+
## 1.2.0 — 2026-10-25
|
|
27
|
+
|
|
28
|
+
Additive to 1.1: every 1.1 export is unchanged (the public-api declaration
|
|
29
|
+
snapshot only grows). No schema change. Without `app`, the Polar adapter's
|
|
30
|
+
behavior and checkout request bodies are exactly 1.1.0's.
|
|
31
|
+
|
|
32
|
+
To adopt: pin `@tofound/billing@1.2.0`.
|
|
33
|
+
|
|
34
|
+
- **Polar app tag for a shared Polar org.** `PolarAdapterOptions.app` is this
|
|
35
|
+
host's tag, stamped as `metadata.app` next to `metadata.checkout_id` on every
|
|
36
|
+
checkout. With it set, the normalizer classifies every `order.*`,
|
|
37
|
+
`subscription.*` and `checkout.*` event by `data.metadata.app` of the object
|
|
38
|
+
the event is about: equal → processed as before; present and different (or
|
|
39
|
+
unreadable) → `ignored` with reason `foreign_app`; absent → governed by the new
|
|
40
|
+
`unlabeled?: 'accept' | 'ignore'` (default `'accept'`; `'ignore'` →
|
|
41
|
+
`ignored`, reason `unlabeled_app`). Foreign wins over every other rule, so a
|
|
42
|
+
foreign partial refund is `ignored`, not `needs_review`. A foreign or ignored
|
|
43
|
+
unlabeled event leaves one `ignored` inbox row and nothing else: no ledger
|
|
44
|
+
entry, term, snapshot, alert or `onUnmatched` relay, and a redelivery or
|
|
45
|
+
`replay` stays `ignored`. New type `PolarUnlabeledPolicy`; new config errors
|
|
46
|
+
`polar_invalid_app`, `polar_invalid_unlabeled`, `polar_unlabeled_requires_app`.
|
|
47
|
+
- **Checkout metadata and customer seam.** `CheckoutRequest` (and
|
|
48
|
+
`CreateCheckoutInput`, forwarded by `ingest.createCheckout`) gain optional
|
|
49
|
+
`customerEmail`, `externalCustomerId` and `metadata`. Polar sends them as
|
|
50
|
+
`customer_email`, `external_customer_id` (default `accountId`) and extra
|
|
51
|
+
`metadata` keys. `checkout_id` and `app` are reserved and cannot be set by the
|
|
52
|
+
host (`polar_reserved_metadata_key`, before any call); a non-primitive value
|
|
53
|
+
is `polar_invalid_metadata`. Other adapters ignore the three fields.
|
|
54
|
+
- **Docs:** API.md (options, outcomes, seam), a *Shared Polar org* section in
|
|
55
|
+
MIGRATION-LOHI.md.
|
|
56
|
+
|
|
7
57
|
## 1.1.0 — 2026-10-24
|
|
8
58
|
|
|
9
59
|
Additive to 1.0: every 1.0 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.3 ships (the public API is frozen from 1.0.0 on; 1.1, 1.2 and 1.3 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.3.0 --exact # peer: drizzle-orm ^0.45 for /drizzle
|
|
27
27
|
```
|
|
28
28
|
|
|
29
29
|
```ts
|
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/inbox/ingest.d.ts
CHANGED
|
@@ -104,6 +104,12 @@ export interface CreateCheckoutInput {
|
|
|
104
104
|
cancelUrl: string;
|
|
105
105
|
/** The buyer's IP, forwarded to adapters that use it (Polar picks the tax country from it). Empty or blank means unknown. */
|
|
106
106
|
customerIpAddress?: string | null;
|
|
107
|
+
/** The buyer's email, forwarded to adapters that use it (Polar prefills the pay page). Blank means unknown. */
|
|
108
|
+
customerEmail?: string | null;
|
|
109
|
+
/** The provider's customer id when it is not `accountId` (Polar `external_customer_id`). Blank means `accountId`. */
|
|
110
|
+
externalCustomerId?: string | null;
|
|
111
|
+
/** Host metadata forwarded to adapters that carry it (Polar: onto the order and subscription). Empty means none. */
|
|
112
|
+
metadata?: Readonly<Record<string, string | number | boolean>> | null;
|
|
107
113
|
/** Session lifetime. Default 30 min. A payment after it still credits. */
|
|
108
114
|
ttlMs?: number;
|
|
109
115
|
meta?: Record<string, unknown> | null;
|
package/dist/inbox/ingest.js
CHANGED
|
@@ -414,6 +414,9 @@ export function createIngest(options) {
|
|
|
414
414
|
cancelUrl: input.cancelUrl,
|
|
415
415
|
productRef: session.productRef,
|
|
416
416
|
...(input.customerIpAddress?.trim() ? { customerIpAddress: input.customerIpAddress.trim() } : {}),
|
|
417
|
+
...(input.customerEmail?.trim() ? { customerEmail: input.customerEmail.trim() } : {}),
|
|
418
|
+
...(input.externalCustomerId?.trim() ? { externalCustomerId: input.externalCustomerId.trim() } : {}),
|
|
419
|
+
...(input.metadata && Object.keys(input.metadata).length > 0 ? { metadata: input.metadata } : {}),
|
|
417
420
|
});
|
|
418
421
|
await store.transaction((tx) => store.bind(tx).insertSession(session));
|
|
419
422
|
return { session, redirect };
|
|
@@ -9,7 +9,13 @@ export interface NormalizeOptions {
|
|
|
9
9
|
products: Readonly<Record<string, string>>;
|
|
10
10
|
/** Our checkout session ids, as carried in `metadata.checkout_id`. */
|
|
11
11
|
checkoutPattern: RegExp;
|
|
12
|
+
/** The host's app tag; unset = no ownership check (a single-tenant org). */
|
|
13
|
+
app?: string;
|
|
14
|
+
/** What an event without `metadata.app` is. Only read when `app` is set. */
|
|
15
|
+
unlabeled?: PolarUnlabeledPolicy;
|
|
12
16
|
}
|
|
17
|
+
/** Events without `metadata.app` (orders created before the tag existed): process them, or leave them to the other host. */
|
|
18
|
+
export type PolarUnlabeledPolicy = 'accept' | 'ignore';
|
|
13
19
|
/** The provider's watermark: when Polar last changed the object, else when it was created or sent. */
|
|
14
20
|
export declare function occurredAtOf(envelope: PolarEnvelope, fallback: Date): Date;
|
|
15
21
|
/** The server-issued external customer id (design §4.1). */
|
|
@@ -29,6 +29,26 @@ function checkoutRefOf(data, options) {
|
|
|
29
29
|
const ref = str(rec(data['metadata'])?.['checkout_id']);
|
|
30
30
|
return ref && options.checkoutPattern.test(ref) ? ref : null;
|
|
31
31
|
}
|
|
32
|
+
/**
|
|
33
|
+
* The ignore verdict for an event this adapter does not own, or null to process
|
|
34
|
+
* it. Ownership is the `metadata.app` Polar copied from our checkout onto the
|
|
35
|
+
* order / subscription (and left on the checkout itself). Present and not
|
|
36
|
+
* exactly our tag — another host's, empty, not a string, or `metadata` not an
|
|
37
|
+
* object at all — is foreign: a label we cannot read is never credited. Absent
|
|
38
|
+
* is `unlabeled`, governed by the host's policy.
|
|
39
|
+
*/
|
|
40
|
+
function notOurs(data, options) {
|
|
41
|
+
if (options.app === undefined)
|
|
42
|
+
return null;
|
|
43
|
+
const metadata = data['metadata'];
|
|
44
|
+
if (metadata !== undefined && metadata !== null && !rec(metadata))
|
|
45
|
+
return { kind: 'ignored', reason: 'foreign_app' };
|
|
46
|
+
const label = rec(metadata)?.['app'];
|
|
47
|
+
if (label === undefined || label === null) {
|
|
48
|
+
return options.unlabeled === 'ignore' ? { kind: 'ignored', reason: 'unlabeled_app' } : null;
|
|
49
|
+
}
|
|
50
|
+
return label === options.app ? null : { kind: 'ignored', reason: 'foreign_app' };
|
|
51
|
+
}
|
|
32
52
|
function moneyOf(currencyRaw, amountMinor, rawAmount) {
|
|
33
53
|
const currency = own(CURRENCIES, (str(currencyRaw) ?? '').toUpperCase());
|
|
34
54
|
if (!currency)
|
|
@@ -203,11 +223,16 @@ function checkoutEvent(envelope, options) {
|
|
|
203
223
|
}
|
|
204
224
|
export function normalizePolarEvent(envelope, occurredAt, options) {
|
|
205
225
|
const { type } = envelope;
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
226
|
+
const family = type.startsWith('subscription.')
|
|
227
|
+
? subscriptionEvent
|
|
228
|
+
: type.startsWith('order.')
|
|
229
|
+
? orderEvent
|
|
230
|
+
: type.startsWith('checkout.')
|
|
231
|
+
? (e, _at, o) => checkoutEvent(e, o)
|
|
232
|
+
: null;
|
|
233
|
+
if (!family)
|
|
234
|
+
return { kind: 'ignored', reason: `unhandled_type:${type}` };
|
|
235
|
+
// Ownership first: a foreign event must not reach a rule that could park it
|
|
236
|
+
// for review (partial refund, unknown product, unbound order …).
|
|
237
|
+
return notOurs(envelope.data, options) ?? family(envelope, occurredAt, options);
|
|
213
238
|
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type CheckoutCapable, type CheckoutRedirect, type CheckoutRequest, type IngestOutcome, type PortalCapable, type ProviderAdapter, type ProviderEnvironment, type ProviderResponse } from '../port.js';
|
|
2
|
+
import { type PolarUnlabeledPolicy } from './events.js';
|
|
3
|
+
export type { PolarUnlabeledPolicy } from './events.js';
|
|
2
4
|
export { POLAR_WEBHOOK_ID_HEADER, POLAR_WEBHOOK_SIGNATURE_HEADER, POLAR_WEBHOOK_TIMESTAMP_HEADER, POLAR_WEBHOOK_TOLERANCE_SECONDS, signPolarWebhook, type PolarKeyDerivation, } from './signature.js';
|
|
3
5
|
/**
|
|
4
6
|
* 2Novel's two-switch arming, made explicit: production needs both the
|
|
@@ -21,6 +23,19 @@ export interface PolarAdapterOptions {
|
|
|
21
23
|
accessToken?: string;
|
|
22
24
|
/** Our checkout session ids as carried in `metadata.checkout_id`. Default: UUID. */
|
|
23
25
|
checkoutPattern?: RegExp;
|
|
26
|
+
/**
|
|
27
|
+
* This host's tag in a Polar org shared with other hosts. Stamped on every
|
|
28
|
+
* checkout as `metadata.app`; an event whose object carries a different
|
|
29
|
+
* `metadata.app` is ignored (`foreign_app`) — never credited, reversed,
|
|
30
|
+
* snapshotted or parked for review. Unset: no tagging, no ownership check.
|
|
31
|
+
*/
|
|
32
|
+
app?: string;
|
|
33
|
+
/**
|
|
34
|
+
* An event with no `metadata.app` (an order made before the tag existed):
|
|
35
|
+
* `'accept'` processes it as before (default), `'ignore'` leaves it to the
|
|
36
|
+
* other host (`unlabeled_app`). Needs `app`.
|
|
37
|
+
*/
|
|
38
|
+
unlabeled?: PolarUnlabeledPolicy;
|
|
24
39
|
/** Replay window in seconds. Default 300. */
|
|
25
40
|
toleranceSec?: number;
|
|
26
41
|
/** Wall clock for the replay window. Default `new Date()`. */
|
|
@@ -25,6 +25,9 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
|
|
25
25
|
/** Header and body bounds; past them the delivery is refused, not stored. */
|
|
26
26
|
const MAX_WEBHOOK_ID = 128;
|
|
27
27
|
const MAX_EVENT_TYPE = 64;
|
|
28
|
+
/** Keys the adapter writes into checkout metadata; a host cannot set them. */
|
|
29
|
+
const RESERVED_METADATA_KEYS = new Set(['checkout_id', 'app']);
|
|
30
|
+
const MAX_APP_LENGTH = 128;
|
|
28
31
|
const stateless = (pattern) => new RegExp(pattern.source, pattern.flags.replace(/[gy]/g, ''));
|
|
29
32
|
/**
|
|
30
33
|
* 2Novel's two-switch arming, made explicit: production needs both the
|
|
@@ -101,8 +104,23 @@ export function createPolarAdapter(options) {
|
|
|
101
104
|
const tolerance = options.toleranceSec ?? POLAR_WEBHOOK_TOLERANCE_SECONDS;
|
|
102
105
|
if (!Number.isFinite(tolerance) || tolerance <= 0)
|
|
103
106
|
throw new ProviderConfigError('polar_invalid_tolerance', 'toleranceSec must be positive');
|
|
107
|
+
const app = options.app;
|
|
108
|
+
if (app !== undefined && (typeof app !== 'string' || app.trim().length === 0 || app !== app.trim() || app.length > MAX_APP_LENGTH)) {
|
|
109
|
+
throw new ProviderConfigError('polar_invalid_app', 'app must be a non-blank string without surrounding whitespace, at most 128 characters');
|
|
110
|
+
}
|
|
111
|
+
const unlabeled = options.unlabeled;
|
|
112
|
+
if (unlabeled !== undefined && unlabeled !== 'accept' && unlabeled !== 'ignore') {
|
|
113
|
+
throw new ProviderConfigError('polar_invalid_unlabeled', "unlabeled must be 'accept' or 'ignore'");
|
|
114
|
+
}
|
|
115
|
+
if (unlabeled !== undefined && app === undefined) {
|
|
116
|
+
throw new ProviderConfigError('polar_unlabeled_requires_app', 'unlabeled has no meaning without an app tag');
|
|
117
|
+
}
|
|
104
118
|
const products = { ...options.products };
|
|
105
|
-
const normalizeOptions = {
|
|
119
|
+
const normalizeOptions = {
|
|
120
|
+
products,
|
|
121
|
+
checkoutPattern: stateless(options.checkoutPattern ?? UUID_RE),
|
|
122
|
+
...(app !== undefined ? { app, ...(unlabeled ? { unlabeled } : {}) } : {}),
|
|
123
|
+
};
|
|
106
124
|
const clock = options.clock ?? (() => new Date());
|
|
107
125
|
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
108
126
|
const timeoutMs = options.timeoutMs ?? 10_000;
|
|
@@ -112,6 +130,26 @@ export function createPolarAdapter(options) {
|
|
|
112
130
|
const matches = Object.keys(products).filter((id) => products[id] === productRef);
|
|
113
131
|
return matches.length === 1 ? matches[0] : null;
|
|
114
132
|
}
|
|
133
|
+
/** Host metadata for the checkout; the adapter's own keys are not the host's to set. */
|
|
134
|
+
function checkoutMetadata(input) {
|
|
135
|
+
if (input === undefined || input === null)
|
|
136
|
+
return {};
|
|
137
|
+
if (typeof input !== 'object' || Array.isArray(input))
|
|
138
|
+
throw new ProviderConfigError('polar_invalid_metadata', 'checkout metadata must be a flat object');
|
|
139
|
+
const out = {};
|
|
140
|
+
for (const [key, value] of Object.entries(input)) {
|
|
141
|
+
if (key === '__proto__')
|
|
142
|
+
throw new ProviderConfigError('polar_invalid_metadata', 'checkout metadata key "__proto__" is not allowed');
|
|
143
|
+
if (RESERVED_METADATA_KEYS.has(key)) {
|
|
144
|
+
throw new ProviderConfigError('polar_reserved_metadata_key', `checkout metadata key "${key}" is reserved by the adapter`);
|
|
145
|
+
}
|
|
146
|
+
if (typeof value !== 'string' && typeof value !== 'boolean' && !(typeof value === 'number' && Number.isFinite(value))) {
|
|
147
|
+
throw new ProviderConfigError('polar_invalid_metadata', `checkout metadata "${key}" must be a string, number or boolean`);
|
|
148
|
+
}
|
|
149
|
+
out[key] = value;
|
|
150
|
+
}
|
|
151
|
+
return out;
|
|
152
|
+
}
|
|
115
153
|
async function call(path, body) {
|
|
116
154
|
if (!options.accessToken) {
|
|
117
155
|
throw new ProviderConfigError('polar_not_configured', 'a Polar access token is required for checkout and portal sessions');
|
|
@@ -208,12 +246,15 @@ export function createPolarAdapter(options) {
|
|
|
208
246
|
if (!normalizeOptions.checkoutPattern.test(req.sessionId)) {
|
|
209
247
|
throw new ProviderConfigError('polar_invalid_checkout_id', 'checkout session id does not match the adapter checkoutPattern');
|
|
210
248
|
}
|
|
249
|
+
const metadata = checkoutMetadata(req.metadata);
|
|
250
|
+
const customerEmail = req.customerEmail?.trim();
|
|
211
251
|
const raw = await call('/checkouts/', {
|
|
212
252
|
products: [productId],
|
|
213
|
-
external_customer_id: req.accountId,
|
|
253
|
+
external_customer_id: req.externalCustomerId?.trim() || req.accountId,
|
|
214
254
|
...(req.customerIpAddress ? { customer_ip_address: req.customerIpAddress } : {}),
|
|
215
|
-
|
|
216
|
-
metadata
|
|
255
|
+
...(customerEmail ? { customer_email: customerEmail } : {}),
|
|
256
|
+
// Polar copies metadata onto the resulting order and subscription.
|
|
257
|
+
metadata: { checkout_id: req.sessionId, ...(app !== undefined ? { app } : {}), ...metadata },
|
|
217
258
|
// A discount code would make the order's amount differ from the
|
|
218
259
|
// session's catalog amount: the buyer pays and the purchase is parked
|
|
219
260
|
// for review. Discounts belong in the catalog, not on the pay page.
|
package/dist/providers/port.d.ts
CHANGED
|
@@ -153,6 +153,12 @@ export interface CheckoutRequest {
|
|
|
153
153
|
productRef?: string | null;
|
|
154
154
|
/** The buyer's IP when the host has it; adapters that cannot use it ignore it (Polar: tax country). */
|
|
155
155
|
customerIpAddress?: string | null;
|
|
156
|
+
/** The buyer's email, to prefill the pay page when the host has it; adapters that cannot use it ignore it (Polar: `customer_email`). */
|
|
157
|
+
customerEmail?: string | null;
|
|
158
|
+
/** The provider-side customer id when it is not `accountId` (Polar: `external_customer_id`, e.g. a host-namespaced `lohi:<uid>`); adapters that cannot use it ignore it. */
|
|
159
|
+
externalCustomerId?: string | null;
|
|
160
|
+
/** Host keys the provider carries onto the resulting purchase (Polar: checkout `metadata`). The adapter's own keys are reserved; adapters that cannot use it ignore it. */
|
|
161
|
+
metadata?: Readonly<Record<string, string | number | boolean>> | null;
|
|
156
162
|
}
|
|
157
163
|
export type CheckoutRedirect = {
|
|
158
164
|
kind: 'redirect';
|
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
|
|
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
|
|
@@ -218,6 +218,8 @@ await ingest.sweep()
|
|
|
218
218
|
`ignored` (`no_handler:<kind>`).
|
|
219
219
|
- **`createCheckout({ customerIpAddress })`** (1.1) is forwarded to the adapter's
|
|
220
220
|
`CheckoutRequest` when non-empty; an adapter that cannot use it ignores it.
|
|
221
|
+
`customerEmail`, `externalCustomerId` and `metadata` (1.2) travel the same
|
|
222
|
+
way, each only when non-blank / non-empty (see Polar → *Shared Polar org*).
|
|
221
223
|
- `sweep` lists only rows of the providers this ingest has adapters for, and
|
|
222
224
|
a row it cannot even record stays due without stopping the rows behind it.
|
|
223
225
|
- `onUnmatched` receives deliveries no session matches (e.g. another product's
|
|
@@ -268,7 +270,9 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
|
|
|
268
270
|
no default either, and it picks the API host:
|
|
269
271
|
`api.polar.sh` or `sandbox-api.polar.sh`. Sandbox and production products
|
|
270
272
|
have different ids, so pass the `products` map for the environment you run.
|
|
271
|
-
Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance
|
|
273
|
+
Other config errors: `polar_webhook_secrets_required`, `polar_invalid_tolerance`,
|
|
274
|
+
and, from 1.2, `polar_invalid_app`, `polar_invalid_unlabeled`,
|
|
275
|
+
`polar_unlabeled_requires_app`.
|
|
272
276
|
- **Standard Webhooks verification** runs on the raw body before any parse.
|
|
273
277
|
The signed content is `${webhook-id}.${webhook-timestamp}.${rawBody}`, HMAC-SHA256, and any
|
|
274
278
|
`v1,` entry of `webhook-signature` may match any secret in
|
|
@@ -280,13 +284,70 @@ const { url } = await polar.createPortalSession({ kind: 'account_id', value: acc
|
|
|
280
284
|
`malformed` (400). Nothing is stored in either case. The event id is
|
|
281
285
|
`polar:<webhook-id>`, so a retry of a message whose row is final is
|
|
282
286
|
`duplicate`; a `failed` row is processed again.
|
|
287
|
+
- **Shared Polar org (1.2).** Two hosts can run on one Polar organization
|
|
288
|
+
(Lohi and 2Novel do). Every webhook of the org reaches both, so each host
|
|
289
|
+
tags its checkouts and the adapter keeps only its own events.
|
|
290
|
+
|
|
291
|
+
| Option | |
|
|
292
|
+
|---|---|
|
|
293
|
+
| `app?: string` | This host's tag (non-blank, no surrounding whitespace, at most 128 characters; else `ProviderConfigError('polar_invalid_app')`). Stamped as `metadata.app` next to `metadata.checkout_id` on every checkout. Unset: no tag, no ownership check, behavior and request bodies exactly as 1.1.0 |
|
|
294
|
+
| `unlabeled?: 'accept' \| 'ignore'` | What an event with no `metadata.app` is. `'accept'` (default) processes it as before, for orders made before the tag existed; `'ignore'` leaves it to the other host. Needs `app` (`polar_unlabeled_requires_app`; anything else `polar_invalid_unlabeled`). Type `PolarUnlabeledPolicy` |
|
|
295
|
+
|
|
296
|
+
Ownership is read from `data.metadata.app` of the object the event is about,
|
|
297
|
+
before any other rule: `order.*` from the order, `subscription.*` from the
|
|
298
|
+
subscription, `checkout.*` from the checkout (Polar copies the checkout's
|
|
299
|
+
metadata onto the order and the subscription it creates). Other event types
|
|
300
|
+
are not classified (`unhandled_type:<type>`).
|
|
301
|
+
|
|
302
|
+
| `metadata.app` | `unlabeled` | normalized as |
|
|
303
|
+
|---|---|---|
|
|
304
|
+
| equal to `app` | any | processed as without a tag |
|
|
305
|
+
| present and anything else (another host's tag, empty, not a string, other case) | any | `ignored`, reason `foreign_app` |
|
|
306
|
+
| absent (no `metadata`, no key, or `null`) | `'accept'` | processed as without a tag |
|
|
307
|
+
| absent | `'ignore'` | `ignored`, reason `unlabeled_app` |
|
|
308
|
+
|
|
309
|
+
Foreign wins over every other rule, so a foreign partial refund, unknown
|
|
310
|
+
product, bad amount or unbound order is `ignored`, never `needs_review`.
|
|
311
|
+
What the host sees from `ingest.handle`: `{ status: 'ignored', reason:
|
|
312
|
+
'foreign_app' }` (or `unlabeled_app`), answered 200 by `respondPolar`
|
|
313
|
+
(`{received, outcome: 'ignored', reason}`), one inbox row in `ignored`, one
|
|
314
|
+
`billing.webhook` event with outcome `ignored`. No ledger entry, purchase,
|
|
315
|
+
term, `subscription.snapshot` handler call, `billing.alert`, `afterCredited`
|
|
316
|
+
or `onUnmatched` relay; a redelivery and `replay` answer `duplicate` with the
|
|
317
|
+
same reason and run nothing. The row is the delivery's redacted payload, kept
|
|
318
|
+
like any ignored delivery, so every foreign event of the org costs this host
|
|
319
|
+
one inbox row: plan the inbox's retention for `foreign_app` rows. Ownership
|
|
320
|
+
runs before the subscription-receipt rule, so with an `app` a renewal order
|
|
321
|
+
without our tag reads `foreign_app` / `unlabeled_app` rather than
|
|
322
|
+
`subscription_order`; nothing is credited either way. `metadata` that is
|
|
323
|
+
present but not an object counts as a foreign (unreadable) label.
|
|
324
|
+
|
|
325
|
+
`createCheckout` (and `ingest.createCheckout`, since the fields are on
|
|
326
|
+
`CheckoutRequest` / `CreateCheckoutInput`) also takes:
|
|
327
|
+
|
|
328
|
+
| Field | Polar request |
|
|
329
|
+
|---|---|
|
|
330
|
+
| `externalCustomerId?: string \| null` | `external_customer_id`; default `accountId`. Lohi: `lohi:<uid>` |
|
|
331
|
+
| `customerEmail?: string \| null` | `customer_email`, trimmed; omitted when blank |
|
|
332
|
+
| `metadata?: Record<string, string \| number \| boolean> \| null` | merged into `metadata` after `checkout_id` and `app` (e.g. `lohi_account`) |
|
|
333
|
+
|
|
334
|
+
`checkout_id` and `app` are reserved, whether or not the adapter has an
|
|
335
|
+
`app`: a host key with either name is refused before any call
|
|
336
|
+
(`polar_reserved_metadata_key`), and a value that is not a string, finite
|
|
337
|
+
number or boolean is `polar_invalid_metadata` (`__proto__` is refused too). Metadata values are
|
|
338
|
+
stored in the inbox with the payload and redacted by key name only: keep
|
|
339
|
+
personal data out of them. Polar's own limits on keys
|
|
340
|
+
and values, and a rejected `customer_email`, come back as a `PolarApiError`
|
|
341
|
+
(`polar_error`, with `status`). With no `app` and none of the new fields the
|
|
342
|
+
request body is byte-identical to 1.1.0. SePay, Apple and Google ignore the
|
|
343
|
+
three fields.
|
|
283
344
|
- **Credit packs.** `createCheckout` refuses an unmapped `productRef`
|
|
284
345
|
(exactly one Polar product per ref), a non-positive amount, or a session id
|
|
285
346
|
that is not `checkoutPattern` before any call (`ProviderConfigError` codes
|
|
286
347
|
`polar_unknown_product`, `polar_invalid_amount`, `polar_invalid_checkout_id`,
|
|
287
348
|
and `polar_not_configured` without a token). A failed call is `PolarApiError`
|
|
288
349
|
(`polar_unreachable`, `polar_error` with `status`, `polar_bad_response`). It then creates a Polar checkout
|
|
289
|
-
with `external_customer_id = accountId
|
|
350
|
+
with `external_customer_id = accountId` (or `externalCustomerId`), `metadata.checkout_id = sessionId`
|
|
290
351
|
and `allow_discount_codes: false`. A response whose currency or `amount`
|
|
291
352
|
(the product price before discount and tax) differs from the catalog amount,
|
|
292
353
|
or that carries a `discount_amount`, is refused as `polar_price_mismatch`.
|
|
@@ -632,3 +693,18 @@ quote:
|
|
|
632
693
|
|
|
633
694
|
**`serializePlanQuote`** puts `kind, plan, months, market` first and
|
|
634
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/docs/GUIDE.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# @tofound/billing — task guide (1.
|
|
1
|
+
# @tofound/billing — task guide (1.2)
|
|
2
2
|
|
|
3
3
|
How to do the common jobs with the library. [API.md](API.md) is the
|
|
4
4
|
reference for every export; this page walks the order of the calls and what
|
|
@@ -41,6 +41,7 @@ the session once.
|
|
|
41
41
|
credits: pack.credits + pack.bonusCredits, productRef: pack.productRef,
|
|
42
42
|
description, successUrl, errorUrl, cancelUrl,
|
|
43
43
|
customerIpAddress, // 1.1: Polar uses it for the tax country; others ignore it
|
|
44
|
+
// 1.2, Polar only (others ignore them): customerEmail, externalCustomerId, metadata — see API.md → Shared Polar org
|
|
44
45
|
})
|
|
45
46
|
// send the buyer to `redirect` (SePay: `kind: 'form'`; Polar: `kind: 'redirect'`)
|
|
46
47
|
```
|
package/docs/MIGRATION-LOHI.md
CHANGED
|
@@ -220,6 +220,61 @@ Ask the catalog for tiers (`SUBSCRIPTION_TIERS`,
|
|
|
220
220
|
`tiersWithPermission(…)`). Never retype a tier list: the library carries no
|
|
221
221
|
tier literals.
|
|
222
222
|
|
|
223
|
+
## Shared Polar org (1.2.0)
|
|
224
|
+
|
|
225
|
+
Lohi and 2Novel use one Polar organization, so every Polar webhook reaches
|
|
226
|
+
both hosts. Without a tag, a Lohi order refunded partially lands in
|
|
227
|
+
2Novel's `needs_review` queue and the other way round. 1.2.0 gives the Polar
|
|
228
|
+
adapter an `app` tag. Adopt it when Lohi moves its Polar checkout onto the
|
|
229
|
+
library; it replaces the private fetch decorator Lohi uses to stamp checkouts.
|
|
230
|
+
|
|
231
|
+
```ts
|
|
232
|
+
const polar = createPolarAdapter({
|
|
233
|
+
environment, webhookSecrets, products, accessToken,
|
|
234
|
+
app: 'lohi', // 2Novel: '2novel'
|
|
235
|
+
unlabeled: 'accept', // switch Lohi to 'ignore' only after the checks below; 2Novel keeps 'accept'
|
|
236
|
+
})
|
|
237
|
+
|
|
238
|
+
// Per checkout; ingest.createCheckout takes the same three fields.
|
|
239
|
+
await polar.createCheckout({
|
|
240
|
+
...request,
|
|
241
|
+
externalCustomerId: `lohi:${user.id}`,
|
|
242
|
+
customerEmail: user.email,
|
|
243
|
+
metadata: { lohi_account: user.id }, // `checkout_id` and `app` are reserved
|
|
244
|
+
})
|
|
245
|
+
```
|
|
246
|
+
|
|
247
|
+
- **Events:** `metadata.app === 'lohi'` is processed as before. Another tag is
|
|
248
|
+
`ignored` (`foreign_app`) and an event without the tag is `ignored`
|
|
249
|
+
(`unlabeled_app`) under `'ignore'`. Neither is credited, reversed,
|
|
250
|
+
snapshotted, alerted or relayed through `onUnmatched`, and a redelivery or
|
|
251
|
+
`replay` stays `ignored`. `respondPolar` acknowledges them with 200.
|
|
252
|
+
- **Account ids:** the library does not read `lohi_account`. With
|
|
253
|
+
`externalCustomerId: 'lohi:<uid>'`, subscription events arrive with
|
|
254
|
+
`account = { kind: 'polar_customer_external_id', value: 'lohi:<uid>' }`, and
|
|
255
|
+
`resolveAccount` strips the prefix. Reject an unprefixed id.
|
|
256
|
+
- **Account ids and the portal:** a portal for a namespaced customer takes the
|
|
257
|
+
`polar_customer_external_id` kind with the prefixed value
|
|
258
|
+
(`{ kind: 'polar_customer_external_id', value: 'lohi:<uid>' }`); an
|
|
259
|
+
`account_id` ref is sent as is, without the prefix.
|
|
260
|
+
- **Before turning on `'ignore'`:** an event is Lohi's only if its object
|
|
261
|
+
carries `metadata.app`. Both hosts stamp UUID `checkout_id`s, so an event
|
|
262
|
+
with only a `checkout_id` cannot be told apart and is ignored
|
|
263
|
+
(`unlabeled_app`) under `'ignore'`: no credit, no reversal, no alert. That
|
|
264
|
+
covers a checkout created before the tag shipped and paid later (a payment
|
|
265
|
+
after the 30-minute session still credits), and the refund of any order made
|
|
266
|
+
before the tag. Keep `'accept'` until the pre-tag sessions have settled, and
|
|
267
|
+
deal with pre-tag refunds by hand. Subscription events are classified by the
|
|
268
|
+
subscription's own `metadata.app`, which relies on Polar copying the
|
|
269
|
+
checkout's metadata onto the subscription (it does for orders): check one
|
|
270
|
+
sandbox subscription end to end first, or its access is never granted.
|
|
271
|
+
- **Personal data:** the inbox redacts by key name only, so a PII value under a
|
|
272
|
+
neutral metadata key (`note: 'John Doe'`) is stored. Put ids in `metadata`,
|
|
273
|
+
never names, emails or phone numbers.
|
|
274
|
+
- **Both hosts:** deploy the tag on the checkout side before turning on `ignore`
|
|
275
|
+
on the receiving side, and keep the webhook subscription of each host
|
|
276
|
+
pointed at its own URL; the tag only decides whose event a delivery is.
|
|
277
|
+
|
|
223
278
|
## Quotes
|
|
224
279
|
|
|
225
280
|
Lohi keeps `planFunding()` and `GATES`, and `/pricing/quote` stays byte
|
package/package.json
CHANGED