munim-billing 0.1.0 → 0.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/LICENSE +42 -201
- package/README.md +8 -27
- package/lib/cjs/index.js +2 -28
- package/lib/cjs/react-native.js +2 -118
- package/lib/cjs/web.js +2 -157
- package/lib/esm/chunks/57OHO4KT.js +2 -0
- package/lib/esm/client.d.ts +0 -1
- package/lib/esm/errors.d.ts +0 -1
- package/lib/esm/index.d.ts +0 -1
- package/lib/esm/index.js +2 -6
- package/lib/esm/react-native.d.ts +0 -1
- package/lib/esm/react-native.js +2 -114
- package/lib/esm/types.d.ts +5 -1
- package/lib/esm/version.d.ts +1 -2
- package/lib/esm/web.d.ts +0 -1
- package/lib/esm/web.js +2 -152
- package/lib/esm/webhooks.d.ts +0 -1
- package/package.json +11 -16
- package/lib/cjs/client.js +0 -233
- package/lib/cjs/client.js.map +0 -1
- package/lib/cjs/errors.js +0 -55
- package/lib/cjs/errors.js.map +0 -1
- package/lib/cjs/index.js.map +0 -1
- package/lib/cjs/react-native.js.map +0 -1
- package/lib/cjs/types.js +0 -21
- package/lib/cjs/types.js.map +0 -1
- package/lib/cjs/version.js +0 -6
- package/lib/cjs/version.js.map +0 -1
- package/lib/cjs/web.js.map +0 -1
- package/lib/cjs/webhooks.js +0 -137
- package/lib/cjs/webhooks.js.map +0 -1
- package/lib/esm/client.d.ts.map +0 -1
- package/lib/esm/client.js +0 -226
- package/lib/esm/client.js.map +0 -1
- package/lib/esm/errors.d.ts.map +0 -1
- package/lib/esm/errors.js +0 -50
- package/lib/esm/errors.js.map +0 -1
- package/lib/esm/index.d.ts.map +0 -1
- package/lib/esm/index.js.map +0 -1
- package/lib/esm/react-native.d.ts.map +0 -1
- package/lib/esm/react-native.js.map +0 -1
- package/lib/esm/types.d.ts.map +0 -1
- package/lib/esm/types.js +0 -18
- package/lib/esm/types.js.map +0 -1
- package/lib/esm/version.d.ts.map +0 -1
- package/lib/esm/version.js +0 -3
- package/lib/esm/version.js.map +0 -1
- package/lib/esm/web.d.ts.map +0 -1
- package/lib/esm/web.js.map +0 -1
- package/lib/esm/webhooks.d.ts.map +0 -1
- package/lib/esm/webhooks.js +0 -129
- package/lib/esm/webhooks.js.map +0 -1
- package/src/client.ts +0 -314
- package/src/errors.ts +0 -74
- package/src/index.ts +0 -26
- package/src/react-native.ts +0 -154
- package/src/types.ts +0 -360
- package/src/version.ts +0 -2
- package/src/web.ts +0 -182
- package/src/webhooks.ts +0 -169
package/src/client.ts
DELETED
|
@@ -1,314 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,74 +0,0 @@
|
|
|
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
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
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'
|
package/src/react-native.ts
DELETED
|
@@ -1,154 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* munim-billing/react-native: open a Munim checkout from a React Native or
|
|
3
|
-
* Expo app.
|
|
4
|
-
*
|
|
5
|
-
* The checkout opens in an in-app sheet (ASWebAuthenticationSession on iOS,
|
|
6
|
-
* a Custom Tab on Android) through `expo-web-browser`, the same kind of
|
|
7
|
-
* sheet munim-venmo uses. The sheet closes when the checkout redirects to
|
|
8
|
-
* your app's scheme, so create the checkout **on your server** with
|
|
9
|
-
* `success_url` and `cancel_url` set to that scheme:
|
|
10
|
-
*
|
|
11
|
-
* success_url: 'myapp://billing/done'
|
|
12
|
-
* cancel_url: 'myapp://billing/canceled'
|
|
13
|
-
*
|
|
14
|
-
* Never ship your secret key in an app.
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
export type CheckoutReturn = {
|
|
18
|
-
status: 'completed' | 'canceled'
|
|
19
|
-
checkoutId?: string
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
export type OpenCheckoutResult =
|
|
23
|
-
| { status: 'completed'; checkoutId?: string; url: string }
|
|
24
|
-
| { status: 'canceled'; checkoutId?: string; url?: string }
|
|
25
|
-
/** No in-app sheet was available, so the checkout opened in the browser. Watch for your deep link. */
|
|
26
|
-
| { status: 'opened' }
|
|
27
|
-
|
|
28
|
-
/** The parts of `expo-web-browser` this uses. */
|
|
29
|
-
export type WebBrowserLike = {
|
|
30
|
-
openAuthSessionAsync: (
|
|
31
|
-
url: string,
|
|
32
|
-
redirectUrl?: string | null,
|
|
33
|
-
options?: Record<string, unknown>
|
|
34
|
-
) => Promise<{ type: string; url?: string }>
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export type OpenCheckoutOptions = {
|
|
38
|
-
/**
|
|
39
|
-
* The URL prefix the sheet watches for, usually your scheme or the
|
|
40
|
-
* checkout's `success_url`, e.g. `'myapp://billing'`. When the checkout
|
|
41
|
-
* navigates there, the sheet closes.
|
|
42
|
-
*/
|
|
43
|
-
returnUrl: string
|
|
44
|
-
/**
|
|
45
|
-
* `expo-web-browser`, if you'd rather pass it in than have it found
|
|
46
|
-
* automatically: `import * as WebBrowser from 'expo-web-browser'`.
|
|
47
|
-
*/
|
|
48
|
-
webBrowser?: WebBrowserLike
|
|
49
|
-
/** iOS: an ephemeral session that doesn't share Safari's cookies. Default `false`. */
|
|
50
|
-
preferEphemeralSession?: boolean
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
declare const require: (name: string) => unknown
|
|
54
|
-
|
|
55
|
-
function loadWebBrowser(): WebBrowserLike | null {
|
|
56
|
-
try {
|
|
57
|
-
// Optional peer dependency, looked up only when it's needed.
|
|
58
|
-
const mod = (typeof require === 'function' ? require('expo-web-browser') : undefined) as
|
|
59
|
-
| Partial<WebBrowserLike>
|
|
60
|
-
| undefined
|
|
61
|
-
return mod && typeof mod.openAuthSessionAsync === 'function' ? (mod as WebBrowserLike) : null
|
|
62
|
-
} catch {
|
|
63
|
-
return null
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
function loadLinking(): { openURL: (url: string) => Promise<unknown> } | null {
|
|
68
|
-
try {
|
|
69
|
-
const mod = (typeof require === 'function' ? require('react-native') : undefined) as
|
|
70
|
-
| { Linking?: { openURL: (url: string) => Promise<unknown> } }
|
|
71
|
-
| undefined
|
|
72
|
-
return mod?.Linking ?? null
|
|
73
|
-
} catch {
|
|
74
|
-
return null
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
/** Reads a URL's query (and fragment) without `URL.searchParams`, which React Native doesn't implement. */
|
|
79
|
-
function queryParams(url: string): Map<string, string> {
|
|
80
|
-
const params = new Map<string, string>()
|
|
81
|
-
const start = url.indexOf('?')
|
|
82
|
-
const hash = url.indexOf('#')
|
|
83
|
-
const parts: string[] = []
|
|
84
|
-
if (start >= 0) parts.push(url.slice(start + 1, hash > start ? hash : undefined))
|
|
85
|
-
if (hash >= 0) parts.push(url.slice(hash + 1))
|
|
86
|
-
for (const part of parts) {
|
|
87
|
-
for (const pair of part.split('&')) {
|
|
88
|
-
if (!pair) continue
|
|
89
|
-
const eq = pair.indexOf('=')
|
|
90
|
-
const rawKey = eq >= 0 ? pair.slice(0, eq) : pair
|
|
91
|
-
const rawValue = eq >= 0 ? pair.slice(eq + 1) : ''
|
|
92
|
-
try {
|
|
93
|
-
const key = decodeURIComponent(rawKey.replace(/\+/g, ' ')).toLowerCase()
|
|
94
|
-
if (!params.has(key)) params.set(key, decodeURIComponent(rawValue.replace(/\+/g, ' ')))
|
|
95
|
-
} catch {
|
|
96
|
-
// A malformed escape: skip that pair.
|
|
97
|
-
}
|
|
98
|
-
}
|
|
99
|
-
}
|
|
100
|
-
return params
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Reads the URL the checkout returned to. `checkout_id` means it was paid;
|
|
105
|
-
* `canceled=true` (or no `checkout_id`) means it wasn't.
|
|
106
|
-
*/
|
|
107
|
-
export function parseCheckoutReturnUrl(url: string): CheckoutReturn {
|
|
108
|
-
const params = queryParams(url)
|
|
109
|
-
const checkoutId = params.get('checkout_id') || undefined
|
|
110
|
-
const canceled = params.get('canceled') ?? params.get('cancelled')
|
|
111
|
-
if (canceled === 'true' || canceled === '1' || !checkoutId) {
|
|
112
|
-
return checkoutId ? { status: 'canceled', checkoutId } : { status: 'canceled' }
|
|
113
|
-
}
|
|
114
|
-
return { status: 'completed', checkoutId }
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Opens a checkout `url` (from `munim.checkouts.create` on your server) in an
|
|
119
|
-
* in-app sheet and resolves when the customer comes back.
|
|
120
|
-
*
|
|
121
|
-
* - `completed`: the checkout redirected to your `success_url`. Confirm on
|
|
122
|
-
* your server (the `checkout.completed` webhook, or
|
|
123
|
-
* `munim.checkouts.retrieve(checkoutId)`) before granting anything.
|
|
124
|
-
* - `canceled`: the customer closed the sheet or hit cancel.
|
|
125
|
-
* - `opened`: `expo-web-browser` isn't installed, so the checkout opened in
|
|
126
|
-
* the browser; the result arrives later as a deep link to your app.
|
|
127
|
-
*/
|
|
128
|
-
export async function openCheckout(url: string, options: OpenCheckoutOptions): Promise<OpenCheckoutResult> {
|
|
129
|
-
if (!url) throw new Error('munim-billing: openCheckout needs the checkout url.')
|
|
130
|
-
if (!options?.returnUrl || !/^[a-z][a-z0-9+.-]*:/i.test(options.returnUrl)) {
|
|
131
|
-
throw new Error("munim-billing: openCheckout needs a returnUrl like 'myapp://billing'.")
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
const browser = options.webBrowser ?? loadWebBrowser()
|
|
135
|
-
if (browser) {
|
|
136
|
-
const result = await browser.openAuthSessionAsync(url, options.returnUrl, {
|
|
137
|
-
preferEphemeralSession: options.preferEphemeralSession ?? false,
|
|
138
|
-
})
|
|
139
|
-
if (result.type === 'success' && result.url) {
|
|
140
|
-
const parsed = parseCheckoutReturnUrl(result.url)
|
|
141
|
-
return parsed.status === 'completed'
|
|
142
|
-
? { status: 'completed', checkoutId: parsed.checkoutId, url: result.url }
|
|
143
|
-
: { status: 'canceled', checkoutId: parsed.checkoutId, url: result.url }
|
|
144
|
-
}
|
|
145
|
-
return { status: 'canceled' }
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
const linking = loadLinking()
|
|
149
|
-
if (!linking) {
|
|
150
|
-
throw new Error('munim-billing: install expo-web-browser (or run inside React Native) to open a checkout.')
|
|
151
|
-
}
|
|
152
|
-
await linking.openURL(url)
|
|
153
|
-
return { status: 'opened' }
|
|
154
|
-
}
|