munim-billing 0.0.0-stage → 0.2.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/LICENSE +201 -0
- package/README.md +550 -2
- package/lib/cjs/client.js +233 -0
- package/lib/cjs/client.js.map +1 -0
- package/lib/cjs/errors.js +55 -0
- package/lib/cjs/errors.js.map +1 -0
- package/lib/cjs/index.js +28 -0
- package/lib/cjs/index.js.map +1 -0
- package/lib/cjs/package.json +1 -0
- package/lib/cjs/react-native.js +118 -0
- package/lib/cjs/react-native.js.map +1 -0
- package/lib/cjs/types.js +21 -0
- package/lib/cjs/types.js.map +1 -0
- package/lib/cjs/version.js +6 -0
- package/lib/cjs/version.js.map +1 -0
- package/lib/cjs/web.js +157 -0
- package/lib/cjs/web.js.map +1 -0
- package/lib/cjs/webhooks.js +137 -0
- package/lib/cjs/webhooks.js.map +1 -0
- package/lib/esm/client.d.ts +131 -0
- package/lib/esm/client.d.ts.map +1 -0
- package/lib/esm/client.js +226 -0
- package/lib/esm/client.js.map +1 -0
- package/lib/esm/errors.d.ts +22 -0
- package/lib/esm/errors.d.ts.map +1 -0
- package/lib/esm/errors.js +50 -0
- package/lib/esm/errors.js.map +1 -0
- package/lib/esm/index.d.ts +10 -0
- package/lib/esm/index.d.ts.map +1 -0
- package/lib/esm/index.js +6 -0
- package/lib/esm/index.js.map +1 -0
- package/lib/esm/package.json +1 -0
- package/lib/esm/react-native.d.ts +72 -0
- package/lib/esm/react-native.d.ts.map +1 -0
- package/lib/esm/react-native.js +114 -0
- package/lib/esm/react-native.js.map +1 -0
- package/lib/esm/types.d.ts +303 -0
- package/lib/esm/types.d.ts.map +1 -0
- package/lib/esm/types.js +18 -0
- package/lib/esm/types.js.map +1 -0
- package/lib/esm/version.d.ts +3 -0
- package/lib/esm/version.d.ts.map +1 -0
- package/lib/esm/version.js +3 -0
- package/lib/esm/version.js.map +1 -0
- package/lib/esm/web.d.ts +40 -0
- package/lib/esm/web.d.ts.map +1 -0
- package/lib/esm/web.js +152 -0
- package/lib/esm/web.js.map +1 -0
- package/lib/esm/webhooks.d.ts +59 -0
- package/lib/esm/webhooks.d.ts.map +1 -0
- package/lib/esm/webhooks.js +129 -0
- package/lib/esm/webhooks.js.map +1 -0
- package/package.json +116 -4
- package/src/client.ts +314 -0
- package/src/errors.ts +74 -0
- package/src/index.ts +26 -0
- package/src/react-native.ts +154 -0
- package/src/types.ts +366 -0
- package/src/version.ts +2 -0
- package/src/web.ts +182 -0
- package/src/webhooks.ts +169 -0
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { MunimBillingError } from './errors.js';
|
|
2
|
+
/**
|
|
3
|
+
* Webhook signatures.
|
|
4
|
+
*
|
|
5
|
+
* Munim signs each delivery with the endpoint's secret (`whsec_…`):
|
|
6
|
+
*
|
|
7
|
+
* Munim-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
|
|
8
|
+
*
|
|
9
|
+
* The HMAC key is the whole secret string, `whsec_` prefix included, as
|
|
10
|
+
* UTF-8. A header may carry several `v1=` values (while a secret rotates);
|
|
11
|
+
* any one matching is enough.
|
|
12
|
+
*
|
|
13
|
+
* Uses WebCrypto (`crypto.subtle`), so it runs in Node 20+, Deno, Bun,
|
|
14
|
+
* edge runtimes, Convex and browsers. Node 18 needs
|
|
15
|
+
* `--experimental-global-webcrypto`.
|
|
16
|
+
*/
|
|
17
|
+
export const SIGNATURE_HEADER = 'Munim-Signature';
|
|
18
|
+
export const EVENT_ID_HEADER = 'Munim-Event-Id';
|
|
19
|
+
export const DEFAULT_TOLERANCE_SECONDS = 300;
|
|
20
|
+
const encoder = new TextEncoder();
|
|
21
|
+
function subtle() {
|
|
22
|
+
const value = globalThis.crypto?.subtle;
|
|
23
|
+
if (!value) {
|
|
24
|
+
throw new MunimBillingError('Web Crypto (crypto.subtle) is not available in this runtime. Use Node 20+ or another runtime with WebCrypto.', { type: 'internal' });
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function toHex(buffer) {
|
|
29
|
+
return Array.from(new Uint8Array(buffer), (byte) => byte.toString(16).padStart(2, '0')).join('');
|
|
30
|
+
}
|
|
31
|
+
function asString(body) {
|
|
32
|
+
return typeof body === 'string' ? body : new TextDecoder().decode(body);
|
|
33
|
+
}
|
|
34
|
+
/** Hex HMAC-SHA256 of `${timestamp}.${rawBody}` with `secret` as the key. */
|
|
35
|
+
export async function computeSignature(secret, rawBody, timestamp) {
|
|
36
|
+
const key = await subtle().importKey('raw', encoder.encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
|
|
37
|
+
const mac = await subtle().sign('HMAC', key, encoder.encode(`${timestamp}.${asString(rawBody)}`));
|
|
38
|
+
return toHex(mac);
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The `Munim-Signature` header value for a payload: `t=<timestamp>,v1=<hex>`.
|
|
42
|
+
*
|
|
43
|
+
* @param timestamp Unix **seconds**. Defaults to now.
|
|
44
|
+
*/
|
|
45
|
+
export async function signWebhookPayload(secret, rawBody, timestamp = Math.floor(Date.now() / 1000)) {
|
|
46
|
+
const t = Math.floor(timestamp);
|
|
47
|
+
return `t=${t},v1=${await computeSignature(secret, rawBody, t)}`;
|
|
48
|
+
}
|
|
49
|
+
/** Splits `t=…,v1=…,v1=…` into its timestamp and signatures. */
|
|
50
|
+
export function parseSignatureHeader(header) {
|
|
51
|
+
let timestamp = null;
|
|
52
|
+
const signatures = [];
|
|
53
|
+
for (const part of header.split(',')) {
|
|
54
|
+
const index = part.indexOf('=');
|
|
55
|
+
if (index < 0)
|
|
56
|
+
continue;
|
|
57
|
+
const key = part.slice(0, index).trim();
|
|
58
|
+
const value = part.slice(index + 1).trim();
|
|
59
|
+
if (key === 't' && /^\d+$/.test(value)) {
|
|
60
|
+
timestamp = Number(value);
|
|
61
|
+
}
|
|
62
|
+
else if (key === 'v1' && value) {
|
|
63
|
+
signatures.push(value.toLowerCase());
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { timestamp, signatures };
|
|
67
|
+
}
|
|
68
|
+
/** Compares two strings in time that depends only on their length. */
|
|
69
|
+
export function timingSafeEqual(a, b) {
|
|
70
|
+
if (a.length !== b.length)
|
|
71
|
+
return false;
|
|
72
|
+
let diff = 0;
|
|
73
|
+
for (let i = 0; i < a.length; i++) {
|
|
74
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
75
|
+
}
|
|
76
|
+
return diff === 0;
|
|
77
|
+
}
|
|
78
|
+
function fail(message) {
|
|
79
|
+
throw new MunimBillingError(message, { type: 'signature_verification', status: 400 });
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Checks a webhook delivery and returns its event.
|
|
83
|
+
*
|
|
84
|
+
* Pass the request body exactly as received (before any JSON parsing), the
|
|
85
|
+
* `Munim-Signature` header, and the endpoint's `whsec_…` secret. Throws a
|
|
86
|
+
* `MunimBillingError` with `type: 'signature_verification'` when the
|
|
87
|
+
* signature doesn't match or the timestamp is outside the tolerance.
|
|
88
|
+
*/
|
|
89
|
+
export async function verifyWebhook(rawBody, signatureHeader, secret, options = {}) {
|
|
90
|
+
if (!secret)
|
|
91
|
+
fail('No webhook secret was given.');
|
|
92
|
+
if (!signatureHeader)
|
|
93
|
+
fail(`Missing ${SIGNATURE_HEADER} header.`);
|
|
94
|
+
const { timestamp, signatures } = parseSignatureHeader(signatureHeader);
|
|
95
|
+
if (timestamp === null || signatures.length === 0) {
|
|
96
|
+
fail(`Malformed ${SIGNATURE_HEADER} header.`);
|
|
97
|
+
}
|
|
98
|
+
const expected = await computeSignature(secret, rawBody, timestamp);
|
|
99
|
+
if (!signatures.some((signature) => timingSafeEqual(signature, expected))) {
|
|
100
|
+
fail('Webhook signature does not match. Check the secret and that the body is the raw, unparsed request body.');
|
|
101
|
+
}
|
|
102
|
+
const tolerance = options.toleranceSeconds ?? DEFAULT_TOLERANCE_SECONDS;
|
|
103
|
+
if (tolerance > 0) {
|
|
104
|
+
const nowSeconds = Math.floor((options.now ?? Date.now()) / 1000);
|
|
105
|
+
if (Math.abs(nowSeconds - timestamp) > tolerance) {
|
|
106
|
+
fail('Webhook timestamp is outside the tolerance.');
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
try {
|
|
110
|
+
return JSON.parse(asString(rawBody));
|
|
111
|
+
}
|
|
112
|
+
catch (cause) {
|
|
113
|
+
throw new MunimBillingError('Webhook body is not valid JSON.', {
|
|
114
|
+
type: 'signature_verification',
|
|
115
|
+
status: 400,
|
|
116
|
+
cause,
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** `munim.webhooks` / `MunimBilling.webhooks`. */
|
|
121
|
+
export const webhooks = {
|
|
122
|
+
verify: verifyWebhook,
|
|
123
|
+
sign: signWebhookPayload,
|
|
124
|
+
computeSignature,
|
|
125
|
+
parseHeader: parseSignatureHeader,
|
|
126
|
+
SIGNATURE_HEADER,
|
|
127
|
+
EVENT_ID_HEADER,
|
|
128
|
+
};
|
|
129
|
+
//# sourceMappingURL=webhooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"webhooks.js","sourceRoot":"","sources":["../../src/webhooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,aAAa,CAAA;AAG/C;;;;;;;;;;;;;;GAcG;AAEH,MAAM,CAAC,MAAM,gBAAgB,GAAG,iBAAiB,CAAA;AACjD,MAAM,CAAC,MAAM,eAAe,GAAG,gBAAgB,CAAA;AAC/C,MAAM,CAAC,MAAM,yBAAyB,GAAG,GAAG,CAAA;AAE5C,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAA;AAEjC,SAAS,MAAM;IACb,MAAM,KAAK,GAAI,UAAkC,CAAC,MAAM,EAAE,MAAM,CAAA;IAChE,IAAI,CAAC,KAAK,EAAE,CAAC;QACX,MAAM,IAAI,iBAAiB,CACzB,8GAA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EAAE,CAAC;QAClB,MAAM,UAAU,GAAG,IAAI,CAAC,KAAK,CAAC,CAAC,OAAO,CAAC,GAAG,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC,GAAG,IAAI,CAAC,CAAA;QACjE,IAAI,IAAI,CAAC,GAAG,CAAC,UAAU,GAAG,SAAS,CAAC,GAAG,SAAS,EAAE,CAAC;YACjD,IAAI,CAAC,6CAA6C,CAAC,CAAA;QACrD,CAAC;IACH,CAAC;IAED,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAU,CAAA;IAC/C,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,iBAAiB,CAAC,iCAAiC,EAAE;YAC7D,IAAI,EAAE,wBAAwB;YAC9B,MAAM,EAAE,GAAG;YACX,KAAK;SACN,CAAC,CAAA;IACJ,CAAC;AACH,CAAC;AAED,kDAAkD;AAClD,MAAM,CAAC,MAAM,QAAQ,GAAG;IACtB,MAAM,EAAE,aAAa;IACrB,IAAI,EAAE,kBAAkB;IACxB,gBAAgB;IAChB,WAAW,EAAE,oBAAoB;IACjC,gBAAgB;IAChB,eAAe;CACP,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,118 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "munim-billing",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Munim Billing: take payments with Munim, Inc. as your merchant of record. Cards, Apple Pay, Google Pay, PayPal and Venmo through one API; Munim handles the payment, keeps its fee and pays you out to your bank or PayPal. Server SDK, webhook verification, and checkout helpers for the web and React Native / Expo",
|
|
5
|
+
"main": "./lib/cjs/index.js",
|
|
6
|
+
"module": "./lib/esm/index.js",
|
|
7
|
+
"types": "./lib/esm/index.d.ts",
|
|
8
|
+
"react-native": "./lib/esm/index.js",
|
|
9
|
+
"source": "./src/index.ts",
|
|
10
|
+
"sideEffects": false,
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./lib/esm/index.d.ts",
|
|
14
|
+
"import": "./lib/esm/index.js",
|
|
15
|
+
"require": "./lib/cjs/index.js"
|
|
16
|
+
},
|
|
17
|
+
"./web": {
|
|
18
|
+
"types": "./lib/esm/web.d.ts",
|
|
19
|
+
"import": "./lib/esm/web.js",
|
|
20
|
+
"require": "./lib/cjs/web.js"
|
|
21
|
+
},
|
|
22
|
+
"./react-native": {
|
|
23
|
+
"types": "./lib/esm/react-native.d.ts",
|
|
24
|
+
"import": "./lib/esm/react-native.js",
|
|
25
|
+
"require": "./lib/cjs/react-native.js"
|
|
26
|
+
},
|
|
27
|
+
"./package.json": "./package.json"
|
|
28
|
+
},
|
|
29
|
+
"typesVersions": {
|
|
30
|
+
"*": {
|
|
31
|
+
"web": [
|
|
32
|
+
"./lib/esm/web.d.ts"
|
|
33
|
+
],
|
|
34
|
+
"react-native": [
|
|
35
|
+
"./lib/esm/react-native.d.ts"
|
|
36
|
+
]
|
|
37
|
+
}
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"typecheck": "tsc --noEmit -p tsconfig.json",
|
|
41
|
+
"clean": "rm -rf lib",
|
|
42
|
+
"build": "npm run clean && tsc -p tsconfig.build.json && tsc -p tsconfig.cjs.json && node scripts/write-module-types.mjs",
|
|
43
|
+
"test": "vitest run",
|
|
44
|
+
"release": "semantic-release"
|
|
45
|
+
},
|
|
46
|
+
"keywords": [
|
|
47
|
+
"billing",
|
|
48
|
+
"payments",
|
|
49
|
+
"merchant-of-record",
|
|
50
|
+
"checkout",
|
|
51
|
+
"subscriptions",
|
|
52
|
+
"stripe",
|
|
53
|
+
"paypal",
|
|
54
|
+
"venmo",
|
|
55
|
+
"apple-pay",
|
|
56
|
+
"google-pay",
|
|
57
|
+
"webhooks",
|
|
58
|
+
"payouts",
|
|
59
|
+
"react-native",
|
|
60
|
+
"expo",
|
|
61
|
+
"typescript",
|
|
62
|
+
"munim-technologies"
|
|
63
|
+
],
|
|
64
|
+
"files": [
|
|
65
|
+
"src",
|
|
66
|
+
"!src/__tests__",
|
|
67
|
+
"lib",
|
|
68
|
+
"README.md",
|
|
69
|
+
"CHANGELOG.md",
|
|
70
|
+
"LICENSE"
|
|
71
|
+
],
|
|
72
|
+
"repository": {
|
|
73
|
+
"type": "git",
|
|
74
|
+
"url": "git+https://github.com/munimtechnologies/munim-billing.git"
|
|
75
|
+
},
|
|
76
|
+
"author": "sheehanmunim <support@munimtech.com> (https://github.com/sheehanmunim)",
|
|
77
|
+
"license": "Apache-2.0",
|
|
78
|
+
"bugs": {
|
|
79
|
+
"url": "https://github.com/munimtechnologies/munim-billing/issues"
|
|
80
|
+
},
|
|
81
|
+
"homepage": "https://munimtech.com/billing",
|
|
82
|
+
"publishConfig": {
|
|
83
|
+
"access": "public",
|
|
84
|
+
"registry": "https://registry.npmjs.org/"
|
|
85
|
+
},
|
|
86
|
+
"engines": {
|
|
87
|
+
"node": ">=18"
|
|
88
|
+
},
|
|
89
|
+
"peerDependencies": {
|
|
90
|
+
"expo-web-browser": "*",
|
|
91
|
+
"react-native": "*"
|
|
92
|
+
},
|
|
93
|
+
"peerDependenciesMeta": {
|
|
94
|
+
"expo-web-browser": {
|
|
95
|
+
"optional": true
|
|
96
|
+
},
|
|
97
|
+
"react-native": {
|
|
98
|
+
"optional": true
|
|
99
|
+
}
|
|
100
|
+
},
|
|
101
|
+
"devDependencies": {
|
|
102
|
+
"@semantic-release/changelog": "^6.0.3",
|
|
103
|
+
"@semantic-release/git": "^10.0.1",
|
|
104
|
+
"conventional-changelog-conventionalcommits": "^9.3.1",
|
|
105
|
+
"happy-dom": "^21.0.4",
|
|
106
|
+
"semantic-release": "^25.0.9",
|
|
107
|
+
"typescript": "^5.8.3",
|
|
108
|
+
"vitest": "^5.0.5"
|
|
109
|
+
},
|
|
110
|
+
"prettier": {
|
|
111
|
+
"quoteProps": "consistent",
|
|
112
|
+
"singleQuote": true,
|
|
113
|
+
"tabWidth": 2,
|
|
114
|
+
"trailingComma": "es5",
|
|
115
|
+
"useTabs": false,
|
|
116
|
+
"semi": false
|
|
117
|
+
}
|
|
118
|
+
}
|
package/src/client.ts
ADDED
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
import { errorFromResponse, MunimBillingError } from './errors.js'
|
|
2
|
+
import type {
|
|
3
|
+
AppleReceiptParams,
|
|
4
|
+
Balance,
|
|
5
|
+
Entitlement,
|
|
6
|
+
GoogleReceiptParams,
|
|
7
|
+
StoreSubscription,
|
|
8
|
+
StoreSubscriptionListParams,
|
|
9
|
+
Subscriber,
|
|
10
|
+
Checkout,
|
|
11
|
+
CheckoutCreateParams,
|
|
12
|
+
Customer,
|
|
13
|
+
CustomerListParams,
|
|
14
|
+
List,
|
|
15
|
+
ListParams,
|
|
16
|
+
ManageUrl,
|
|
17
|
+
Mode,
|
|
18
|
+
Payout,
|
|
19
|
+
Price,
|
|
20
|
+
PriceCreateParams,
|
|
21
|
+
PriceListParams,
|
|
22
|
+
PriceUpdateParams,
|
|
23
|
+
Product,
|
|
24
|
+
ProductCreateParams,
|
|
25
|
+
ProductUpdateParams,
|
|
26
|
+
RefundParams,
|
|
27
|
+
Subscription,
|
|
28
|
+
SubscriptionCancelParams,
|
|
29
|
+
SubscriptionListParams,
|
|
30
|
+
Transaction,
|
|
31
|
+
TransactionListParams,
|
|
32
|
+
} from './types.js'
|
|
33
|
+
import { VERSION } from './version.js'
|
|
34
|
+
import { webhooks } from './webhooks.js'
|
|
35
|
+
|
|
36
|
+
export const LIVE_BASE_URL = 'https://billing-api.munimtech.com'
|
|
37
|
+
export const TEST_BASE_URL = 'https://billing-sandbox-api.munimtech.com'
|
|
38
|
+
|
|
39
|
+
/** `'test'` for `mb_test_…` keys, `'live'` for `mb_live_…`, `null` otherwise. */
|
|
40
|
+
export function modeForKey(secretKey: string): Mode | null {
|
|
41
|
+
if (secretKey.startsWith('mb_test_')) return 'test'
|
|
42
|
+
if (secretKey.startsWith('mb_live_')) return 'live'
|
|
43
|
+
return null
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The API base for a key: the sandbox for `mb_test_…`, live for `mb_live_…`. */
|
|
47
|
+
export function baseUrlForKey(secretKey: string): string {
|
|
48
|
+
const mode = modeForKey(secretKey)
|
|
49
|
+
if (mode === 'test') return TEST_BASE_URL
|
|
50
|
+
if (mode === 'live') return LIVE_BASE_URL
|
|
51
|
+
throw new MunimBillingError(
|
|
52
|
+
'Munim Billing secret keys start with mb_test_sk_ or mb_live_sk_. Find yours at https://munimtech.com/billing/dashboard.',
|
|
53
|
+
{ type: 'authentication' }
|
|
54
|
+
)
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>
|
|
58
|
+
|
|
59
|
+
export type MunimBillingOptions = {
|
|
60
|
+
/** Overrides the API base picked from the key, e.g. a `https://<name>.convex.site` URL. */
|
|
61
|
+
baseUrl?: string
|
|
62
|
+
/** A `fetch` to use instead of the global one. */
|
|
63
|
+
fetch?: FetchLike
|
|
64
|
+
/** Per-request timeout. Default 30 000 ms. */
|
|
65
|
+
timeoutMs?: number
|
|
66
|
+
/**
|
|
67
|
+
* The secret key must never ship in a browser or app. The client refuses
|
|
68
|
+
* to start there unless this is `true` (e.g. for a local tool).
|
|
69
|
+
*/
|
|
70
|
+
dangerouslyAllowBrowser?: boolean
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
type Query = Record<string, string | number | boolean | null | undefined>
|
|
74
|
+
|
|
75
|
+
type RequestOptions = {
|
|
76
|
+
query?: Query
|
|
77
|
+
body?: unknown
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A list call that can also walk every page: `await list(params)` or `for await (const x of list.all(params))`. */
|
|
81
|
+
export type ListMethod<T, P extends ListParams> = ((params?: P) => Promise<List<T>>) & {
|
|
82
|
+
all: (params?: P) => AsyncIterableIterator<T>
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Walks every page of a list, starting from `params.cursor` (if any).
|
|
87
|
+
*
|
|
88
|
+
* ```ts
|
|
89
|
+
* for await (const txn of paginate((p) => munim.transactions.list(p), { limit: 100 })) { … }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
export async function* paginate<T, P extends ListParams>(
|
|
93
|
+
fetchPage: (params: P) => Promise<List<T>>,
|
|
94
|
+
params: P = {} as P
|
|
95
|
+
): AsyncIterableIterator<T> {
|
|
96
|
+
let cursor = params.cursor
|
|
97
|
+
for (;;) {
|
|
98
|
+
const page = await fetchPage({ ...params, cursor })
|
|
99
|
+
for (const item of page.data) {
|
|
100
|
+
yield item
|
|
101
|
+
}
|
|
102
|
+
if (!page.has_more || !page.next_cursor) return
|
|
103
|
+
cursor = page.next_cursor
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function listMethod<T, P extends ListParams>(fetchPage: (params: P) => Promise<List<T>>): ListMethod<T, P> {
|
|
108
|
+
const method = ((params?: P) => fetchPage((params ?? {}) as P)) as ListMethod<T, P>
|
|
109
|
+
method.all = (params?: P) => paginate(fetchPage, (params ?? {}) as P)
|
|
110
|
+
return method
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function isBrowserLike(): boolean {
|
|
114
|
+
const g = globalThis as { window?: unknown; document?: unknown; navigator?: { product?: string } }
|
|
115
|
+
return (
|
|
116
|
+
(typeof g.window !== 'undefined' && typeof g.document !== 'undefined') ||
|
|
117
|
+
g.navigator?.product === 'ReactNative'
|
|
118
|
+
)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function id(value: string): string {
|
|
122
|
+
if (!value) {
|
|
123
|
+
throw new MunimBillingError('An id is required.', { type: 'invalid_request', param: 'id' })
|
|
124
|
+
}
|
|
125
|
+
return encodeURIComponent(value)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The Munim Billing server client.
|
|
130
|
+
*
|
|
131
|
+
* ```ts
|
|
132
|
+
* const munim = new MunimBilling(process.env.MUNIM_BILLING_SECRET_KEY!)
|
|
133
|
+
* const checkout = await munim.checkouts.create({ price_id: 'pri_…' })
|
|
134
|
+
* ```
|
|
135
|
+
*/
|
|
136
|
+
export class MunimBilling {
|
|
137
|
+
/** Webhook helpers, also available as `munim.webhooks`. */
|
|
138
|
+
static readonly webhooks = webhooks
|
|
139
|
+
readonly webhooks = webhooks
|
|
140
|
+
|
|
141
|
+
/** `'test'` or `'live'`, from the key prefix (`null` for other keys with a custom `baseUrl`). */
|
|
142
|
+
readonly mode: Mode | null
|
|
143
|
+
readonly baseUrl: string
|
|
144
|
+
|
|
145
|
+
readonly #secretKey: string
|
|
146
|
+
readonly #fetch: FetchLike
|
|
147
|
+
readonly #timeoutMs: number
|
|
148
|
+
|
|
149
|
+
constructor(secretKey: string, options: MunimBillingOptions = {}) {
|
|
150
|
+
if (!secretKey || typeof secretKey !== 'string') {
|
|
151
|
+
throw new MunimBillingError('A Munim Billing secret key is required.', { type: 'authentication' })
|
|
152
|
+
}
|
|
153
|
+
if (!options.dangerouslyAllowBrowser && isBrowserLike()) {
|
|
154
|
+
throw new MunimBillingError(
|
|
155
|
+
'MunimBilling uses your secret key and must run on your server. In a browser or app, create the checkout on your server and open its url with munim-billing/web or munim-billing/react-native.',
|
|
156
|
+
{ type: 'invalid_request' }
|
|
157
|
+
)
|
|
158
|
+
}
|
|
159
|
+
this.#secretKey = secretKey
|
|
160
|
+
this.mode = modeForKey(secretKey)
|
|
161
|
+
this.baseUrl = (options.baseUrl ?? baseUrlForKey(secretKey)).replace(/\/+$/, '')
|
|
162
|
+
const fetchImpl = options.fetch ?? (globalThis as { fetch?: FetchLike }).fetch
|
|
163
|
+
if (!fetchImpl) {
|
|
164
|
+
throw new MunimBillingError('No fetch is available. Pass one with options.fetch.', { type: 'internal' })
|
|
165
|
+
}
|
|
166
|
+
this.#fetch = fetchImpl
|
|
167
|
+
this.#timeoutMs = options.timeoutMs ?? 30_000
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** Sends one request to the API. The resource methods below are built on it. */
|
|
171
|
+
async request<T>(method: 'GET' | 'POST', path: string, options: RequestOptions = {}): Promise<T> {
|
|
172
|
+
let url = `${this.baseUrl}${path}`
|
|
173
|
+
if (options.query) {
|
|
174
|
+
const search = new URLSearchParams()
|
|
175
|
+
for (const [key, value] of Object.entries(options.query)) {
|
|
176
|
+
if (value !== undefined && value !== null) search.append(key, String(value))
|
|
177
|
+
}
|
|
178
|
+
const encoded = search.toString()
|
|
179
|
+
if (encoded) url += `?${encoded}`
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const headers: Record<string, string> = {
|
|
183
|
+
'Authorization': `Bearer ${this.#secretKey}`,
|
|
184
|
+
'Accept': 'application/json',
|
|
185
|
+
'Munim-Billing-Client': `munim-billing-js/${VERSION}`,
|
|
186
|
+
}
|
|
187
|
+
let body: string | undefined
|
|
188
|
+
if (method === 'POST') {
|
|
189
|
+
headers['Content-Type'] = 'application/json'
|
|
190
|
+
body = JSON.stringify(options.body ?? {})
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const controller = typeof AbortController !== 'undefined' ? new AbortController() : undefined
|
|
194
|
+
const timer = controller ? setTimeout(() => controller.abort(), this.#timeoutMs) : undefined
|
|
195
|
+
let response: Response
|
|
196
|
+
try {
|
|
197
|
+
response = await this.#fetch(url, { method, headers, body, signal: controller?.signal })
|
|
198
|
+
} catch (cause) {
|
|
199
|
+
const timedOut = controller?.signal.aborted
|
|
200
|
+
throw new MunimBillingError(
|
|
201
|
+
timedOut
|
|
202
|
+
? `Munim Billing request timed out after ${this.#timeoutMs} ms.`
|
|
203
|
+
: 'Could not reach Munim Billing.',
|
|
204
|
+
{ type: 'connection', cause }
|
|
205
|
+
)
|
|
206
|
+
} finally {
|
|
207
|
+
if (timer) clearTimeout(timer)
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
const text = await response.text()
|
|
211
|
+
let parsed: unknown = undefined
|
|
212
|
+
if (text) {
|
|
213
|
+
try {
|
|
214
|
+
parsed = JSON.parse(text)
|
|
215
|
+
} catch {
|
|
216
|
+
parsed = undefined
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
if (!response.ok) {
|
|
220
|
+
throw errorFromResponse(response.status, parsed)
|
|
221
|
+
}
|
|
222
|
+
if (parsed === undefined) {
|
|
223
|
+
throw new MunimBillingError('Munim Billing returned a response that is not JSON.', {
|
|
224
|
+
type: 'internal',
|
|
225
|
+
status: response.status,
|
|
226
|
+
})
|
|
227
|
+
}
|
|
228
|
+
return parsed as T
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
#get<T>(path: string, query?: Query): Promise<T> {
|
|
232
|
+
return this.request<T>('GET', path, { query })
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
#post<T>(path: string, body?: unknown): Promise<T> {
|
|
236
|
+
return this.request<T>('POST', path, { body })
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
readonly products = {
|
|
240
|
+
create: (params: ProductCreateParams) => this.#post<Product>('/v1/products', params),
|
|
241
|
+
list: listMethod<Product, ListParams>((params) => this.#get('/v1/products', params)),
|
|
242
|
+
retrieve: (productId: string) => this.#get<Product>(`/v1/products/${id(productId)}`),
|
|
243
|
+
update: (productId: string, params: ProductUpdateParams) =>
|
|
244
|
+
this.#post<Product>(`/v1/products/${id(productId)}`, params),
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
readonly prices = {
|
|
248
|
+
create: (params: PriceCreateParams) => this.#post<Price>('/v1/prices', params),
|
|
249
|
+
list: listMethod<Price, PriceListParams>((params) => this.#get('/v1/prices', params)),
|
|
250
|
+
retrieve: (priceId: string) => this.#get<Price>(`/v1/prices/${id(priceId)}`),
|
|
251
|
+
/** A price's amount can't change; make a new price instead. */
|
|
252
|
+
update: (priceId: string, params: PriceUpdateParams) =>
|
|
253
|
+
this.#post<Price>(`/v1/prices/${id(priceId)}`, params),
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
readonly checkouts = {
|
|
257
|
+
/** Creates a checkout. Send the customer to its `url`. */
|
|
258
|
+
create: (params: CheckoutCreateParams) => this.#post<Checkout>('/v1/checkouts', params),
|
|
259
|
+
retrieve: (checkoutId: string) => this.#get<Checkout>(`/v1/checkouts/${id(checkoutId)}`),
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
readonly customers = {
|
|
263
|
+
list: listMethod<Customer, CustomerListParams>((params) => this.#get('/v1/customers', params)),
|
|
264
|
+
retrieve: (customerId: string) => this.#get<Customer>(`/v1/customers/${id(customerId)}`),
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
readonly transactions = {
|
|
268
|
+
list: listMethod<Transaction, TransactionListParams>((params) => this.#get('/v1/transactions', params)),
|
|
269
|
+
retrieve: (transactionId: string) => this.#get<Transaction>(`/v1/transactions/${id(transactionId)}`),
|
|
270
|
+
/** Refunds `amount` cents, or everything not yet refunded. */
|
|
271
|
+
refund: (transactionId: string, params: RefundParams = {}) =>
|
|
272
|
+
this.#post<Transaction>(`/v1/transactions/${id(transactionId)}/refund`, params),
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
readonly subscriptions = {
|
|
276
|
+
list: listMethod<Subscription, SubscriptionListParams>((params) => this.#get('/v1/subscriptions', params)),
|
|
277
|
+
retrieve: (subscriptionId: string) => this.#get<Subscription>(`/v1/subscriptions/${id(subscriptionId)}`),
|
|
278
|
+
/** Cancels at the end of the paid period by default; `{ at_period_end: false }` cancels now. */
|
|
279
|
+
cancel: (subscriptionId: string, params: SubscriptionCancelParams = {}) =>
|
|
280
|
+
this.#post<Subscription>(`/v1/subscriptions/${id(subscriptionId)}/cancel`, params),
|
|
281
|
+
/** A Munim-hosted page where the customer can see and cancel the subscription. */
|
|
282
|
+
manageUrl: (subscriptionId: string) =>
|
|
283
|
+
this.#post<ManageUrl>(`/v1/subscriptions/${id(subscriptionId)}/manage_url`),
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
readonly balance = {
|
|
287
|
+
retrieve: () => this.#get<Balance>('/v1/balance'),
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
readonly payouts = {
|
|
291
|
+
list: listMethod<Payout, ListParams>((params) => this.#get('/v1/payouts', params)),
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** Everything one of your users is entitled to, across web, App Store and Google Play. */
|
|
295
|
+
readonly subscribers = {
|
|
296
|
+
retrieve: (appUserId: string) => this.#get<Subscriber>(`/v1/subscribers/${id(appUserId)}`),
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/** Verify a store purchase with Apple / Google and attach it to your user. */
|
|
300
|
+
readonly receipts = {
|
|
301
|
+
apple: (params: AppleReceiptParams) => this.#post<StoreSubscription>('/v1/receipts/apple', params),
|
|
302
|
+
google: (params: GoogleReceiptParams) => this.#post<StoreSubscription>('/v1/receipts/google', params),
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
readonly storeSubscriptions = {
|
|
306
|
+
list: listMethod<StoreSubscription, StoreSubscriptionListParams>((params) =>
|
|
307
|
+
this.#get('/v1/store_subscriptions', params),
|
|
308
|
+
),
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
readonly entitlements = {
|
|
312
|
+
list: () => this.#get<List<Entitlement>>('/v1/entitlements'),
|
|
313
|
+
}
|
|
314
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
export type MunimBillingErrorType =
|
|
2
|
+
| 'invalid_request'
|
|
3
|
+
| 'authentication'
|
|
4
|
+
| 'not_found'
|
|
5
|
+
| 'conflict'
|
|
6
|
+
| 'processor'
|
|
7
|
+
| 'internal'
|
|
8
|
+
/** The request never got a response (network failure, timeout). */
|
|
9
|
+
| 'connection'
|
|
10
|
+
/** The webhook signature didn't match, or its timestamp is too old. */
|
|
11
|
+
| 'signature_verification'
|
|
12
|
+
|
|
13
|
+
/** Every error the SDK throws. */
|
|
14
|
+
export class MunimBillingError extends Error {
|
|
15
|
+
readonly type: MunimBillingErrorType
|
|
16
|
+
/** HTTP status, or `null` when there was no response. */
|
|
17
|
+
readonly status: number | null
|
|
18
|
+
/** The request field the error is about, when the API names one. */
|
|
19
|
+
readonly param: string | null
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
message: string,
|
|
23
|
+
options: {
|
|
24
|
+
type: MunimBillingErrorType
|
|
25
|
+
status?: number | null
|
|
26
|
+
param?: string | null
|
|
27
|
+
cause?: unknown
|
|
28
|
+
}
|
|
29
|
+
) {
|
|
30
|
+
super(message)
|
|
31
|
+
this.name = 'MunimBillingError'
|
|
32
|
+
this.type = options.type
|
|
33
|
+
this.status = options.status ?? null
|
|
34
|
+
this.param = options.param ?? null
|
|
35
|
+
if (options.cause !== undefined) {
|
|
36
|
+
;(this as { cause?: unknown }).cause = options.cause
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const KNOWN_TYPES = new Set<MunimBillingErrorType>([
|
|
42
|
+
'invalid_request',
|
|
43
|
+
'authentication',
|
|
44
|
+
'not_found',
|
|
45
|
+
'conflict',
|
|
46
|
+
'processor',
|
|
47
|
+
'internal',
|
|
48
|
+
])
|
|
49
|
+
|
|
50
|
+
function typeForStatus(status: number): MunimBillingErrorType {
|
|
51
|
+
if (status === 401 || status === 403) return 'authentication'
|
|
52
|
+
if (status === 404) return 'not_found'
|
|
53
|
+
if (status === 409) return 'conflict'
|
|
54
|
+
if (status === 402 || status === 502) return 'processor'
|
|
55
|
+
if (status >= 500) return 'internal'
|
|
56
|
+
return 'invalid_request'
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Builds the error for a non-2xx response from its parsed body (if any). */
|
|
60
|
+
export function errorFromResponse(status: number, body: unknown): MunimBillingError {
|
|
61
|
+
const error =
|
|
62
|
+
body && typeof body === 'object' && 'error' in body
|
|
63
|
+
? (body as { error?: { type?: string; message?: string; param?: string } }).error
|
|
64
|
+
: undefined
|
|
65
|
+
const type =
|
|
66
|
+
error?.type && KNOWN_TYPES.has(error.type as MunimBillingErrorType)
|
|
67
|
+
? (error.type as MunimBillingErrorType)
|
|
68
|
+
: typeForStatus(status)
|
|
69
|
+
return new MunimBillingError(error?.message || `Munim Billing request failed with status ${status}`, {
|
|
70
|
+
type,
|
|
71
|
+
status,
|
|
72
|
+
param: error?.param ?? null,
|
|
73
|
+
})
|
|
74
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
export {
|
|
2
|
+
MunimBilling,
|
|
3
|
+
baseUrlForKey,
|
|
4
|
+
modeForKey,
|
|
5
|
+
paginate,
|
|
6
|
+
LIVE_BASE_URL,
|
|
7
|
+
TEST_BASE_URL,
|
|
8
|
+
} from './client.js'
|
|
9
|
+
export type { ListMethod, MunimBillingOptions } from './client.js'
|
|
10
|
+
export { MunimBillingError, errorFromResponse } from './errors.js'
|
|
11
|
+
export type { MunimBillingErrorType } from './errors.js'
|
|
12
|
+
export {
|
|
13
|
+
verifyWebhook,
|
|
14
|
+
signWebhookPayload,
|
|
15
|
+
computeSignature,
|
|
16
|
+
parseSignatureHeader,
|
|
17
|
+
timingSafeEqual,
|
|
18
|
+
webhooks,
|
|
19
|
+
SIGNATURE_HEADER,
|
|
20
|
+
EVENT_ID_HEADER,
|
|
21
|
+
DEFAULT_TOLERANCE_SECONDS,
|
|
22
|
+
} from './webhooks.js'
|
|
23
|
+
export type { VerifyWebhookOptions } from './webhooks.js'
|
|
24
|
+
export { EVENT_TYPES } from './types.js'
|
|
25
|
+
export type * from './types.js'
|
|
26
|
+
export { VERSION } from './version.js'
|