gembapay 1.4.0 → 1.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +33 -0
- package/README.md +83 -20
- package/package.json +5 -4
- package/src/index.d.ts +164 -24
- package/src/index.js +130 -26
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# Changelog — `gembapay` (npm)
|
|
2
|
+
|
|
3
|
+
## 1.5.0 — 2026-11-30
|
|
4
|
+
|
|
5
|
+
Aligned with the GembaPay API as it runs today.
|
|
6
|
+
|
|
7
|
+
**Added**
|
|
8
|
+
- Subscriptions with an API key: `createPlan()`, `listPlans()`, `subscribe(planToken, …)`,
|
|
9
|
+
`repricePlan()`, `cancelSubscription()`, `changeSubscriptionPlan()` (needs
|
|
10
|
+
`subscriptions:change_plan`, sends an `Idempotency-Key`) and `cancelScheduledPlanChange()`.
|
|
11
|
+
- `GembaPayError.body` — the API's error body (or raw text), e.g. `kycStatus` on a KYC `403`.
|
|
12
|
+
- Types: `Order` (for `getPayment()`), the real `PaymentStatus` and `StatsResponse` shapes,
|
|
13
|
+
`exchangeRate` on `PaymentResponse`, plan / subscribe / plan-change types, and the
|
|
14
|
+
`subscription.plan_changed` / `subscription.plan_change_scheduled` webhook events with their fields.
|
|
15
|
+
|
|
16
|
+
**Changed**
|
|
17
|
+
- `listTransactions()` is deprecated and now rejects at once with code `not_available_with_api_key`:
|
|
18
|
+
the endpoint is dashboard-only and always answered `401` to an API key.
|
|
19
|
+
- Error message: the API's `error` field is used first (then `message`), so messages match the API
|
|
20
|
+
reference (`KYC verification required`, `Domain not allowed`, …).
|
|
21
|
+
- A non-JSON error answer (the per-IP rate limiter sends plain text) becomes a `GembaPayError` with
|
|
22
|
+
the HTTP status and code `rate_limited` (429) or `http_error`, instead of `parse_error`.
|
|
23
|
+
- The "missing API key" error points to merchant-dashboard.gembapay.com.
|
|
24
|
+
- README: real response fields, `exchangeRate` direction, no iframe / no automatic return after
|
|
25
|
+
payment, legacy vs V2 webhook verification, absolute links.
|
|
26
|
+
|
|
27
|
+
## 1.4.0
|
|
28
|
+
|
|
29
|
+
- `verifyWebhookV2()`; `parseWebhook()` / `webhookHandler()` verify Signature-V2 when present
|
|
30
|
+
(`{ requireV2: true }` refuses legacy-only requests).
|
|
31
|
+
- Refunds (`createRefund`, `listRefunds`, `getRefund`) and payment links
|
|
32
|
+
(`createPaymentLink`, `listPaymentLinks`, `getPaymentLink`, `setPaymentLinkStatus`,
|
|
33
|
+
`deletePaymentLink`) on `/api/v1`.
|
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Accept credit cards (via Stripe) and PayPal through a single API. Funds settle d
|
|
|
13
13
|
|
|
14
14
|
- **One API, two payment methods** — Stripe (cards/Apple Pay/Google Pay) and PayPal
|
|
15
15
|
- **Direct settlement** — Payments route straight into your own Stripe or PayPal account
|
|
16
|
-
- **
|
|
16
|
+
- **70 currencies** — Price in any supported currency
|
|
17
17
|
- **Test mode built-in** — Stripe and PayPal sandbox environments for development
|
|
18
18
|
- **TypeScript support** — Full type definitions included
|
|
19
19
|
- **Zero dependencies** — Uses only Node.js built-in modules
|
|
@@ -45,9 +45,14 @@ console.log(payment.paymentUrl);
|
|
|
45
45
|
// → https://payment.gembapay.com/checkout/3f9c1e7a-2b4d-4c8e-9f10-a2b3c4d5e6f7
|
|
46
46
|
|
|
47
47
|
console.log(payment.allowedMethods);
|
|
48
|
-
// → ['stripe', 'paypal']
|
|
48
|
+
// → ['stripe', 'paypal'] (the methods connected and enabled in your dashboard)
|
|
49
49
|
```
|
|
50
50
|
|
|
51
|
+
Before the first call: connect Stripe and/or PayPal in the
|
|
52
|
+
[merchant dashboard](https://merchant-dashboard.gembapay.com) — also for test mode, otherwise the API
|
|
53
|
+
answers `400` with `code: 'NO_PAYMENT_METHOD'`. Test keys work before KYC; live keys need approved KYC
|
|
54
|
+
(`403 KYC verification required`). Use the key on your server only.
|
|
55
|
+
|
|
51
56
|
## Usage
|
|
52
57
|
|
|
53
58
|
### Create Payment
|
|
@@ -60,20 +65,34 @@ const payment = await gembapay.createPayment({
|
|
|
60
65
|
description: 'Premium Plan'
|
|
61
66
|
});
|
|
62
67
|
|
|
63
|
-
//
|
|
64
|
-
//
|
|
68
|
+
// payment → { success, orderId, paymentUrl, amountUsd: '49.99', amountOriginal: 49.99,
|
|
69
|
+
// currencyOriginal: 'USD', exchangeRate: 1, allowedMethods, expiresAt }
|
|
70
|
+
// exchangeRate = units of currencyOriginal per 1 USD (EUR ≈ 0.91); the request expires after 24 h.
|
|
71
|
+
|
|
72
|
+
// Send the customer to payment.paymentUrl as-is (unguessable token, not your orderId) —
|
|
73
|
+
// a redirect or a new tab; the checkout cannot be shown in an iframe.
|
|
74
|
+
// The checkout follows the customer's browser language (en/bg/es) and device theme;
|
|
75
|
+
// to fix them: payment.paymentUrl + '?lang=bg&theme=light'
|
|
65
76
|
res.redirect(payment.paymentUrl);
|
|
66
77
|
```
|
|
67
78
|
|
|
79
|
+
After paying, the customer stays on GembaPay's confirmation page — there is no return URL. Mark the
|
|
80
|
+
order paid from the `payment.completed` webhook (below) or by polling `getPaymentStatus()`.
|
|
81
|
+
|
|
68
82
|
### Check Status
|
|
69
83
|
|
|
70
84
|
```javascript
|
|
71
85
|
const status = await gembapay.getPaymentStatus('ORDER-456');
|
|
86
|
+
console.log(status.status); // 'pending' | 'completed' | 'expired' | 'refunded'
|
|
72
87
|
|
|
73
|
-
|
|
74
|
-
console.log(
|
|
88
|
+
const order = await gembapay.getPayment('ORDER-456');
|
|
89
|
+
console.log(order.payment && order.payment.txHash); // Stripe 'pi_…' or PayPal capture id
|
|
90
|
+
console.log(order.payment && order.payment.paymentMethod); // 'card' | 'apple_pay' | 'google_pay' | 'link' | null (PayPal)
|
|
75
91
|
```
|
|
76
92
|
|
|
93
|
+
`status.network` / `order.network` belong to the crypto rail and do not name the provider of a card
|
|
94
|
+
or PayPal payment; the provider is in the webhook (`payment.paymentProvider`).
|
|
95
|
+
|
|
77
96
|
### Webhook Verification
|
|
78
97
|
|
|
79
98
|
GembaPay signs every webhook. `parseWebhook` and `webhookHandler` verify the timestamped
|
|
@@ -96,7 +115,7 @@ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
|
|
|
96
115
|
gembapay.webhookHandler(async (event) => {
|
|
97
116
|
if (event.event === 'payment.completed') {
|
|
98
117
|
console.log(`✓ Order ${event.payment.orderId} paid`);
|
|
99
|
-
console.log(`
|
|
118
|
+
console.log(` ${event.payment.amountOriginal} ${event.payment.currencyOriginal} via ${event.payment.paymentProvider}`);
|
|
100
119
|
await fulfillOrder(event.payment.orderId);
|
|
101
120
|
}
|
|
102
121
|
})
|
|
@@ -107,10 +126,10 @@ Or verify manually:
|
|
|
107
126
|
|
|
108
127
|
```javascript
|
|
109
128
|
app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }), (req, res) => {
|
|
110
|
-
const
|
|
129
|
+
const header = req.headers['x-gembapay-signature-v2'];
|
|
111
130
|
|
|
112
131
|
// req.body is the raw Buffer here - verify first, parse after
|
|
113
|
-
if (!gembapay.
|
|
132
|
+
if (!gembapay.verifyWebhookV2(req.body, header)) {
|
|
114
133
|
return res.status(401).send('Invalid signature');
|
|
115
134
|
}
|
|
116
135
|
|
|
@@ -124,7 +143,7 @@ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }), (req,
|
|
|
124
143
|
Which events you receive is set in the dashboard (Webhooks): `payment.completed` (always),
|
|
125
144
|
`payment.refunded`, `payment.failed`, `payment.expired`, `dispute.created`, `dispute.closed` and
|
|
126
145
|
`subscription.*`. Every event has an `eventId` — process each one once. Payloads and handling advice for
|
|
127
|
-
each event: [docs/webhooks.md](
|
|
146
|
+
each event: [docs/webhooks.md](https://github.com/ivanovslavy/gembapay/blob/main/docs/webhooks.md).
|
|
128
147
|
|
|
129
148
|
```javascript
|
|
130
149
|
app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
|
|
@@ -172,16 +191,54 @@ await gembapay.setPaymentLinkStatus(link.id, 'disabled');
|
|
|
172
191
|
await gembapay.deletePaymentLink(link.id);
|
|
173
192
|
```
|
|
174
193
|
|
|
175
|
-
###
|
|
194
|
+
### Subscriptions
|
|
195
|
+
|
|
196
|
+
With an API key the key decides the mode (a test key only sees test plans). Archiving a plan, the
|
|
197
|
+
subscriber list and the metrics are in the dashboard.
|
|
198
|
+
|
|
199
|
+
```javascript
|
|
200
|
+
const plan = await gembapay.createPlan({
|
|
201
|
+
name: 'Pro', amount: 19.99, currency: 'EUR', interval: 'month',
|
|
202
|
+
allowedMethods: ['stripe', 'paypal'], trialDays: 14, externalRef: 'pro-monthly',
|
|
203
|
+
});
|
|
204
|
+
console.log(plan.subscribeUrl); // https://payment.gembapay.com/sub/<token> — share or embed
|
|
205
|
+
|
|
206
|
+
// or start a subscription from your server and redirect the customer:
|
|
207
|
+
const { url } = await gembapay.subscribe(plan.token, { email: 'jane@example.com', method: 'stripe' });
|
|
208
|
+
|
|
209
|
+
await gembapay.repricePlan(plan.token, 24.99); // everyone, from the next renewal
|
|
210
|
+
await gembapay.changeSubscriptionPlan(subscriptionId, otherPlan.token); // needs subscriptions:change_plan
|
|
211
|
+
await gembapay.cancelSubscription(subscriptionId); // at the end of the paid period
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
`subscriptionId` comes from the `subscription.*` webhooks. With a repeated `externalRef` the existing
|
|
215
|
+
plan is returned without `subscribeUrl` — build it from `plan.token`.
|
|
216
|
+
|
|
217
|
+
### Stats
|
|
176
218
|
|
|
177
219
|
```javascript
|
|
178
|
-
const stats = await gembapay.getStats();
|
|
179
|
-
//
|
|
220
|
+
const { stats } = await gembapay.getStats();
|
|
221
|
+
// { totalRevenue (USD, 30 days), totalTransactions, successRate (%), recentTransactions }
|
|
180
222
|
```
|
|
181
223
|
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
224
|
+
`listTransactions()` is deprecated: the transaction list is a dashboard-only endpoint, so the method
|
|
225
|
+
rejects with code `not_available_with_api_key`.
|
|
226
|
+
|
|
227
|
+
### Errors
|
|
228
|
+
|
|
229
|
+
Every failed call rejects with a `GembaPayError`: `statusCode`, `code` (e.g. `NO_PAYMENT_METHOD`,
|
|
230
|
+
`missing_scope`, `rate_limited`, `idempotency_key_reused`), `message` (the API's `error` text) and
|
|
231
|
+
`body` (the full error body).
|
|
232
|
+
|
|
233
|
+
```javascript
|
|
234
|
+
try {
|
|
235
|
+
await gembapay.createPayment({ orderId: 'ORDER-1', amount: 10, currency: 'EUR' });
|
|
236
|
+
} catch (err) {
|
|
237
|
+
if (err.statusCode === 409) { /* this orderId exists already — use a new one */ }
|
|
238
|
+
else if (err.code === 'NO_PAYMENT_METHOD') { /* connect Stripe/PayPal in the dashboard */ }
|
|
239
|
+
else throw err;
|
|
240
|
+
}
|
|
241
|
+
```
|
|
185
242
|
|
|
186
243
|
## Test Mode
|
|
187
244
|
|
|
@@ -256,8 +313,13 @@ app.listen(3000);
|
|
|
256
313
|
| `createPayment(params)` | Create payment request → returns `paymentUrl` |
|
|
257
314
|
| `getPayment(orderId)` | Get payment details |
|
|
258
315
|
| `getPaymentStatus(orderId)` | Check payment status |
|
|
259
|
-
| `
|
|
260
|
-
| `
|
|
316
|
+
| `getStats()` | Merchant statistics (last 30 days) |
|
|
317
|
+
| `createPlan(params)` / `listPlans()` | Subscription plans |
|
|
318
|
+
| `subscribe(planToken, { email, method?, firstChargeDiscount? })` | Start a subscription → `url` |
|
|
319
|
+
| `repricePlan(planToken, amount)` | New price for everyone on the plan |
|
|
320
|
+
| `cancelSubscription(id)` | Cancel at period end |
|
|
321
|
+
| `changeSubscriptionPlan(id, planToken, { idempotencyKey }?)` / `cancelScheduledPlanChange(id)` | Up/downgrade (`subscriptions:change_plan`) |
|
|
322
|
+
| `listTransactions()` | Deprecated — dashboard-only, always rejects |
|
|
261
323
|
| `createRefund(params, { idempotencyKey }?)` | Full / partial refund (`refunds:write`) |
|
|
262
324
|
| `listRefunds({ orderId?, limit? })` | List refunds |
|
|
263
325
|
| `getRefund(id)` | Get a refund |
|
|
@@ -278,11 +340,12 @@ app.listen(3000);
|
|
|
278
340
|
|
|
279
341
|
## Links
|
|
280
342
|
|
|
343
|
+
- [Developer page](https://gembapay.com/developers)
|
|
344
|
+
- [API reference](https://github.com/ivanovslavy/gembapay/blob/main/docs/api-reference.md) · [Webhooks](https://github.com/ivanovslavy/gembapay/blob/main/docs/webhooks.md) · [Integration guide](https://github.com/ivanovslavy/gembapay/blob/main/docs/integration.md)
|
|
281
345
|
- [Documentation](https://gembapay.com/docs)
|
|
282
346
|
- [Merchant Dashboard](https://merchant-dashboard.gembapay.com)
|
|
283
347
|
- [Integration Guide](https://gembapay.com/integration)
|
|
284
|
-
- [GitHub](https://github.com/ivanovslavy/gembapay)
|
|
285
|
-
- [Developer Resources](https://gembapay.com/developers)
|
|
348
|
+
- [GitHub](https://github.com/ivanovslavy/gembapay) · [Changelog](https://github.com/ivanovslavy/gembapay/blob/main/packages/npm/CHANGELOG.md)
|
|
286
349
|
|
|
287
350
|
## Support
|
|
288
351
|
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gembapay",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "GembaPay
|
|
3
|
+
"version": "1.5.0",
|
|
4
|
+
"description": "GembaPay — unified payment gateway for Stripe card payments and PayPal. Funds settle directly to the merchant.",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"types": "src/index.d.ts",
|
|
7
7
|
"files": [
|
|
8
8
|
"src/",
|
|
9
9
|
"LICENSE",
|
|
10
|
-
"README.md"
|
|
10
|
+
"README.md",
|
|
11
|
+
"CHANGELOG.md"
|
|
11
12
|
],
|
|
12
13
|
"scripts": {
|
|
13
14
|
"test": "node test/test.js",
|
|
@@ -47,7 +48,7 @@
|
|
|
47
48
|
"type": "git",
|
|
48
49
|
"url": "https://github.com/ivanovslavy/gembapay"
|
|
49
50
|
},
|
|
50
|
-
"homepage": "https://gembapay.com",
|
|
51
|
+
"homepage": "https://gembapay.com/developers",
|
|
51
52
|
"bugs": {
|
|
52
53
|
"url": "https://github.com/ivanovslavy/gembapay/issues",
|
|
53
54
|
"email": "contacts@gembapay.com"
|
package/src/index.d.ts
CHANGED
|
@@ -13,35 +13,70 @@ declare module 'gembapay' {
|
|
|
13
13
|
export interface CreatePaymentParams {
|
|
14
14
|
/** Your unique order identifier */
|
|
15
15
|
orderId: string;
|
|
16
|
-
/** Payment amount */
|
|
17
|
-
amount: number;
|
|
18
|
-
/**
|
|
16
|
+
/** Payment amount (> 0, max 1,000,000; whole units for JPY, KRW, VND, CLP, PYG, ISK, UGX) */
|
|
17
|
+
amount: number | string;
|
|
18
|
+
/** ISO 4217 code — 70 supported (default: 'USD') */
|
|
19
19
|
currency?: string;
|
|
20
|
-
/**
|
|
20
|
+
/** Shown on the checkout */
|
|
21
21
|
description?: string;
|
|
22
22
|
}
|
|
23
23
|
|
|
24
|
+
export type PaymentRequestStatus = 'pending' | 'completed' | 'expired' | 'refunded' | (string & {});
|
|
25
|
+
|
|
24
26
|
export interface PaymentResponse {
|
|
25
|
-
success:
|
|
27
|
+
success: true;
|
|
26
28
|
orderId: string;
|
|
29
|
+
/** Send the customer here as-is (redirect or new tab; it cannot be framed) */
|
|
27
30
|
paymentUrl: string;
|
|
31
|
+
/** Decimal string, e.g. "13.68" */
|
|
28
32
|
amountUsd: string;
|
|
29
33
|
amountOriginal: number;
|
|
30
34
|
currencyOriginal: string;
|
|
31
|
-
|
|
35
|
+
/** Units of currencyOriginal per 1 USD (amountUsd = amountOriginal / exchangeRate) */
|
|
36
|
+
exchangeRate: number;
|
|
37
|
+
allowedMethods: ('stripe' | 'paypal' | (string & {}))[];
|
|
38
|
+
/** 24 h after creation */
|
|
32
39
|
expiresAt: string;
|
|
33
40
|
}
|
|
34
41
|
|
|
35
42
|
export interface PaymentStatus {
|
|
43
|
+
success: true;
|
|
44
|
+
orderId: string;
|
|
45
|
+
status: PaymentRequestStatus;
|
|
46
|
+
amountUsd: string;
|
|
47
|
+
/** Field of the crypto rail — NOT the provider for card / PayPal orders */
|
|
48
|
+
network: string | null;
|
|
49
|
+
completedAt: string | null;
|
|
50
|
+
isTestMode: boolean;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface Order {
|
|
36
54
|
orderId: string;
|
|
37
|
-
status:
|
|
55
|
+
status: PaymentRequestStatus;
|
|
38
56
|
amountUsd: string;
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
57
|
+
amountOriginal: string | null;
|
|
58
|
+
/** Always 'USD' (accounting currency); see currencyOriginal */
|
|
59
|
+
currency: string;
|
|
60
|
+
currencyOriginal: string | null;
|
|
61
|
+
description: string | null;
|
|
62
|
+
/** Only for payment-link checkouts */
|
|
63
|
+
customerEmail: string | null;
|
|
64
|
+
metadata: any;
|
|
65
|
+
network: string | null;
|
|
66
|
+
paymentMode: string | null;
|
|
67
|
+
merchantAddress: string | null;
|
|
68
|
+
isTestMode: boolean;
|
|
69
|
+
createdAt: string;
|
|
70
|
+
completedAt: string | null;
|
|
71
|
+
expiresAt: string | null;
|
|
72
|
+
payment: null | {
|
|
73
|
+
/** Provider payment id: Stripe pi_… or PayPal capture id */
|
|
74
|
+
txHash: string;
|
|
75
|
+
/** "0" for card and PayPal */
|
|
76
|
+
blockNumber: string | null;
|
|
77
|
+
status: string;
|
|
78
|
+
paymentMethod: PaymentMethod | null;
|
|
79
|
+
confirmedAt: string;
|
|
45
80
|
};
|
|
46
81
|
}
|
|
47
82
|
|
|
@@ -51,7 +86,8 @@ declare module 'gembapay' {
|
|
|
51
86
|
export type WebhookEventType =
|
|
52
87
|
| 'payment.completed' | 'payment.refunded' | 'payment.failed' | 'payment.expired'
|
|
53
88
|
| 'dispute.created' | 'dispute.closed'
|
|
54
|
-
| 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
|
|
89
|
+
| 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
|
|
90
|
+
| 'subscription.plan_changed' | 'subscription.plan_change_scheduled';
|
|
55
91
|
|
|
56
92
|
/** Fields every webhook carries. */
|
|
57
93
|
interface WebhookEnvelope {
|
|
@@ -81,7 +117,10 @@ declare module 'gembapay' {
|
|
|
81
117
|
paymentProvider: 'stripe' | 'paypal' | string;
|
|
82
118
|
/** How the customer paid. null for PayPal and payments recorded before 2026-10-21. */
|
|
83
119
|
paymentMethod: PaymentMethod | null;
|
|
120
|
+
/** Payer email when the provider reports it, else 'stripe-customer' / 'paypal-customer' */
|
|
84
121
|
customerAddress?: string;
|
|
122
|
+
/** PayPal only (= amount) */
|
|
123
|
+
tokenAmount?: number;
|
|
85
124
|
timestamp?: string;
|
|
86
125
|
};
|
|
87
126
|
}
|
|
@@ -160,7 +199,8 @@ declare module 'gembapay' {
|
|
|
160
199
|
|
|
161
200
|
/** Subscription events use a flat payload (no `payment`, no orderId). */
|
|
162
201
|
export interface SubscriptionEvent {
|
|
163
|
-
event: 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
|
|
202
|
+
event: 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
|
|
203
|
+
| 'subscription.plan_changed' | 'subscription.plan_change_scheduled';
|
|
164
204
|
eventId: string;
|
|
165
205
|
subscriptionId: string;
|
|
166
206
|
providerSubscriptionId: string | null;
|
|
@@ -172,6 +212,17 @@ declare module 'gembapay' {
|
|
|
172
212
|
amount?: number;
|
|
173
213
|
currency?: string;
|
|
174
214
|
paymentMethod?: PaymentMethod | null;
|
|
215
|
+
/** subscription.payment: 'cycle' (renewal) or 'plan_change' (prorated upgrade difference) */
|
|
216
|
+
reason?: 'cycle' | 'plan_change' | (string & {});
|
|
217
|
+
/** plan-change events */
|
|
218
|
+
fromPlanToken?: string | null;
|
|
219
|
+
toPlanToken?: string | null;
|
|
220
|
+
fromAmount?: number | null;
|
|
221
|
+
toAmount?: number | null;
|
|
222
|
+
prorated?: number | null;
|
|
223
|
+
proratedRef?: string | null;
|
|
224
|
+
scheduled?: boolean;
|
|
225
|
+
effectiveAt?: string | null;
|
|
175
226
|
test?: boolean;
|
|
176
227
|
timestamp: string;
|
|
177
228
|
}
|
|
@@ -233,17 +284,96 @@ declare module 'gembapay' {
|
|
|
233
284
|
}
|
|
234
285
|
|
|
235
286
|
export interface StatsResponse {
|
|
236
|
-
|
|
287
|
+
success: true;
|
|
288
|
+
stats: {
|
|
289
|
+
/** USD, completed payments of the last 30 days */
|
|
290
|
+
totalRevenue: number;
|
|
291
|
+
/** All payments ever recorded */
|
|
292
|
+
totalTransactions: number;
|
|
293
|
+
/** Percent, last 30 days */
|
|
294
|
+
successRate: number;
|
|
295
|
+
/** Completed payments of the last 30 days */
|
|
296
|
+
recentTransactions: number;
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
export interface CreatePlanParams {
|
|
301
|
+
name: string;
|
|
302
|
+
amount: number;
|
|
303
|
+
currency?: string;
|
|
304
|
+
interval?: 'day' | 'week' | 'month' | 'year';
|
|
305
|
+
intervalCount?: number;
|
|
306
|
+
description?: string;
|
|
307
|
+
/** Default ['stripe'] */
|
|
308
|
+
allowedMethods?: ('stripe' | 'paypal')[];
|
|
309
|
+
trialDays?: number;
|
|
310
|
+
/** Your own id — makes creation idempotent */
|
|
311
|
+
externalRef?: string;
|
|
237
312
|
}
|
|
238
313
|
|
|
239
|
-
export interface
|
|
314
|
+
export interface Plan {
|
|
315
|
+
id: string;
|
|
316
|
+
/** 40 hex — the subscribe page is https://payment.gembapay.com/sub/<token> */
|
|
317
|
+
token: string;
|
|
318
|
+
name: string;
|
|
319
|
+
/** Decimal string */
|
|
320
|
+
amount: string;
|
|
321
|
+
currency: string;
|
|
322
|
+
interval: 'day' | 'week' | 'month' | 'year';
|
|
323
|
+
intervalCount: number;
|
|
324
|
+
description: string | null;
|
|
325
|
+
allowedMethods: ('stripe' | 'paypal')[];
|
|
326
|
+
trialDays: number | null;
|
|
327
|
+
status: 'active' | 'archived';
|
|
328
|
+
isTestMode: boolean;
|
|
329
|
+
createdAt: string;
|
|
330
|
+
subscriberCount?: number;
|
|
331
|
+
stripeReady?: boolean;
|
|
332
|
+
/** Absent when an existing plan is returned for a repeated externalRef */
|
|
333
|
+
subscribeUrl?: string;
|
|
334
|
+
embedSnippet?: string;
|
|
240
335
|
[key: string]: any;
|
|
241
336
|
}
|
|
242
337
|
|
|
338
|
+
export interface SubscribeParams {
|
|
339
|
+
email?: string;
|
|
340
|
+
method?: 'stripe' | 'paypal';
|
|
341
|
+
/** Stripe only */
|
|
342
|
+
firstChargeDiscount?: { percent: number };
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
export interface SubscribeResponse {
|
|
346
|
+
url: string;
|
|
347
|
+
provider: 'stripe' | 'paypal';
|
|
348
|
+
sessionId?: string;
|
|
349
|
+
subscriptionId?: string;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
export interface PlanChangeResponse {
|
|
353
|
+
id: string;
|
|
354
|
+
applied?: boolean;
|
|
355
|
+
scheduled: boolean;
|
|
356
|
+
effectiveAt?: string | null;
|
|
357
|
+
plan: Plan;
|
|
358
|
+
pendingPlan: Plan | null;
|
|
359
|
+
prorated?: number | null;
|
|
360
|
+
proratedRef?: string | null;
|
|
361
|
+
fromPlanToken?: string;
|
|
362
|
+
toPlanToken?: string;
|
|
363
|
+
fromAmount?: number;
|
|
364
|
+
toAmount?: number;
|
|
365
|
+
currency?: string;
|
|
366
|
+
interval?: string;
|
|
367
|
+
intervalCount?: number;
|
|
368
|
+
}
|
|
369
|
+
|
|
243
370
|
export class GembaPayError extends Error {
|
|
244
371
|
statusCode: number | null;
|
|
372
|
+
/** API code (e.g. 'NO_PAYMENT_METHOD', 'missing_scope', 'rate_limited') or an SDK code */
|
|
245
373
|
code: string | null;
|
|
246
|
-
|
|
374
|
+
/** Parsed error body (or raw text) from the API, if any */
|
|
375
|
+
body: any;
|
|
376
|
+
constructor(message: string, statusCode?: number | null, code?: string | null, body?: any);
|
|
247
377
|
}
|
|
248
378
|
|
|
249
379
|
export class GembaPay {
|
|
@@ -255,18 +385,28 @@ declare module 'gembapay' {
|
|
|
255
385
|
/** Create a payment request */
|
|
256
386
|
createPayment(params: CreatePaymentParams): Promise<PaymentResponse>;
|
|
257
387
|
|
|
258
|
-
/**
|
|
259
|
-
getPayment(orderId: string): Promise<
|
|
388
|
+
/** Full order record of one of your orders */
|
|
389
|
+
getPayment(orderId: string): Promise<Order>;
|
|
260
390
|
|
|
261
|
-
/**
|
|
391
|
+
/** Status of one of your orders */
|
|
262
392
|
getPaymentStatus(orderId: string): Promise<PaymentStatus>;
|
|
263
393
|
|
|
264
|
-
/**
|
|
265
|
-
listTransactions(params?: Record<string, string>): Promise<
|
|
394
|
+
/** @deprecated Dashboard-only endpoint; always rejects with code 'not_available_with_api_key'. */
|
|
395
|
+
listTransactions(params?: Record<string, string>): Promise<never>;
|
|
266
396
|
|
|
267
|
-
/**
|
|
397
|
+
/** Merchant statistics (last 30 days) */
|
|
268
398
|
getStats(): Promise<StatsResponse>;
|
|
269
399
|
|
|
400
|
+
/** Subscriptions (the key decides test/live) */
|
|
401
|
+
createPlan(params: CreatePlanParams): Promise<Plan>;
|
|
402
|
+
listPlans(): Promise<Plan[]>;
|
|
403
|
+
subscribe(planToken: string, params?: SubscribeParams): Promise<SubscribeResponse>;
|
|
404
|
+
repricePlan(planToken: string, amount: number): Promise<{ token: string; amount: number; stripePriceId: string; migrated: number; failed: number; total: number }>;
|
|
405
|
+
cancelSubscription(subscriptionId: string): Promise<{ id: string; cancelAtPeriodEnd: true }>;
|
|
406
|
+
/** Needs "subscriptions:change_plan" */
|
|
407
|
+
changeSubscriptionPlan(subscriptionId: string, planToken: string, options?: IdempotencyOptions): Promise<PlanChangeResponse>;
|
|
408
|
+
cancelScheduledPlanChange(subscriptionId: string, options?: IdempotencyOptions): Promise<PlanChangeResponse>;
|
|
409
|
+
|
|
270
410
|
/** Refund a payment fully or partly (key needs "refunds:write") */
|
|
271
411
|
createRefund(params: CreateRefundParams, options?: IdempotencyOptions): Promise<Refund>;
|
|
272
412
|
listRefunds(params?: { orderId?: string; limit?: number }): Promise<Refund[]>;
|
package/src/index.js
CHANGED
|
@@ -4,15 +4,17 @@ const https = require('https');
|
|
|
4
4
|
const crypto = require('crypto');
|
|
5
5
|
|
|
6
6
|
const BASE_URL = 'https://api.gembapay.com';
|
|
7
|
-
const VERSION = '1.
|
|
7
|
+
const VERSION = '1.5.0';
|
|
8
8
|
const SIGNATURE_TOLERANCE_SEC = 300;
|
|
9
9
|
|
|
10
10
|
class GembaPayError extends Error {
|
|
11
|
-
constructor(message, statusCode, code) {
|
|
11
|
+
constructor(message, statusCode, code, body) {
|
|
12
12
|
super(message);
|
|
13
13
|
this.name = 'GembaPayError';
|
|
14
14
|
this.statusCode = statusCode;
|
|
15
15
|
this.code = code;
|
|
16
|
+
/** The parsed error body from the API (or the raw text when it was not JSON), if any. */
|
|
17
|
+
this.body = body === undefined ? null : body;
|
|
16
18
|
}
|
|
17
19
|
}
|
|
18
20
|
|
|
@@ -27,7 +29,7 @@ class GembaPay {
|
|
|
27
29
|
*/
|
|
28
30
|
constructor({ apiKey, webhookSecret, baseUrl, timeout } = {}) {
|
|
29
31
|
if (!apiKey) {
|
|
30
|
-
throw new GembaPayError('API key is required. Get yours at https://merchant.gembapay.com', null, 'missing_api_key');
|
|
32
|
+
throw new GembaPayError('API key is required. Get yours at https://merchant-dashboard.gembapay.com (API Keys)', null, 'missing_api_key');
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
this.apiKey = apiKey;
|
|
@@ -44,9 +46,12 @@ class GembaPay {
|
|
|
44
46
|
* @param {Object} params
|
|
45
47
|
* @param {string} params.orderId - Your unique order identifier
|
|
46
48
|
* @param {number} params.amount - Payment amount
|
|
47
|
-
* @param {string} [params.currency='USD'] -
|
|
48
|
-
* @param {string} [params.description] -
|
|
49
|
-
* @returns {Promise<Object>}
|
|
49
|
+
* @param {string} [params.currency='USD'] - ISO 4217 code (70 supported)
|
|
50
|
+
* @param {string} [params.description] - Shown on the checkout
|
|
51
|
+
* @returns {Promise<Object>} { success, orderId, paymentUrl, amountUsd, amountOriginal, currencyOriginal,
|
|
52
|
+
* exchangeRate (units of currencyOriginal per 1 USD), allowedMethods, expiresAt }.
|
|
53
|
+
* The request expires after 24 h. Only these four fields are sent: the API has no return URL,
|
|
54
|
+
* customer email or metadata parameter.
|
|
50
55
|
*/
|
|
51
56
|
async createPayment({ orderId, amount, currency = 'USD', description } = {}) {
|
|
52
57
|
if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
|
|
@@ -74,7 +79,9 @@ class GembaPay {
|
|
|
74
79
|
/**
|
|
75
80
|
* Check payment status for one of YOUR orders (authenticated, ownership-scoped).
|
|
76
81
|
* @param {string} orderId - Order identifier
|
|
77
|
-
* @returns {Promise<Object>}
|
|
82
|
+
* @returns {Promise<Object>} { success, orderId, status, amountUsd, network, completedAt, isTestMode }.
|
|
83
|
+
* status: 'pending' | 'completed' | 'expired' | 'refunded'. `network` belongs to the crypto rail and
|
|
84
|
+
* is not the payment provider for card / PayPal orders — use getPayment() → payment.txHash, or the webhook.
|
|
78
85
|
*/
|
|
79
86
|
async getPaymentStatus(orderId) {
|
|
80
87
|
if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
|
|
@@ -84,19 +91,20 @@ class GembaPay {
|
|
|
84
91
|
// ── Merchant ─────────────────────────────────────────
|
|
85
92
|
|
|
86
93
|
/**
|
|
87
|
-
*
|
|
88
|
-
*
|
|
89
|
-
*
|
|
94
|
+
* @deprecated The transaction list is a dashboard (login) endpoint; the API answers 401 to an API key.
|
|
95
|
+
* Kept so existing code gets a clear error instead of a confusing 401. Use getPaymentStatus(),
|
|
96
|
+
* getPayment() and getStats(), or the dashboard.
|
|
97
|
+
* @returns {Promise<never>}
|
|
90
98
|
*/
|
|
91
|
-
async listTransactions(
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
99
|
+
async listTransactions() {
|
|
100
|
+
throw new GembaPayError(
|
|
101
|
+
'listTransactions() is not available with an API key: /api/merchant/transactions is a dashboard endpoint. '
|
|
102
|
+
+ 'Use getPayment(orderId), getPaymentStatus(orderId) or getStats().', null, 'not_available_with_api_key');
|
|
95
103
|
}
|
|
96
104
|
|
|
97
105
|
/**
|
|
98
|
-
* Get merchant statistics
|
|
99
|
-
* @returns {Promise<Object>}
|
|
106
|
+
* Get merchant statistics (last 30 days, USD).
|
|
107
|
+
* @returns {Promise<Object>} { success, stats: { totalRevenue, totalTransactions, successRate, recentTransactions } }
|
|
100
108
|
*/
|
|
101
109
|
async getStats() {
|
|
102
110
|
return this._request('GET', '/api/merchant/stats');
|
|
@@ -294,6 +302,93 @@ class GembaPay {
|
|
|
294
302
|
return this._request('DELETE', `/api/v1/payment-links/${encodeURIComponent(id)}`);
|
|
295
303
|
}
|
|
296
304
|
|
|
305
|
+
// ── Subscriptions ────────────────────────────────────
|
|
306
|
+
// With an API key the key decides the mode (test key → test plans only). Getting one plan, archiving a
|
|
307
|
+
// plan, listing subscribers and the metrics are dashboard-only endpoints and are therefore not here.
|
|
308
|
+
|
|
309
|
+
/**
|
|
310
|
+
* Create a subscription plan. Returns the plan object (incl. token, subscribeUrl, embedSnippet).
|
|
311
|
+
* With an externalRef that already exists, the stored plan is returned (idempotent sync) — it then has
|
|
312
|
+
* no subscribeUrl; the subscribe page is https://payment.gembapay.com/sub/<token>.
|
|
313
|
+
* @param {Object} params - { name, amount, currency?, interval?: 'day'|'week'|'month'|'year',
|
|
314
|
+
* intervalCount?, description?, allowedMethods?: ('stripe'|'paypal')[], trialDays?, externalRef? }
|
|
315
|
+
* @returns {Promise<Object>}
|
|
316
|
+
*/
|
|
317
|
+
async createPlan(params = {}) {
|
|
318
|
+
if (!params.name) throw new GembaPayError('name is required', null, 'missing_param');
|
|
319
|
+
if (!(Number(params.amount) > 0)) throw new GembaPayError('amount must be greater than 0', null, 'invalid_param');
|
|
320
|
+
const body = { ...params };
|
|
321
|
+
delete body.isTestMode; // the key decides the mode
|
|
322
|
+
return this._request('POST', '/api/subscriptions', body);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** @returns {Promise<Object[]>} Plans of this key's mode (array, newest first) */
|
|
326
|
+
async listPlans() {
|
|
327
|
+
return this._request('GET', '/api/subscriptions');
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
/**
|
|
331
|
+
* Start a subscription to one of your plans from your server. Redirect the customer to the returned url.
|
|
332
|
+
* @param {string} planToken
|
|
333
|
+
* @param {Object} params - { email, method?: 'stripe'|'paypal', firstChargeDiscount?: { percent } (Stripe only) }
|
|
334
|
+
* @returns {Promise<Object>} { url, sessionId, provider } (PayPal: { url, subscriptionId, provider })
|
|
335
|
+
*/
|
|
336
|
+
async subscribe(planToken, { email, method, firstChargeDiscount } = {}) {
|
|
337
|
+
if (!planToken) throw new GembaPayError('planToken is required', null, 'missing_param');
|
|
338
|
+
const body = {};
|
|
339
|
+
if (email) body.email = email;
|
|
340
|
+
if (method) body.method = method;
|
|
341
|
+
if (firstChargeDiscount) body.firstChargeDiscount = firstChargeDiscount;
|
|
342
|
+
return this._request('POST', `/api/subscriptions/plan/${encodeURIComponent(planToken)}/subscribe`, body);
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Change the recurring price of a plan for everyone on it (Stripe, no proration — from the next renewal).
|
|
347
|
+
* @param {string} planToken @param {number} amount
|
|
348
|
+
* @returns {Promise<Object>} { token, amount, stripePriceId, migrated, failed, total }
|
|
349
|
+
*/
|
|
350
|
+
async repricePlan(planToken, amount) {
|
|
351
|
+
if (!planToken) throw new GembaPayError('planToken is required', null, 'missing_param');
|
|
352
|
+
if (!(Number(amount) > 0)) throw new GembaPayError('amount must be greater than 0', null, 'invalid_param');
|
|
353
|
+
return this._request('POST', `/api/subscriptions/plan/${encodeURIComponent(planToken)}/reprice`, { amount });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Cancel a subscription at the end of the paid period.
|
|
358
|
+
* @param {string} subscriptionId - `subscriptionId` from the subscription.* webhooks
|
|
359
|
+
* @returns {Promise<Object>} { id, cancelAtPeriodEnd: true }
|
|
360
|
+
*/
|
|
361
|
+
async cancelSubscription(subscriptionId) {
|
|
362
|
+
if (!subscriptionId) throw new GembaPayError('subscriptionId is required', null, 'missing_param');
|
|
363
|
+
return this._request('POST', `/api/subscriptions/subscribers/${encodeURIComponent(subscriptionId)}/cancel`, {});
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/**
|
|
367
|
+
* Move a subscriber to another plan (same currency + interval). Dearer → now, after the prorated
|
|
368
|
+
* difference is paid (402 otherwise, nothing changes); cheaper → at the next renewal.
|
|
369
|
+
* The API key needs the "subscriptions:change_plan" permission.
|
|
370
|
+
* @param {string} subscriptionId @param {string} planToken
|
|
371
|
+
* @param {Object} [options] - { idempotencyKey } — reuse it when retrying so the difference is not charged twice
|
|
372
|
+
* @returns {Promise<Object>} { id, applied, scheduled, effectiveAt, plan, pendingPlan, prorated, … }
|
|
373
|
+
*/
|
|
374
|
+
async changeSubscriptionPlan(subscriptionId, planToken, { idempotencyKey } = {}) {
|
|
375
|
+
if (!subscriptionId) throw new GembaPayError('subscriptionId is required', null, 'missing_param');
|
|
376
|
+
if (!planToken) throw new GembaPayError('planToken is required', null, 'missing_param');
|
|
377
|
+
return this._request('POST', `/api/subscriptions/subscribers/${encodeURIComponent(subscriptionId)}/change-plan`,
|
|
378
|
+
{ planToken }, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Call off a scheduled (cheaper) plan change. Needs "subscriptions:change_plan".
|
|
383
|
+
* @param {string} subscriptionId @param {Object} [options] - { idempotencyKey }
|
|
384
|
+
* @returns {Promise<Object>} { id, scheduled: false, plan, pendingPlan: null }
|
|
385
|
+
*/
|
|
386
|
+
async cancelScheduledPlanChange(subscriptionId, { idempotencyKey } = {}) {
|
|
387
|
+
if (!subscriptionId) throw new GembaPayError('subscriptionId is required', null, 'missing_param');
|
|
388
|
+
return this._request('POST', `/api/subscriptions/subscribers/${encodeURIComponent(subscriptionId)}/change-plan/cancel`,
|
|
389
|
+
{}, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
|
|
390
|
+
}
|
|
391
|
+
|
|
297
392
|
// ── Internal ─────────────────────────────────────────
|
|
298
393
|
|
|
299
394
|
_request(method, path, body, extraHeaders = {}) {
|
|
@@ -317,19 +412,28 @@ class GembaPay {
|
|
|
317
412
|
let data = '';
|
|
318
413
|
res.on('data', (chunk) => data += chunk);
|
|
319
414
|
res.on('end', () => {
|
|
415
|
+
let parsed;
|
|
320
416
|
try {
|
|
321
|
-
|
|
417
|
+
parsed = JSON.parse(data);
|
|
418
|
+
} catch {
|
|
419
|
+
// Not JSON — e.g. the per-IP rate limiter answers 429 with plain text.
|
|
322
420
|
if (res.statusCode >= 400) {
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
res.statusCode,
|
|
326
|
-
parsed.code
|
|
327
|
-
));
|
|
328
|
-
} else {
|
|
329
|
-
resolve(parsed);
|
|
421
|
+
const text = String(data || '').trim().slice(0, 300);
|
|
422
|
+
return reject(new GembaPayError(text || `HTTP ${res.statusCode}`, res.statusCode,
|
|
423
|
+
res.statusCode === 429 ? 'rate_limited' : 'http_error', text));
|
|
330
424
|
}
|
|
331
|
-
|
|
332
|
-
|
|
425
|
+
return reject(new GembaPayError(`Invalid response: ${String(data).slice(0, 300)}`, res.statusCode, 'parse_error'));
|
|
426
|
+
}
|
|
427
|
+
if (res.statusCode >= 400) {
|
|
428
|
+
// The API puts the message in `error` (some answers add a longer `message` or `details`).
|
|
429
|
+
reject(new GembaPayError(
|
|
430
|
+
(parsed && (parsed.error || parsed.message)) || `HTTP ${res.statusCode}`,
|
|
431
|
+
res.statusCode,
|
|
432
|
+
(parsed && parsed.code) || null,
|
|
433
|
+
parsed
|
|
434
|
+
));
|
|
435
|
+
} else {
|
|
436
|
+
resolve(parsed);
|
|
333
437
|
}
|
|
334
438
|
});
|
|
335
439
|
});
|