gembapay 1.3.1 → 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 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
- - **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,25 +65,42 @@ 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 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
- console.log(status.status); // 'completed'
74
- console.log(status.network); // 'stripe', 'paypal'
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
- GembaPay signs every webhook with HMAC-SHA256 over the **raw request body** and sends the
80
- signature as **bare hex** (no `sha256=` prefix) in the `X-GembaPay-Signature` header.
81
- `verifyWebhook`, `parseWebhook` and `webhookHandler` check exactly that. Mount the webhook route
98
+ GembaPay signs every webhook. `parseWebhook` and `webhookHandler` verify the timestamped
99
+ **`X-GembaPay-Signature-V2`** header (`t=<unix>,v1=<hex>`, HMAC-SHA256 over `"<t>.<raw body>"`) and
100
+ reject requests older than 5 minutes — a copied webhook cannot be replayed. Only when a request has no
101
+ V2 header do they fall back to the legacy `X-GembaPay-Signature` (bare hex over the raw body); pass
102
+ `{ requireV2: true }` to refuse legacy-only requests. `verifyWebhookV2(rawBody, header)` and
103
+ `verifyWebhook(rawBody, signature)` are available for manual checks. Mount the webhook route
82
104
  with `express.raw({ type: 'application/json' })` so the SDK sees the exact bytes that were signed
83
105
  (a parsed `express.json()` body is re-serialized as a fallback, which is less reliable).
84
106
  Subscription cycles arrive as `subscription.payment` (flat payload, no `orderId`), not
@@ -93,7 +115,7 @@ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
93
115
  gembapay.webhookHandler(async (event) => {
94
116
  if (event.event === 'payment.completed') {
95
117
  console.log(`✓ Order ${event.payment.orderId} paid`);
96
- console.log(` $${event.payment.usdAmount} via ${event.payment.network}`);
118
+ console.log(` ${event.payment.amountOriginal} ${event.payment.currencyOriginal} via ${event.payment.paymentProvider}`);
97
119
  await fulfillOrder(event.payment.orderId);
98
120
  }
99
121
  })
@@ -104,10 +126,10 @@ Or verify manually:
104
126
 
105
127
  ```javascript
106
128
  app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }), (req, res) => {
107
- const signature = req.headers['x-gembapay-signature'];
129
+ const header = req.headers['x-gembapay-signature-v2'];
108
130
 
109
131
  // req.body is the raw Buffer here - verify first, parse after
110
- if (!gembapay.verifyWebhook(req.body, signature)) {
132
+ if (!gembapay.verifyWebhookV2(req.body, header)) {
111
133
  return res.status(401).send('Invalid signature');
112
134
  }
113
135
 
@@ -118,16 +140,105 @@ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }), (req,
118
140
  });
119
141
  ```
120
142
 
