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
package/README.md
CHANGED
|
@@ -1,3 +1,551 @@
|
|
|
1
|
-
|
|
1
|
+
<!-- Banner Image -->
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://github.com/munimtechnologies/munim-billing">
|
|
5
|
+
<h1 align="center">munim-billing</h1>
|
|
6
|
+
</a>
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
<p align="center">
|
|
10
|
+
<a aria-label="Package version" href="https://www.npmjs.com/package/munim-billing" target="_blank">
|
|
11
|
+
<img alt="Package version" src="https://img.shields.io/npm/v/munim-billing.svg?style=flat-square&label=Version&labelColor=000000&color=0066CC" />
|
|
12
|
+
</a>
|
|
13
|
+
<a aria-label="Package is free to use" href="https://github.com/munimtechnologies/munim-billing/blob/main/LICENSE" target="_blank">
|
|
14
|
+
<img alt="License: Apache-2.0" src="https://img.shields.io/badge/License-Apache%202.0-success.svg?style=flat-square&color=33CC12" target="_blank" />
|
|
15
|
+
</a>
|
|
16
|
+
<a aria-label="package downloads" href="https://www.npmtrends.com/munim-billing" target="_blank">
|
|
17
|
+
<img alt="Downloads" src="https://img.shields.io/npm/dm/munim-billing.svg?style=flat-square&labelColor=gray&color=33CC12&label=Downloads" />
|
|
18
|
+
</a>
|
|
19
|
+
<a aria-label="total package downloads" href="https://www.npmjs.com/package/munim-billing" target="_blank">
|
|
20
|
+
<img alt="Total Downloads" src="https://img.shields.io/npm/dt/munim-billing.svg?style=flat-square&labelColor=gray&color=0066CC&label=Total%20Downloads" />
|
|
21
|
+
</a>
|
|
22
|
+
</p>
|
|
23
|
+
|
|
24
|
+
<p align="center">
|
|
25
|
+
<img alt="Stripe" src="https://img.shields.io/badge/Stripe-Cards%20%2B%20Apple%20Pay%20%2B%20Google%20Pay-635BFF?style=flat-square&logo=stripe&logoColor=white" />
|
|
26
|
+
<img alt="PayPal" src="https://img.shields.io/badge/PayPal-PayPal%20%2B%20Venmo-003087?style=flat-square&logo=paypal&logoColor=white" />
|
|
27
|
+
<img alt="Merchant of record" src="https://img.shields.io/badge/Munim%2C%20Inc.-Merchant%20of%20record-000000?style=flat-square" />
|
|
28
|
+
<img alt="TypeScript" src="https://img.shields.io/badge/TypeScript-Zero%20dependencies-3178C6?style=flat-square&logo=typescript&logoColor=white" />
|
|
29
|
+
</p>
|
|
30
|
+
|
|
31
|
+
<p align="center">
|
|
32
|
+
<a aria-label="try with expo" href="https://docs.expo.dev/"><b>Works with Expo</b></a>
|
|
33
|
+
 • 
|
|
34
|
+
<a aria-label="dashboard" href="https://munimtech.com/billing/dashboard">Open the Dashboard</a>
|
|
35
|
+
 • 
|
|
36
|
+
<a aria-label="documentation" href="https://github.com/munimtechnologies/munim-billing#readme">Read the Documentation</a>
|
|
37
|
+
 • 
