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