121
- ### Transactions & Stats
143
+ Which events you receive is set in the dashboard (Webhooks): `payment.completed` (always),
144
+ `payment.refunded`, `payment.failed`, `payment.expired`, `dispute.created`, `dispute.closed` and
145
+ `subscription.*`. Every event has an `eventId` — process each one once. Payloads and handling advice for
146
+ each event: [docs/webhooks.md](https://github.com/ivanovslavy/gembapay/blob/main/docs/webhooks.md).
122
147
 
123
148
  ```javascript
124
- const stats = await gembapay.getStats();
125
- // const transactions = await gembapay.listTransactions(); // see note below
149
+ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
150
+ gembapay.webhookHandler(async (event) => {
151
+ if (event.test) return; // dashboard "Send test"
152
+ switch (event.event) {
153
+ case 'payment.completed': return markPaid(event.payment.orderId);
154
+ case 'payment.refunded': return recordRefund(event.refund, event.payment.fullyRefunded);
155
+ case 'payment.expired': return cancelIfUnpaid(event.payment.orderId);
156
+ case 'dispute.created': return holdOrder(event.dispute.orderId);
157
+ }
158
+ })
159
+ );
126
160
  ```
127
161
 
128
- > **Note:** `listTransactions()` currently targets a **dashboard (JWT) endpoint** and returns
129
- > `401` with an API key. Use `getStats()` / `getPaymentStatus()` programmatically, or view
130
- > transactions in the dashboard, until the SDK/endpoint is aligned.
162
+ ### Refunds
163
+
164
+ Full or partial refunds of card (incl. Apple Pay / Google Pay) and PayPal payments. The API key needs
165
+ the **`refunds:write`** permission (Dashboard → API Keys → Permissions).
166
+
167
+ ```javascript
168
+ // partial refund — pass your own idempotency key and reuse it if you retry after a timeout
169
+ const refund = await gembapay.createRefund(
170
+ { orderId: 'ORDER-123', amount: '5.00', reason: 'One item returned' },
171
+ { idempotencyKey: `refund-ORDER-123-item-7` }
172
+ );
173
+ console.log(refund.id, refund.status); // 'succeeded' | 'pending'
174
+
175
+ await gembapay.createRefund({ orderId: 'ORDER-123' }); // everything still refundable
176
+ const refunds = await gembapay.listRefunds({ orderId: 'ORDER-123' });
177
+ ```
178
+
179
+ ### Payment Links
180
+
181
+ Create hosted payment links from your own system. The API key needs **`payment_links:write`**; test
182
+ keys create test links, live keys live links.
183
+
184
+ ```javascript
185
+ const link = await gembapay.createPaymentLink({
186
+ amount: 49.9, currency: 'EUR', description: 'Workshop ticket', multiUse: true, maxUses: 100,
187
+ });
188
+ console.log(`https://payment.gembapay.com/link/${link.token}`);
189
+
190
+ await gembapay.setPaymentLinkStatus(link.id, 'disabled');
191
+ await gembapay.deletePaymentLink(link.id);
192
+ ```
193
+
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
218
+
219
+ ```javascript
220
+ const { stats } = await gembapay.getStats();
221
+ // { totalRevenue (USD, 30 days), totalTransactions, successRate (%), recentTransactions }
222
+ ```
223
+
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
+ ```
131
242
 
132
243
  ## Test Mode
133
244
 
@@ -202,11 +313,23 @@ app.listen(3000);
202
313
  | `createPayment(params)` | Create payment request → returns `paymentUrl` |
203
314
  | `getPayment(orderId)` | Get payment details |
204
315
  | `getPaymentStatus(orderId)` | Check payment status |
205
- | `listTransactions(params?)` | List merchant transactions |
206
- | `getStats()` | Get merchant statistics |
207
- | `verifyWebhook(payload, signature)` | Verify webhook signature |
208
- | `parseWebhook(req)` | Parse & verify Express request |
209
- | `webhookHandler(fn)` | Express webhook middleware |
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 |
323
+ | `createRefund(params, { idempotencyKey }?)` | Full / partial refund (`refunds:write`) |
324
+ | `listRefunds({ orderId?, limit? })` | List refunds |
325
+ | `getRefund(id)` | Get a refund |
326
+ | `createPaymentLink(params, { idempotencyKey }?)` | Create a payment link (`payment_links:write`) |
327
+ | `listPaymentLinks()` / `getPaymentLink(id)` | Read payment links |
328
+ | `setPaymentLinkStatus(id, status)` / `deletePaymentLink(id)` | Disable / enable / delete a link |
329
+ | `verifyWebhookV2(rawBody, header, { toleranceSec }?)` | Verify `X-GembaPay-Signature-V2` |
330
+ | `verifyWebhook(rawBody, signature)` | Verify the legacy signature |
331
+ | `parseWebhook(req, { requireV2 }?)` | Parse & verify an Express request (V2 when present) |
332
+ | `webhookHandler(fn, { requireV2 }?)` | Express webhook middleware |
210
333
 
211
334
  ## Fee Structure
212
335
 
@@ -217,11 +340,12 @@ app.listen(3000);
217
340
 
218
341
  ## Links
219
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)
220
345
  - [Documentation](https://gembapay.com/docs)
221
346
  - [Merchant Dashboard](https://merchant-dashboard.gembapay.com)
222
347
  - [Integration Guide](https://gembapay.com/integration)
223
- - [GitHub](https://github.com/ivanovslavy/gembapay)
224
- - [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)
225
349
 
226
350
  ## Support
227
351
 
package/package.json CHANGED
@@ -1,13 +1,14 @@
1
1
  {
2
2
  "name": "gembapay",
3
- "version": "1.3.1",
4
- "description": "GembaPay \u2014 unified payment gateway for Stripe card payments and PayPal. Funds settle directly to the merchant.",
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,69 +13,367 @@ 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
22
  }
23
23
 
24
+ export type PaymentRequestStatus = 'pending' | 'completed' | 'expired' | 'refunded' | (string & {});
25
+
24
26
  export interface PaymentResponse {
25
- success: boolean;
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
- allowedMethods: ('stripe' | 'paypal')[];
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;
36
44
  orderId: string;
37
- status: 'pending' | 'processing' | 'confirmed' | 'completed' | 'failed' | 'expired';
45
+ status: PaymentRequestStatus;
38
46
  amountUsd: string;
39
- network: 'stripe' | 'paypal';
40
- paymentProvider: 'stripe' | 'paypal';
41
- payment?: {
42
- reference?: string;
43
- tokenSymbol?: string;
44
- tokenAmount?: 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 {
54
+ orderId: string;
55
+ status: PaymentRequestStatus;
56
+ amountUsd: string;
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
 
48
83
  /** Stripe may add other values over time - treat unknown ones like 'card'. */
49
84
  export type PaymentMethod = 'card' | 'apple_pay' | 'google_pay' | 'link' | (string & {});
50
85
 
51
- export interface WebhookEvent {
52
- event: 'payment.completed' | 'payment.failed';
86
+ export type WebhookEventType =
87
+ | 'payment.completed' | 'payment.refunded' | 'payment.failed' | 'payment.expired'
88
+ | 'dispute.created' | 'dispute.closed'
89
+ | 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
90
+ | 'subscription.plan_changed' | 'subscription.plan_change_scheduled';
91
+
92
+ /** Fields every webhook carries. */
93
+ interface WebhookEnvelope {
94
+ /** Unique per event — use it as your idempotency key. */
95
+ eventId: string;
96
+ /** true for test-mode payments (test key, test cards, PayPal sandbox) */
53
97
  testMode?: boolean;
98
+ /** true only for dashboard "Send test" samples — never act on them */
99
+ test?: boolean;
100
+ timestamp: string;
101
+ }
102
+
103
+ export interface PaymentCompletedEvent extends WebhookEnvelope {
104
+ event: 'payment.completed';
54
105
  payment: {
55
106
  orderId: string;
56
- reference?: string;
57
- network: string;
107
+ amount: number;
108
+ currency: string;
109
+ amountOriginal?: number | null;
110
+ currencyOriginal?: string | null;
58
111
  usdAmount: number;
59
- tokenAmount?: string;
60
- paymentProvider?: string;
112
+ exchangeRate?: number | null;
113
+ status: 'completed';
114
+ /** Provider payment id: Stripe PaymentIntent (pi_…) or PayPal capture id */
115
+ txHash: string;
116
+ network: string;
117
+ paymentProvider: 'stripe' | 'paypal' | string;
61
118
  /** How the customer paid. null for PayPal and payments recorded before 2026-10-21. */
62
- paymentMethod?: PaymentMethod | null;
119
+ paymentMethod: PaymentMethod | null;
120
+ /** Payer email when the provider reports it, else 'stripe-customer' / 'paypal-customer' */
121
+ customerAddress?: string;
122
+ /** PayPal only (= amount) */
123
+ tokenAmount?: number;
124
+ timestamp?: string;
125
+ };
126
+ }
127
+
128
+ export interface Refund {
129
+ id: string;
130
+ orderId: string;
131
+ amount: number;
132
+ currency: string;
133
+ status: 'succeeded' | 'pending' | 'failed';
134
+ reason: string | null;
135
+ source: 'api' | 'dashboard' | 'provider';
136
+ provider: 'stripe' | 'paypal';
137
+ providerRefundId: string | null;
138
+ failureReason: string | null;
139
+ testMode: boolean;
140
+ createdAt: string;
141
+ }
142
+
143
+ interface PaymentSummary {
144
+ orderId: string;
145
+ amount: number;
146
+ currency: string;
147
+ paymentProvider: 'stripe' | 'paypal' | string;
148
+ paymentMethod: PaymentMethod | null;
149
+ /** Provider payment id (pi_… / PayPal capture id) */
150
+ reference: string;
151
+ }
152
+
153
+ export interface PaymentRefundedEvent extends WebhookEnvelope {
154
+ event: 'payment.refunded';
155
+ refund: Refund;
156
+ payment: PaymentSummary & { refundedTotal: number; remaining: number; fullyRefunded: boolean };
157
+ }
158
+
159
+ export interface PaymentFailedEvent extends WebhookEnvelope {
160
+ event: 'payment.failed';
161
+ payment: {
162
+ orderId: string;
163
+ amount: number;
164
+ currency: string;
165
+ paymentProvider: 'stripe' | 'paypal' | string;
166
+ paymentMethod: PaymentMethod | null;
167
+ failureCode: string | null;
168
+ failureMessage: string | null;
169
+ /** Always false: the customer may retry until expiresAt */
170
+ final: false;
171
+ expiresAt: string | null;
63
172
  };
173
+ }
174
+
175
+ export interface PaymentExpiredEvent extends WebhookEnvelope {
176
+ event: 'payment.expired';
177
+ payment: { orderId: string; amount: number; currency: string; status: 'expired'; expiresAt: string };
178
+ }
179
+
180
+ export interface Dispute {
181
+ id: string;
182
+ provider: 'stripe' | 'paypal';
183
+ providerDisputeId: string;
184
+ orderId: string;
185
+ amount: number | null;
186
+ currency: string | null;
187
+ reason: string | null;
188
+ status: string;
189
+ outcome: 'won' | 'lost' | 'other' | null;
190
+ createdAt: string;
191
+ closedAt: string | null;
192
+ }
193
+
194
+ export interface DisputeEvent extends WebhookEnvelope {
195
+ event: 'dispute.created' | 'dispute.closed';
196
+ dispute: Dispute;
197
+ payment: PaymentSummary;
198
+ }
199
+
200
+ /** Subscription events use a flat payload (no `payment`, no orderId). */
201
+ export interface SubscriptionEvent {
202
+ event: 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled'
203
+ | 'subscription.plan_changed' | 'subscription.plan_change_scheduled';
204
+ eventId: string;
205
+ subscriptionId: string;
206
+ providerSubscriptionId: string | null;
207
+ planId: string | null;
208
+ planToken: string | null;
209
+ customerEmail: string | null;
210
+ status: string | null;
211
+ isTestMode: boolean;
212
+ amount?: number;
213
+ currency?: string;
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;
226
+ test?: boolean;
64
227
  timestamp: string;
65
228
  }
66
229
 
67
- export interface StatsResponse {
230
+ export type WebhookEvent =
231
+ | PaymentCompletedEvent | PaymentRefundedEvent | PaymentFailedEvent | PaymentExpiredEvent
232
+ | DisputeEvent | SubscriptionEvent;
233
+
234
+ export interface CreateRefundParams {
235
+ orderId: string;
236
+ /** In the payment currency; omit to refund everything still refundable */
237
+ amount?: number | string;
238
+ reason?: string;
239
+ }
240
+
241
+ export interface IdempotencyOptions {
242
+ /** Reuse the same key when retrying after a timeout so the operation cannot happen twice. */
243
+ idempotencyKey?: string;
244
+ }
245
+
246
+ export interface CustomerField { enabled: boolean; required: boolean }
247
+
248
+ export interface CreatePaymentLinkParams {
249
+ /** Fixed amount; omit/null to let the payer choose */
250
+ amount?: number | null;
251
+ currency?: string;
252
+ description?: string;
253
+ methods?: ('stripe' | 'paypal')[];
254
+ multiUse?: boolean;
255
+ maxUses?: number | null;
256
+ maxTotalAmount?: number | null;
257
+ expiresAt?: string | null;
258
+ customerFields?: Partial<Record<'name' | 'email' | 'phone' | 'note', CustomerField>>;
259
+ merchantNotify?: boolean;
260
+ }
261
+
262
+ export interface PaymentLink {
263
+ id: string;
264
+ token: string;
265
+ amount: number | null;
266
+ openAmount: boolean;
267
+ currency: string;
268
+ description: string | null;
269
+ methods: string[];
270
+ multiUse: boolean;
271
+ maxUses: number | null;
272
+ maxTotalAmount: number | null;
273
+ expiresAt: string | null;
274
+ merchantNotify: boolean;
275
+ isTestMode: boolean;
276
+ mode: 'test' | 'live';
277
+ status: string;
278
+ rawStatus: 'active' | 'disabled';
279
+ usedCount: number;
280
+ totalCollected: number;
281
+ createdAt: string;
282
+ uses?: any[];
68
283
  [key: string]: any;
69
284
  }
70
285
 
71
- export interface TransactionsResponse {
286
+ export interface StatsResponse {
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;
312
+ }
313
+
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;
72
335
  [key: string]: any;
73
336
  }
74
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
+
75
370
  export class GembaPayError extends Error {
76
371
  statusCode: number | null;
372
+ /** API code (e.g. 'NO_PAYMENT_METHOD', 'missing_scope', 'rate_limited') or an SDK code */
77
373
  code: string | null;
78
- constructor(message: string, statusCode?: number | null, code?: string | null);
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);
79
377
  }
80
378
 
81
379
  export class GembaPay {
@@ -87,26 +385,51 @@ declare module 'gembapay' {
87
385
  /** Create a payment request */
88
386
  createPayment(params: CreatePaymentParams): Promise<PaymentResponse>;
89
387
 
90
- /** Get payment details */
91
- getPayment(orderId: string): Promise<any>;
388
+ /** Full order record of one of your orders */
389
+ getPayment(orderId: string): Promise<Order>;
92
390
 
93
- /** Check payment status */
391
+ /** Status of one of your orders */
94
392
  getPaymentStatus(orderId: string): Promise<PaymentStatus>;
95
393
 
96
- /** List merchant transactions */
97
- listTransactions(params?: Record<string, string>): Promise<TransactionsResponse>;
394
+ /** @deprecated Dashboard-only endpoint; always rejects with code 'not_available_with_api_key'. */
395
+ listTransactions(params?: Record<string, string>): Promise<never>;
98
396
 
99
- /** Get merchant statistics */
397
+ /** Merchant statistics (last 30 days) */
100
398
  getStats(): Promise<StatsResponse>;
101
399
 
102
- /** Verify webhook signature */
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
+
410
+ /** Refund a payment fully or partly (key needs "refunds:write") */
411
+ createRefund(params: CreateRefundParams, options?: IdempotencyOptions): Promise<Refund>;
412
+ listRefunds(params?: { orderId?: string; limit?: number }): Promise<Refund[]>;
413
+ getRefund(refundId: string): Promise<Refund>;
414
+
415
+ /** Payment links (key needs "payment_links:write" to create/change) */
416
+ createPaymentLink(params: CreatePaymentLinkParams, options?: IdempotencyOptions): Promise<PaymentLink>;
417
+ listPaymentLinks(): Promise<PaymentLink[]>;
418
+ getPaymentLink(id: string): Promise<PaymentLink>;
419
+ setPaymentLinkStatus(id: string, status: 'active' | 'disabled'): Promise<PaymentLink>;
420
+ deletePaymentLink(id: string): Promise<{ success: boolean; ok: boolean }>;
421
+
422
+ /** Verify the X-GembaPay-Signature-V2 header (timestamped, recommended) */
423
+ verifyWebhookV2(rawBody: string | Buffer, header: string, options?: { toleranceSec?: number }): boolean;
424
+
425
+ /** Verify the legacy X-GembaPay-Signature header (no replay protection) */
103
426
  verifyWebhook(payload: string | Buffer | object, signature: string): boolean;
104
427
 
105
- /** Parse and verify a webhook request */
106
- parseWebhook(req: { headers: Record<string, string>; body: any }): WebhookEvent;
428
+ /** Parse and verify a webhook request — uses Signature-V2 when present */
429
+ parseWebhook(req: { headers: Record<string, string | undefined>; body: any; rawBody?: any }, options?: { requireV2?: boolean }): WebhookEvent;
107
430
 
108
- /** Express middleware for webhook handling */
109
- webhookHandler(handler: (event: WebhookEvent) => Promise<void>): (req: any, res: any) => Promise<void>;
431
+ /** Express middleware for webhook handling (mount with express.raw) */
432
+ webhookHandler(handler: (event: WebhookEvent) => Promise<void>, options?: { requireV2?: boolean }): (req: any, res: any) => Promise<void>;
110
433
  }
111
434
 
112
435
  export default GembaPay;
package/src/index.js CHANGED
@@ -4,14 +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.1.1';
7
+ const VERSION = '1.5.0';
8
+ const SIGNATURE_TOLERANCE_SEC = 300;
8
9
 
9
10
  class GembaPayError extends Error {
10
- constructor(message, statusCode, code) {
11
+ constructor(message, statusCode, code, body) {
11
12
  super(message);
12
13
  this.name = 'GembaPayError';
13
14
  this.statusCode = statusCode;
14
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;
15
18
  }
16
19
  }
17
20
 
@@ -26,7 +29,7 @@ class GembaPay {
26
29
  */
27
30
  constructor({ apiKey, webhookSecret, baseUrl, timeout } = {}) {
28
31
  if (!apiKey) {
29
- 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');
30
33
  }
31
34
 
32
35
  this.apiKey = apiKey;
@@ -43,9 +46,12 @@ class GembaPay {
43
46
  * @param {Object} params
44
47
  * @param {string} params.orderId - Your unique order identifier
45
48
  * @param {number} params.amount - Payment amount
46
- * @param {string} [params.currency='USD'] - Currency code (51+ supported)
47
- * @param {string} [params.description] - Payment description
48
- * @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
+ * @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.
49
55
  */
50
56
  async createPayment({ orderId, amount, currency = 'USD', description } = {}) {
51
57
  if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
@@ -73,7 +79,9 @@ class GembaPay {
73
79
  /**
74
80
  * Check payment status for one of YOUR orders (authenticated, ownership-scoped).
75
81
  * @param {string} orderId - Order identifier
76
- * @returns {Promise<Object>} Payment status ({ status, orderId, amountUsd, network, completedAt, isTestMode })
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.
77
85
  */
78
86
  async getPaymentStatus(orderId) {
79
87
  if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
@@ -83,19 +91,20 @@ class GembaPay {
83
91
  // ── Merchant ─────────────────────────────────────────
84
92
 
85
93
  /**
86
- * List merchant transactions
87
- * @param {Object} [params] - Query parameters
88
- * @returns {Promise<Object>} Transaction list
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>}
89
98
  */
90
- async listTransactions(params = {}) {
91
- const query = new URLSearchParams(params).toString();
92
- const path = '/api/merchant/transactions' + (query ? `?${query}` : '');
93
- return this._request('GET', path);
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');
94
103
  }
95
104
 
96
105
  /**
97
- * Get merchant statistics
98
- * @returns {Promise<Object>} Payment statistics
106
+ * Get merchant statistics (last 30 days, USD).
107
+ * @returns {Promise<Object>} { success, stats: { totalRevenue, totalTransactions, successRate, recentTransactions } }
99
108
  */
100
109
  async getStats() {
101
110
  return this._request('GET', '/api/merchant/stats');
@@ -104,7 +113,37 @@ class GembaPay {
104
113
  // ── Webhooks ─────────────────────────────────────────
105
114
 
106
115
  /**
107
- * Verify webhook signature
116
+ * Verify a webhook's Signature-V2 header (recommended).
117
+ * Header: "t=<unix>,v1=<hex>[,v1=<hex>]", v1 = HMAC-SHA256(secret, "<t>.<raw body>").
118
+ * Rejects timestamps more than `toleranceSec` away from now (replay protection) and accepts any v1
119
+ * (two are sent for 24 h after a secret rotation).
120
+ * @param {string|Buffer} rawBody - Raw request body, exactly as received
121
+ * @param {string} header - Value of the X-GembaPay-Signature-V2 header
122
+ * @param {Object} [options]
123
+ * @param {number} [options.toleranceSec=300]
124
+ * @returns {boolean}
125
+ */
126
+ verifyWebhookV2(rawBody, header, { toleranceSec = SIGNATURE_TOLERANCE_SEC } = {}) {
127
+ if (!this.webhookSecret) {
128
+ throw new GembaPayError('webhookSecret is required for signature verification', null, 'missing_webhook_secret');
129
+ }
130
+ if (typeof header !== 'string' || !header) return false;
131
+ const parts = header.split(',').map((p) => p.trim());
132
+ const t = Number((parts.find((p) => p.startsWith('t=')) || '').slice(2));
133
+ const sigs = parts.filter((p) => p.startsWith('v1=')).map((p) => p.slice(3));
134
+ if (!Number.isInteger(t) || t <= 0 || !sigs.length) return false;
135
+ if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false;
136
+ const body = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody);
137
+ const expected = Buffer.from(crypto.createHmac('sha256', this.webhookSecret).update(`${t}.${body}`).digest('hex'), 'utf8');
138
+ return sigs.some((s) => {
139
+ const got = Buffer.from(s, 'utf8');
140
+ return got.length === expected.length && crypto.timingSafeEqual(got, expected);
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Verify the legacy X-GembaPay-Signature header (no timestamp → no replay protection).
146
+ * Prefer verifyWebhookV2 / parseWebhook, which use Signature-V2 whenever it is present.
108
147
  * @param {string|Buffer} payload - Raw request body
109
148
  * @param {string} signature - Value of x-gembapay-signature header
110
149
  * @returns {boolean} Whether the signature is valid
@@ -136,15 +175,19 @@ class GembaPay {
136
175
  * @param {Object} req - Express/HTTP request object
137
176
  * @returns {Object} Parsed webhook event { event, payment, testMode }
138
177
  */
139
- parseWebhook(req) {
178
+ parseWebhook(req, { requireV2 = false } = {}) {
140
179
  const signature = req.headers['x-gembapay-signature'];
180
+ const signatureV2 = req.headers['x-gembapay-signature-v2'];
141
181
  // Prefer the RAW body — mount the route with express.raw({ type: 'application/json' }).
142
182
  // Falls back to req.rawBody, then a re-serialized parsed body (least reliable).
143
183
  const raw = Buffer.isBuffer(req.body) ? req.body
144
184
  : (req.rawBody != null ? req.rawBody
145
185
  : (typeof req.body === 'string' ? req.body : JSON.stringify(req.body)));
146
186
 
147
- if (!this.verifyWebhook(raw, signature)) {
187
+ // Signature-V2 (timestamped) whenever GembaPay sent it; the legacy header only as a fallback.
188
+ const valid = signatureV2 ? this.verifyWebhookV2(raw, signatureV2)
189
+ : (!requireV2 && this.verifyWebhook(raw, signature));
190
+ if (!valid) {
148
191
  throw new GembaPayError('Invalid webhook signature', 401, 'invalid_signature');
149
192
  }
150
193
 
@@ -158,10 +201,10 @@ class GembaPay {
158
201
  * @param {Function} handler - async function(event) called on valid webhooks
159
202
  * @returns {Function} Express middleware
160
203
  */
161
- webhookHandler(handler) {
204
+ webhookHandler(handler, options = {}) {
162
205
  return async (req, res) => {
163
206
  try {
164
- const event = this.parseWebhook(req);
207
+ const event = this.parseWebhook(req, options);
165
208
  await handler(event);
166
209
  res.status(200).json({ received: true });
167
210
  } catch (err) {
@@ -174,9 +217,181 @@ class GembaPay {
174
217
  };
175
218
  }
176
219
 
220
+ // ── Refunds (API v1) ─────────────────────────────────
221
+
222
+ /**
223
+ * Refund a completed card or PayPal payment — fully or partly. The API key needs the
224
+ * "refunds:write" permission (Dashboard → API Keys).
225
+ * @param {Object} params
226
+ * @param {string} params.orderId - Your order id
227
+ * @param {number|string} [params.amount] - In the payment currency; omit to refund everything left
228
+ * @param {string} [params.reason]
229
+ * @param {Object} [options]
230
+ * @param {string} [options.idempotencyKey] - Pass the SAME key when you retry after a timeout, so the
231
+ * refund cannot happen twice. Default: a new random key (no retry protection).
232
+ * @returns {Promise<Object>} The refund
233
+ */
234
+ async createRefund({ orderId, amount, reason } = {}, { idempotencyKey } = {}) {
235
+ if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
236
+ const body = { orderId };
237
+ if (amount !== undefined && amount !== null) body.amount = amount;
238
+ if (reason) body.reason = reason;
239
+ const res = await this._request('POST', '/api/v1/refunds', body, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
240
+ return res.refund;
241
+ }
242
+
243
+ /**
244
+ * List refunds (newest first; this key's mode only).
245
+ * @param {Object} [params] - { orderId, limit }
246
+ * @returns {Promise<Object[]>}
247
+ */
248
+ async listRefunds({ orderId, limit } = {}) {
249
+ const q = new URLSearchParams();
250
+ if (orderId) q.set('orderId', orderId);
251
+ if (limit) q.set('limit', String(limit));
252
+ const res = await this._request('GET', '/api/v1/refunds' + (q.toString() ? `?${q}` : ''));
253
+ return res.refunds;
254
+ }
255
+
256
+ /** @param {string} refundId @returns {Promise<Object>} */
257
+ async getRefund(refundId) {
258
+ if (!refundId) throw new GembaPayError('refundId is required', null, 'missing_param');
259
+ const res = await this._request('GET', `/api/v1/refunds/${encodeURIComponent(refundId)}`);
260
+ return res.refund;
261
+ }
262
+
263
+ // ── Payment links (API v1) ───────────────────────────
264
+
265
+ /**
266
+ * Create a payment link (paid at https://payment.gembapay.com/link/<token>). The API key needs the
267
+ * "payment_links:write" permission. Test keys create test links, live keys live links.
268
+ * @param {Object} params - { amount?, currency?, description?, methods?, multiUse?, maxUses?,
269
+ * maxTotalAmount?, expiresAt?, customerFields?, merchantNotify? }
270
+ * @param {Object} [options] - { idempotencyKey }
271
+ * @returns {Promise<Object>} The payment link
272
+ */
273
+ async createPaymentLink(params = {}, { idempotencyKey } = {}) {
274
+ const res = await this._request('POST', '/api/v1/payment-links', params, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
275
+ return res.paymentLink;
276
+ }
277
+
278
+ /** @returns {Promise<Object[]>} Payment links of this key's mode */
279
+ async listPaymentLinks() {
280
+ const res = await this._request('GET', '/api/v1/payment-links');
281
+ return res.paymentLinks;
282
+ }
283
+
284
+ /** @param {string} id @returns {Promise<Object>} The link with its completed payments (uses) */
285
+ async getPaymentLink(id) {
286
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
287
+ const res = await this._request('GET', `/api/v1/payment-links/${encodeURIComponent(id)}`);
288
+ return res.paymentLink;
289
+ }
290
+
291
+ /** @param {string} id @param {'active'|'disabled'} status @returns {Promise<Object>} */
292
+ async setPaymentLinkStatus(id, status) {
293
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
294
+ if (!['active', 'disabled'].includes(status)) throw new GembaPayError('status must be "active" or "disabled"', null, 'invalid_param');
295
+ const res = await this._request('PATCH', `/api/v1/payment-links/${encodeURIComponent(id)}`, { status });
296
+ return res.paymentLink;
297
+ }
298
+
299
+ /** Delete a link (its payment history is kept). @param {string} id */
300
+ async deletePaymentLink(id) {
301
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
302
+ return this._request('DELETE', `/api/v1/payment-links/${encodeURIComponent(id)}`);
303
+ }
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
+
177
392
  // ── Internal ─────────────────────────────────────────
178
393
 
179
- _request(method, path, body) {
394
+ _request(method, path, body, extraHeaders = {}) {
180
395
  return new Promise((resolve, reject) => {
181
396
  const url = new URL(this.baseUrl + path);
182
397
 
@@ -189,6 +404,7 @@ class GembaPay {
189
404
  'Authorization': `Bearer ${this.apiKey}`,
190
405
  'Content-Type': 'application/json',
191
406
  'User-Agent': `gembapay-node/${VERSION}`,
407
+ ...extraHeaders,
192
408
  },
193
409
  };
194
410
 
@@ -196,19 +412,28 @@ class GembaPay {
196
412
  let data = '';
197
413
  res.on('data', (chunk) => data += chunk);
198
414
  res.on('end', () => {
415
+ let parsed;
199
416
  try {
200
- const parsed = JSON.parse(data);
417
+ parsed = JSON.parse(data);
418
+ } catch {
419
+ // Not JSON — e.g. the per-IP rate limiter answers 429 with plain text.
201
420
  if (res.statusCode >= 400) {
202
- reject(new GembaPayError(
203
- parsed.message || parsed.error || `HTTP ${res.statusCode}`,
204
- res.statusCode,
205
- parsed.code
206
- ));
207
- } else {
208
- 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));
209
424
  }
210
- } catch {
211
- reject(new GembaPayError(`Invalid response: ${data}`, res.statusCode, 'parse_error'));
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);
212
437
  }
213
438
  });
214
439
  });