|
|
38
|
+
<a aria-label="report issues" href="https://github.com/munimtechnologies/munim-billing/issues">Report Issues</a>
|
|
39
|
+
</p>
|
|
40
|
+
|
|
41
|
+
<h6 align="center">Follow Munim Technologies</h6>
|
|
42
|
+
<p align="center">
|
|
43
|
+
<a aria-label="Follow Munim Technologies on GitHub" href="https://github.com/munimtechnologies" target="_blank">
|
|
44
|
+
<img alt="Munim Technologies on GitHub" src="https://img.shields.io/badge/GitHub-222222?style=for-the-badge&logo=github&logoColor=white" target="_blank" />
|
|
45
|
+
</a>
|
|
46
|
+
<a aria-label="Follow Munim Technologies on LinkedIn" href="https://linkedin.com/in/sheehanmunim" target="_blank">
|
|
47
|
+
<img alt="Munim Technologies on LinkedIn" src="https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white" target="_blank" />
|
|
48
|
+
</a>
|
|
49
|
+
<a aria-label="Visit Munim Technologies Website" href="https://munimtech.com" target="_blank">
|
|
50
|
+
<img alt="Munim Technologies Website" src="https://img.shields.io/badge/Website-0066CC?style=for-the-badge&logo=globe&logoColor=white" target="_blank" />
|
|
51
|
+
</a>
|
|
52
|
+
</p>
|
|
53
|
+
|
|
54
|
+
## Introduction
|
|
55
|
+
|
|
56
|
+
**munim-billing** is the SDK for **Munim Billing**, where Munim, Inc. is your merchant of record. Your customers pay Munim with a card, Apple Pay, Google Pay, Link, PayPal or Venmo. Munim takes the payment, keeps its fee, and pays you the rest to your bank account or your PayPal.
|
|
57
|
+
|
|
58
|
+
One package covers every side of it: a **server client** for products, prices, checkouts, subscriptions, refunds and payouts; **webhook verification**; and **checkout helpers** for the web (an overlay or a redirect) and for **React Native / Expo** (an in-app sheet).
|
|
59
|
+
|
|
60
|
+
**Fully compatible with Expo!** The React Native helper uses `expo-web-browser`, so it works in Expo Go, development builds and bare apps, with no native code of its own.
|
|
61
|
+
|
|
62
|
+
**Zero dependencies.** It's `fetch` and Web Crypto, so it runs in Node, Deno, Bun, Cloudflare Workers, Vercel Edge, Convex actions, browsers and React Native.
|
|
63
|
+
|
|
64
|
+
See your sales, customers, subscriptions, API keys, webhooks and payouts in the [Munim Billing dashboard](https://munimtech.com/billing/dashboard).
|
|
65
|
+
|
|
66
|
+
## Table of contents
|
|
67
|
+
|
|
68
|
+
- [📚 Documentation](#-documentation)
|
|
69
|
+
- [🚀 Features](#-features)
|
|
70
|
+
- [How It Works](#how-it-works)
|
|
71
|
+
- [Platform Support Matrix](#platform-support-matrix)
|
|
72
|
+
- [📦 Installation](#-installation)
|
|
73
|
+
- [⚡ Quick Start](#-quick-start)
|
|
74
|
+
- [🔧 API Reference](#-api-reference)
|
|
75
|
+
- [🪝 Webhooks](#-webhooks)
|
|
76
|
+
- [📖 Usage Examples](#-usage-examples)
|
|
77
|
+
- [🔍 Troubleshooting](#-troubleshooting)
|
|
78
|
+
- [👏 Contributing](#-contributing)
|
|
79
|
+
- [📄 License](#-license)
|
|
80
|
+
|
|
81
|
+
## 📚 Documentation
|
|
82
|
+
|
|
83
|
+
<p>Learn how to sell with Munim Billing <a aria-label="documentation" href="https://github.com/munimtechnologies/munim-billing#readme">in our documentation!</a></p>
|
|
84
|
+
|
|
85
|
+
- [Getting Started](#-installation)
|
|
86
|
+
- [API Reference](#-api-reference)
|
|
87
|
+
- [Webhooks](#-webhooks)
|
|
88
|
+
- [Troubleshooting](#-troubleshooting)
|
|
89
|
+
|
|
90
|
+
## 🚀 Features
|
|
91
|
+
|
|
92
|
+
### Payments
|
|
93
|
+
|
|
94
|
+
- 💳 **Every way to pay**: cards, Apple Pay, Google Pay and Link through Stripe; PayPal and Venmo through PayPal, all on one hosted checkout
|
|
95
|
+
- 🔁 **One-time and recurring**: prices can be one-time or bill every day, week, month or year, with free trials
|
|
96
|
+
- 🧾 **Munim is the merchant of record**: the customer pays Munim, Inc., so you don't need your own Stripe or PayPal account
|
|
97
|
+
- ↩️ **Refunds and cancellations**: full or partial refunds, cancel now or at the end of the paid period, and a hosted page where customers manage their own subscription
|
|
98
|
+
|
|
99
|
+
### Getting paid
|
|
100
|
+
|
|
101
|
+
- 🏦 **Payouts to your bank** through Stripe Connect (Stripe checks identity and holds the bank details), or **to your PayPal** through PayPal Payouts
|
|
102
|
+
- 📊 **Your balance at a glance**: `balance.retrieve()` shows what's available, what's still held and what's been paid out
|
|
103
|
+
|
|
104
|
+
### Integration
|
|
105
|
+
|
|
106
|
+
- 🪟 **Web overlay**: `openCheckout(url)` shows the checkout over your page and tells you when it's paid
|
|
107
|
+
- 📱 **React Native / Expo**: `openCheckout(url, { returnUrl })` opens it in an in-app sheet (ASWebAuthenticationSession / Custom Tabs)
|
|
108
|
+
- 🪝 **Signed webhooks**: `verifyWebhook` checks the HMAC-SHA256 signature and timestamp, then hands back a typed event
|
|
109
|
+
- 🔄 **Auto-pagination**: `for await (const txn of munim.transactions.list.all())`
|
|
110
|
+
- 🛡️ **Secret key safety**: the server client refuses to start in a browser or an app
|
|
111
|
+
- 🎯 **TypeScript Support**: every object, request and event is typed
|
|
112
|
+
- 📦 **No dependencies**: just `fetch` and Web Crypto; ESM and CommonJS builds
|
|
113
|
+
|
|
114
|
+
## How It Works
|
|
115
|
+
|
|
116
|
+
Munim Billing works like Paddle: **Munim, Inc. sells to your customer on your behalf** (it's the merchant of record), then pays you.
|
|
117
|
+
|
|
118
|
+
```
|
|
119
|
+
Customer ──pays $10.00──▶ Munim, Inc. (merchant of record)
|
|
120
|
+
│ Stripe (cards, wallets) or PayPal (PayPal, Venmo)
|
|
121
|
+
│
|
|
122
|
+
├── Munim fee: 5% + 50¢ = $1.00 (covers Stripe/PayPal processing)
|
|
123
|
+
│
|
|
124
|
+
└── Your earnings: $9.00 ──▶ your balance
|
|
125
|
+
│ held 7 days, then available
|
|
126
|
+
▼
|
|
127
|
+
Payout ──▶ your bank (Stripe Connect)
|
|
128
|
+
└─▶ your PayPal (PayPal Payouts)
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
1. **Your server** creates a checkout with your secret key: `munim.checkouts.create({ price_id })`.
|
|
132
|
+
2. **The customer** pays on Munim's hosted checkout page, which you open with a redirect, the web overlay, or the React Native sheet.
|
|
133
|
+
3. **Munim** records a transaction (and a subscription, for recurring prices), takes its fee, and sends your webhook `transaction.completed`.
|
|
134
|
+
4. **Your earnings** sit in your balance for the hold period, then pay out weekly, monthly, or when you ask, to the bank or PayPal you set up in the [dashboard](https://munimtech.com/billing/dashboard).
|
|
135
|
+
|
|
136
|
+
| | Default |
|
|
137
|
+
| --- | --- |
|
|
138
|
+
| Munim fee | 5% + 50¢ per sale, which includes Stripe's and PayPal's processing fees |
|
|
139
|
+
| Refunds | Take back the same share of your earnings and of Munim's fee |
|
|
140
|
+
| Disputes (chargebacks) | Take back the sale's earnings plus a $15.00 dispute fee; returned if you win |
|
|
141
|
+
| Hold | 7 days before earnings are available |
|
|
142
|
+
| Minimum payout | $10.00 |
|
|
143
|
+
| Currency | USD |
|
|
144
|
+
|
|
145
|
+
## Platform Support Matrix
|
|
146
|
+
|
|
147
|
+
| Entry point | Node / edge / Convex | Browser | React Native / Expo | Notes |
|
|
148
|
+
| --- | --- | --- | --- | --- |
|
|
149
|
+
| `munim-billing` (`MunimBilling`) | ✅ | ➖ | ➖ | Uses your secret key, so server only. |
|
|
150
|
+
| `verifyWebhook` and friends | ✅ | ✅ | ➖ | Needs Web Crypto (`crypto.subtle`): Node 20+, or Node 18 with `--experimental-global-webcrypto`. |
|
|
151
|
+
| `munim-billing/web` | ➖ | ✅ | ➖ | Overlay iframe or redirect. |
|
|
152
|
+
| `munim-billing/react-native` | ➖ | ➖ | ✅ | In-app sheet with `expo-web-browser`; `Linking.openURL` without it. |
|
|
153
|
+
|
|
154
|
+
✅ supported · ➖ not for this platform
|
|
155
|
+
|
|
156
|
+
**Environments**: keys starting `mb_test_sk_` use the sandbox (`https://billing-sandbox-api.munimtech.com`: Stripe test mode, PayPal sandbox, nothing is really charged). Keys starting `mb_live_sk_` use `https://billing-api.munimtech.com`. Test and live data never mix.
|
|
157
|
+
|
|
158
|
+
## 📦 Installation
|
|
159
|
+
|
|
160
|
+
### Server, web, or bare React Native
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
npm install munim-billing
|
|
164
|
+
# or
|
|
165
|
+
yarn add munim-billing
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### Expo
|
|
169
|
+
|
|
170
|
+
```bash
|
|
171
|
+
npx expo install munim-billing expo-web-browser
|
|
172
|
+
```
|
|
173
|
+
|
|
174
|
+
`expo-web-browser` is an optional peer dependency. With it, the checkout opens in an in-app sheet; without it, it opens in the browser.
|
|
175
|
+
|
|
176
|
+
### Keys
|
|
177
|
+
|
|
178
|
+
Sign in to the [dashboard](https://munimtech.com/billing/dashboard), create an API key under **Developers → API keys**, and keep it on your server:
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
MUNIM_BILLING_SECRET_KEY=mb_test_sk_...
|
|
182
|
+
```
|
|
183
|
+
|
|
184
|
+
## ⚡ Quick Start
|
|
185
|
+
|
|
186
|
+
### 1. Make something to sell (once)
|
|
187
|
+
|
|
188
|
+
You can do this in the dashboard, or with the API:
|
|
189
|
+
|
|
190
|
+
```typescript
|
|
191
|
+
import { MunimBilling } from 'munim-billing'
|
|
192
|
+
|
|
193
|
+
const munim = new MunimBilling(process.env.MUNIM_BILLING_SECRET_KEY!)
|
|
194
|
+
|
|
195
|
+
const product = await munim.products.create({ name: 'Pro' })
|
|
196
|
+
const monthly = await munim.prices.create({
|
|
197
|
+
product_id: product.id,
|
|
198
|
+
unit_amount: 999, // $9.99
|
|
199
|
+
currency: 'usd',
|
|
200
|
+
type: 'recurring',
|
|
201
|
+
interval: 'month',
|
|
202
|
+
trial_days: 7,
|
|
203
|
+
})
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
### 2. Create a checkout (on your server)
|
|
207
|
+
|
|
208
|
+
```typescript
|
|
209
|
+
// e.g. POST /api/checkout
|
|
210
|
+
const checkout = await munim.checkouts.create({
|
|
211
|
+
price_id: monthly.id,
|
|
212
|
+
customer_email: user.email,
|
|
213
|
+
success_url: 'https://example.com/billing/done', // or 'myapp://billing/done' for an app
|
|
214
|
+
cancel_url: 'https://example.com/pricing',
|
|
215
|
+
metadata: { user_id: user.id },
|
|
216
|
+
})
|
|
217
|
+
return Response.json({ url: checkout.url })
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
### 3. Open it
|
|
221
|
+
|
|
222
|
+
**Web**
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
import { openCheckout } from 'munim-billing/web'
|
|
226
|
+
|
|
227
|
+
const { url } = await fetch('/api/checkout', { method: 'POST' }).then((r) => r.json())
|
|
228
|
+
openCheckout(url, {
|
|
229
|
+
onComplete: ({ checkoutId }) => showThanks(checkoutId),
|
|
230
|
+
onClose: () => console.log('closed'),
|
|
231
|
+
})
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
**React Native / Expo**
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
import { openCheckout } from 'munim-billing/react-native'
|
|
238
|
+
|
|
239
|
+
// Your server made the checkout with success_url 'myapp://billing/done'
|
|
240
|
+
// and cancel_url 'myapp://billing/canceled'.
|
|
241
|
+
const { url } = await api.createCheckout()
|
|
242
|
+
const result = await openCheckout(url, { returnUrl: 'myapp://billing' })
|
|
243
|
+
if (result.status === 'completed') {
|
|
244
|
+
await refreshEntitlements() // your server already heard about it by webhook
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
### 4. Grant access from the webhook
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
import { verifyWebhook } from 'munim-billing'
|
|
252
|
+
|
|
253
|
+
export async function POST(request: Request) {
|
|
254
|
+
const event = await verifyWebhook(
|
|
255
|
+
await request.text(),
|
|
256
|
+
request.headers.get('Munim-Signature'),
|
|
257
|
+
process.env.MUNIM_BILLING_WEBHOOK_SECRET!
|
|
258
|
+
)
|
|
259
|
+
switch (event.type) {
|
|
260
|
+
case 'transaction.completed':
|
|
261
|
+
await grantPro(event.data.object.metadata.user_id)
|
|
262
|
+
break
|
|
263
|
+
case 'subscription.canceled':
|
|
264
|
+
await revokePro(event.data.object.metadata.user_id)
|
|
265
|
+
break
|
|
266
|
+
}
|
|
267
|
+
return new Response('ok')
|
|
268
|
+
}
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
## 🔧 API Reference
|
|
272
|
+
|
|
273
|
+
### `new MunimBilling(secretKey, options?)`
|
|
274
|
+
|
|
275
|
+
| Option | Type | Description |
|
|
276
|
+
| --- | --- | --- |
|
|
277
|
+
| `baseUrl` | `string` | Overrides the API base picked from the key (for example a `https://<name>.convex.site` deployment). |
|
|
278
|
+
| `fetch` | `typeof fetch` | A `fetch` to use instead of the global one. |
|
|
279
|
+
| `timeoutMs` | `number` | Per-request timeout. Default `30000`. |
|
|
280
|
+
| `dangerouslyAllowBrowser` | `boolean` | Lets the client start in a browser or app. Don't, unless it's a local tool. |
|
|
281
|
+
|
|
282
|
+
Properties: `mode` (`'test' \| 'live' \| null`), `baseUrl`, `webhooks`.
|
|
283
|
+
|
|
284
|
+
### Resources
|
|
285
|
+
|
|
286
|
+
Every method returns a `Promise`. Amounts are cents; timestamps are Unix milliseconds.
|
|
287
|
+
|
|
288
|
+
| Method | API |
|
|
289
|
+
| --- | --- |
|
|
290
|
+
| `products.create(params)` | `POST /v1/products` |
|
|
291
|
+
| `products.list(params?)` / `.list.all(params?)` | `GET /v1/products` |
|
|
292
|
+
| `products.retrieve(id)` | `GET /v1/products/:id` |
|
|
293
|
+
| `products.update(id, params)` | `POST /v1/products/:id` |
|
|
294
|
+
| `prices.create(params)` | `POST /v1/prices` |
|
|
295
|
+
| `prices.list({ product_id? })` / `.list.all()` | `GET /v1/prices` |
|
|
296
|
+
| `prices.retrieve(id)` | `GET /v1/prices/:id` |
|
|
297
|
+
| `prices.update(id, params)` | `POST /v1/prices/:id`. The amount can't change; make a new price. |
|
|
298
|
+
| `checkouts.create(params)` | `POST /v1/checkouts` |
|
|
299
|
+
| `checkouts.retrieve(id)` | `GET /v1/checkouts/:id` |
|
|
300
|
+
| `customers.list({ email? })` / `.list.all()` | `GET /v1/customers` |
|
|
301
|
+
| `customers.retrieve(id)` | `GET /v1/customers/:id` |
|
|
302
|
+
| `transactions.list({ customer_id?, subscription_id? })` / `.list.all()` | `GET /v1/transactions` |
|
|
303
|
+
| `transactions.retrieve(id)` | `GET /v1/transactions/:id` |
|
|
304
|
+
| `transactions.refund(id, { amount? })` | `POST /v1/transactions/:id/refund` (everything not yet refunded by default) |
|
|
305
|
+
| `subscriptions.list({ customer_id?, status? })` / `.list.all()` | `GET /v1/subscriptions` |
|
|
306
|
+
| `subscriptions.retrieve(id)` | `GET /v1/subscriptions/:id` |
|
|
307
|
+
| `subscriptions.cancel(id, { at_period_end? })` | `POST /v1/subscriptions/:id/cancel` (at period end by default) |
|
|
308
|
+
| `subscriptions.manageUrl(id)` | `POST /v1/subscriptions/:id/manage_url` → `{ url, expires_at }` |
|
|
309
|
+
| `balance.retrieve()` | `GET /v1/balance` |
|
|
310
|
+
| `payouts.list(params?)` / `.list.all()` | `GET /v1/payouts` |
|
|
311
|
+
|
|
312
|
+
Lists take `{ limit?, cursor? }` (`limit` 1–100, default 25) and return `{ object: 'list', data, has_more, next_cursor }`, newest first. `list.all(params)` is an async iterator over every item, and `paginate(fetchPage, params)` does the same for any list function.
|
|
313
|
+
|
|
314
|
+
### Checkout params
|
|
315
|
+
|
|
316
|
+
```typescript
|
|
317
|
+
type CheckoutCreateParams = {
|
|
318
|
+
price_id: string
|
|
319
|
+
quantity?: number
|
|
320
|
+
customer_email?: string
|
|
321
|
+
customer_id?: string
|
|
322
|
+
success_url?: string // https:// or your app's scheme; checkout_id is appended
|
|
323
|
+
cancel_url?: string
|
|
324
|
+
metadata?: Record<string, string>
|
|
325
|
+
}
|
|
326
|
+
```
|
|
327
|
+
|
|
328
|
+
Without `success_url` the checkout shows its own "Payment complete" screen.
|
|
329
|
+
|
|
330
|
+
### Errors
|
|
331
|
+
|
|
332
|
+
Every failure throws a `MunimBillingError`:
|
|
333
|
+
|
|
334
|
+
| Property | Type | Description |
|
|
335
|
+
| --- | --- | --- |
|
|
336
|
+
| `type` | `'invalid_request' \| 'authentication' \| 'not_found' \| 'conflict' \| 'processor' \| 'internal' \| 'connection' \| 'signature_verification'` | What went wrong. |
|
|
337
|
+
| `status` | `number \| null` | HTTP status, or `null` when there was no response. |
|
|
338
|
+
| `param` | `string \| null` | The field the error is about, when there is one. |
|
|
339
|
+
| `message` | `string` | A readable explanation. |
|
|
340
|
+
|
|
341
|
+
### Web: `munim-billing/web`
|
|
342
|
+
|
|
343
|
+
#### `openCheckout(url, options?): { close() }`
|
|
344
|
+
|
|
345
|
+
Shows the checkout in a full-screen overlay (an iframe with `allow="payment"`, so Apple Pay and Google Pay work). Options: `onComplete({ checkoutId })`, `onClose()`, `zIndex`. The checkout page tells the overlay what happened with `postMessage` (`{ source: 'munim-billing', type: 'checkout.completed' | 'checkout.closed', checkout_id }`); only messages from the checkout's own origin count. Escape, the × button and a click outside close it.
|
|
346
|
+
|
|
347
|
+
#### `redirectToCheckout(url): void`
|
|
348
|
+
|
|
349
|
+
Sends the whole page to the checkout. After payment it comes back to your `success_url`.
|
|
350
|
+
|
|
351
|
+
#### `isCheckoutMessage(data): boolean`
|
|
352
|
+
|
|
353
|
+
Whether a `postMessage` payload is one of the checkout page's messages, if you embed it yourself.
|
|
354
|
+
|
|
355
|
+
### React Native: `munim-billing/react-native`
|
|
356
|
+
|
|
357
|
+
#### `openCheckout(url, options): Promise<OpenCheckoutResult>`
|
|
358
|
+
|
|
359
|
+
| Option | Type | Description |
|
|
360
|
+
| --- | --- | --- |
|
|
361
|
+
| `returnUrl` | `string` | Required. The prefix the sheet watches for (your scheme, e.g. `'myapp://billing'`). Make the checkout's `success_url` and `cancel_url` start with it. |
|
|
362
|
+
| `webBrowser` | `typeof import('expo-web-browser')` | Pass it in yourself instead of letting the package find it. |
|
|
363
|
+
| `preferEphemeralSession` | `boolean` | iOS: don't share Safari's cookies. Default `false`. |
|
|
364
|
+
|
|
365
|
+
Resolves with one of:
|
|
366
|
+
|
|
367
|
+
- `{ status: 'completed', checkoutId, url }`: the checkout came back to your `success_url`.
|
|
368
|
+
- `{ status: 'canceled', checkoutId?, url? }`: the customer closed the sheet or canceled.
|
|
369
|
+
- `{ status: 'opened' }`: no `expo-web-browser`, so it opened in the browser; the result comes back later as a deep link.
|
|
370
|
+
|
|
371
|
+
#### `parseCheckoutReturnUrl(url): { status: 'completed' | 'canceled', checkoutId? }`
|
|
372
|
+
|
|
373
|
+
Reads a return URL yourself, for example in a deep-link handler. React Native-safe (doesn't need `URL.searchParams`).
|
|
374
|
+
|
|
375
|
+
### Types
|
|
376
|
+
|
|
377
|
+
All object types are exported: `Product`, `Price`, `Checkout`, `Customer`, `Transaction`, `Subscription`, `Balance`, `Payout`, `List<T>`, `Event`, `EventType`, plus each method's params type (`CheckoutCreateParams`, `PriceCreateParams`, …).
|
|
378
|
+
|
|
379
|
+
## 🪝 Webhooks
|
|
380
|
+
|
|
381
|
+
Add an endpoint in the dashboard under **Developers → Webhooks**. You get a secret starting `whsec_`, shown once. Each delivery is a POST of an `Event`:
|
|
382
|
+
|
|
383
|
+
```json
|
|
384
|
+
{
|
|
385
|
+
"id": "evt_…",
|
|
386
|
+
"object": "event",
|
|
387
|
+
"type": "transaction.completed",
|
|
388
|
+
"created_at": 1764460800000,
|
|
389
|
+
"data": { "object": { "id": "txn_…", "object": "transaction", "amount": 999, "fee": 100, "net": 899, "...": "..." } }
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
with headers:
|
|
394
|
+
|
|
395
|
+
```
|
|
396
|
+
Munim-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256(secret, `${t}.${rawBody}`)>
|
|
397
|
+
Munim-Event-Id: evt_…
|
|
398
|
+
```
|
|
399
|
+
|
|
400
|
+
The HMAC key is the whole secret string, `whsec_` included. `verifyWebhook(rawBody, header, secret, { toleranceSeconds = 300 })` checks the signature in constant time, rejects timestamps more than five minutes off, and returns the typed event. Pass the **raw** body, before any JSON parsing. A header with several `v1=` values passes when any one matches.
|
|
401
|
+
|
|
402
|
+
| Event | `data.object` |
|
|
403
|
+
| --- | --- |
|
|
404
|
+
| `checkout.completed` | `Checkout` |
|
|
405
|
+
| `transaction.completed`, `transaction.refunded`, `transaction.disputed` | `Transaction` |
|
|
406
|
+
| `subscription.created`, `subscription.updated`, `subscription.canceled` | `Subscription` |
|
|
407
|
+
| `payout.paid`, `payout.failed` | `Payout` |
|
|
408
|
+
|
|
409
|
+
Reply with a 2xx within 10 seconds. Failed deliveries retry after 1 min, 5 min, 30 min, 2 h, 6 h, 12 h and 24 h. Use `Munim-Event-Id` to ignore repeats.
|
|
410
|
+
|
|
411
|
+
Also exported: `signWebhookPayload(secret, rawBody, timestamp?)` (makes a header, handy in tests), `computeSignature`, `parseSignatureHeader`, `SIGNATURE_HEADER`, `EVENT_ID_HEADER`. `MunimBilling.webhooks.verify` is the same as `verifyWebhook`.
|
|
412
|
+
|
|
413
|
+
## 📖 Usage Examples
|
|
414
|
+
|
|
415
|
+
### Express
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
import express from 'express'
|
|
419
|
+
import { MunimBilling, verifyWebhook } from 'munim-billing'
|
|
420
|
+
|
|
421
|
+
const app = express()
|
|
422
|
+
const munim = new MunimBilling(process.env.MUNIM_BILLING_SECRET_KEY!)
|
|
423
|
+
|
|
424
|
+
app.post('/api/checkout', express.json(), async (req, res) => {
|
|
425
|
+
const checkout = await munim.checkouts.create({
|
|
426
|
+
price_id: req.body.price_id,
|
|
427
|
+
customer_email: req.user.email,
|
|
428
|
+
success_url: 'https://example.com/billing/done',
|
|
429
|
+
metadata: { user_id: req.user.id },
|
|
430
|
+
})
|
|
431
|
+
res.json({ url: checkout.url })
|
|
432
|
+
})
|
|
433
|
+
|
|
434
|
+
// The raw body, not express.json(), so the signature can be checked.
|
|
435
|
+
app.post('/webhooks/munim', express.text({ type: '*/*' }), async (req, res) => {
|
|
436
|
+
try {
|
|
437
|
+
const event = await verifyWebhook(req.body, req.header('Munim-Signature'), process.env.MUNIM_BILLING_WEBHOOK_SECRET!)
|
|
438
|
+
await handle(event)
|
|
439
|
+
res.sendStatus(200)
|
|
440
|
+
} catch {
|
|
441
|
+
res.sendStatus(400)
|
|
442
|
+
}
|
|
443
|
+
})
|
|
444
|
+
```
|
|
445
|
+
|
|
446
|
+
### Convex
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
// convex/billing.ts
|
|
450
|
+
import { action } from './_generated/server'
|
|
451
|
+
import { v } from 'convex/values'
|
|
452
|
+
import { MunimBilling } from 'munim-billing'
|
|
453
|
+
|
|
454
|
+
export const createCheckout = action({
|
|
455
|
+
args: { priceId: v.string() },
|
|
456
|
+
handler: async (ctx, { priceId }) => {
|
|
457
|
+
const user = await ctx.auth.getUserIdentity()
|
|
458
|
+
if (!user) throw new Error('Not signed in')
|
|
459
|
+
const munim = new MunimBilling(process.env.MUNIM_BILLING_SECRET_KEY!)
|
|
460
|
+
const checkout = await munim.checkouts.create({
|
|
461
|
+
price_id: priceId,
|
|
462
|
+
customer_email: user.email,
|
|
463
|
+
success_url: 'myapp://billing/done',
|
|
464
|
+
cancel_url: 'myapp://billing/canceled',
|
|
465
|
+
metadata: { user_id: user.subject },
|
|
466
|
+
})
|
|
467
|
+
return checkout.url
|
|
468
|
+
},
|
|
469
|
+
})
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
### A Buy button in Expo
|
|
473
|
+
|
|
474
|
+
```tsx
|
|
475
|
+
import { Alert, Pressable, Text } from 'react-native'
|
|
476
|
+
import { useAction } from 'convex/react'
|
|
477
|
+
import { openCheckout } from 'munim-billing/react-native'
|
|
478
|
+
import { api } from '../convex/_generated/api'
|
|
479
|
+
|
|
480
|
+
export function BuyButton({ priceId }: { priceId: string }) {
|
|
481
|
+
const createCheckout = useAction(api.billing.createCheckout)
|
|
482
|
+
const buy = async () => {
|
|
483
|
+
const url = await createCheckout({ priceId })
|
|
484
|
+
const result = await openCheckout(url, { returnUrl: 'myapp://billing' })
|
|
485
|
+
if (result.status === 'completed') Alert.alert('Thanks!', 'Your purchase is on its way.')
|
|
486
|
+
}
|
|
487
|
+
return (
|
|
488
|
+
<Pressable onPress={buy}>
|
|
489
|
+
<Text>Buy</Text>
|
|
490
|
+
</Pressable>
|
|
491
|
+
)
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
### Refund and cancel
|
|
496
|
+
|
|
497
|
+
```typescript
|
|
498
|
+
await munim.transactions.refund('txn_123') // everything
|
|
499
|
+
await munim.transactions.refund('txn_123', { amount: 500 }) // $5.00
|
|
500
|
+
await munim.subscriptions.cancel('sub_123') // at the end of the paid period
|
|
501
|
+
await munim.subscriptions.cancel('sub_123', { at_period_end: false }) // right now
|
|
502
|
+
const { url } = await munim.subscriptions.manageUrl('sub_123') // let the customer do it
|
|
503
|
+
```
|
|
504
|
+
|
|
505
|
+
### Every transaction this month
|
|
506
|
+
|
|
507
|
+
```typescript
|
|
508
|
+
let total = 0
|
|
509
|
+
for await (const txn of munim.transactions.list.all({ limit: 100 })) {
|
|
510
|
+
if (txn.created_at < startOfMonth) break // newest first
|
|
511
|
+
total += txn.net
|
|
512
|
+
}
|
|
513
|
+
```
|
|
514
|
+
|
|
515
|
+
## 🔍 Troubleshooting
|
|
516
|
+
|
|
517
|
+
### Common Issues
|
|
518
|
+
|
|
519
|
+
1. **`Munim Billing secret keys start with mb_test_sk_ or mb_live_sk_`**: you passed some other key (maybe a Stripe one). Create a Munim Billing key in the dashboard, or pass `baseUrl` when talking to your own deployment.
|
|
520
|
+
2. **`MunimBilling uses your secret key and must run on your server`**: you created the client in a browser or an app. Create checkouts on your server and only send the `url` to the client.
|
|
521
|
+
3. **`Webhook signature does not match`**: verify the raw request body (not `JSON.stringify(req.body)`), and check you're using that endpoint's `whsec_` secret from the right mode (test and live endpoints have different secrets).
|
|
522
|
+
4. **`Webhook timestamp is outside the tolerance`**: your server's clock is off, or you're replaying an old delivery. Fix the clock or raise `toleranceSeconds`.
|
|
523
|
+
5. **`Web Crypto (crypto.subtle) is not available`**: use Node 20 or newer (or Node 18 with `--experimental-global-webcrypto`).
|
|
524
|
+
6. **Test payments**: with an `mb_test_sk_` key nothing is charged. Use Stripe's test cards (e.g. `4242 4242 4242 4242`) and PayPal sandbox buyers.
|
|
525
|
+
|
|
526
|
+
### React Native and Expo
|
|
527
|
+
|
|
528
|
+
1. **The sheet never closes**: the checkout's `success_url` / `cancel_url` must start with the `returnUrl` you pass to `openCheckout`, and your app must own that scheme (`scheme` in `app.json`).
|
|
529
|
+
2. **It opens in the browser instead of a sheet**: install `expo-web-browser` (`npx expo install expo-web-browser`), or pass it as `webBrowser`.
|
|
530
|
+
3. **Don't trust the return URL alone**: it only says the customer came back. Grant access from the `transaction.completed` webhook, or check `munim.checkouts.retrieve(checkoutId)` on your server.
|
|
531
|
+
|
|
532
|
+
## 👏 Contributing
|
|
533
|
+
|
|
534
|
+
We welcome contributions! Open an issue or a pull request on [GitHub](https://github.com/munimtechnologies/munim-billing).
|
|
535
|
+
|
|
536
|
+
```bash
|
|
537
|
+
npm install
|
|
538
|
+
npm run typecheck
|
|
539
|
+
npm test # Vitest: client requests, pagination, webhooks, web overlay, React Native returns
|
|
540
|
+
npm run build # ESM (lib/esm) + CommonJS (lib/cjs)
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
## 📄 License
|
|
544
|
+
|
|
545
|
+
This project is licensed under the Apache License 2.0 - see the [LICENSE](LICENSE) file for details.
|
|
546
|
+
|
|
547
|
+
---
|
|
548
|
+
|
|
549
|
+
<a href="https://github.com/munimtechnologies/munim-billing">
|
|
550
|
+
<img alt="Enjoying Munim Technologies? Star the repo on GitHub" src="./.github/resources/star-repo.svg" width="50%">
|
|
551
|
+
</a>
|