gembapay 1.3.0 → 1.4.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/README.md CHANGED
@@ -76,18 +76,23 @@ console.log(status.network); // 'stripe', 'paypal'
76
76
 
77
77
  ### Webhook Verification
78
78
 
79
- > **⚠️ SDK update required.** The live GembaPay backend signs webhooks as **bare hex** (no
80
- > `sha256=` prefix) over the **raw request body**. The current `verifyWebhook`/`webhookHandler`
81
- > in this SDK build expect a `sha256=` prefix and hash the parsed body, so they reject genuine
82
- > webhooks until the SDK is updated. Until then, verify manually against the raw body per
83
- > [docs/webhooks.md](../../docs/webhooks.md#signature-verification). Subscription cycles arrive as
84
- > `subscription.payment` (flat payload, no `orderId`), not `payment.completed`.
79
+ GembaPay signs every webhook. `parseWebhook` and `webhookHandler` verify the timestamped
80
+ **`X-GembaPay-Signature-V2`** header (`t=<unix>,v1=<hex>`, HMAC-SHA256 over `"<t>.<raw body>"`) and
81
+ reject requests older than 5 minutes — a copied webhook cannot be replayed. Only when a request has no
82
+ V2 header do they fall back to the legacy `X-GembaPay-Signature` (bare hex over the raw body); pass
83
+ `{ requireV2: true }` to refuse legacy-only requests. `verifyWebhookV2(rawBody, header)` and
84
+ `verifyWebhook(rawBody, signature)` are available for manual checks. Mount the webhook route
85
+ with `express.raw({ type: 'application/json' })` so the SDK sees the exact bytes that were signed
86
+ (a parsed `express.json()` body is re-serialized as a fallback, which is less reliable).
87
+ Subscription cycles arrive as `subscription.payment` (flat payload, no `orderId`), not
88
+ `payment.completed`. Each `payment.completed` also carries `payment.paymentMethod`
89
+ (`card`, `apple_pay`, `google_pay`, `link`, or `null` for PayPal).
85
90
 
86
91
  ```javascript
87
92
  const express = require('express');
88
93
  const app = express();
89
94
 
90
- app.post('/webhooks/gembapay', express.json(),
95
+ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
91
96
  gembapay.webhookHandler(async (event) => {
92
97
  if (event.event === 'payment.completed') {
93
98
  console.log(`✓ Order ${event.payment.orderId} paid`);
@@ -101,20 +106,72 @@ app.post('/webhooks/gembapay', express.json(),
101
106
  Or verify manually:
102
107
 
103
108
  ```javascript
104
- app.post('/webhooks/gembapay', express.json(), (req, res) => {
109
+ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }), (req, res) => {
105
110
  const signature = req.headers['x-gembapay-signature'];
106
-
111
+
112
+ // req.body is the raw Buffer here - verify first, parse after
107
113
  if (!gembapay.verifyWebhook(req.body, signature)) {
108
114
  return res.status(401).send('Invalid signature');
109
115
  }
110
-
111
- const { event, payment, testMode } = req.body;
116
+
117
+ const { event, payment } = JSON.parse(req.body.toString('utf8'));
112
118
  // Process event...
113
119
 
114
120
  res.json({ received: true });
115
121
  });
116
122
  ```
117
123
 
124
+ Which events you receive is set in the dashboard (Webhooks): `payment.completed` (always),
125
+ `payment.refunded`, `payment.failed`, `payment.expired`, `dispute.created`, `dispute.closed` and
126
+ `subscription.*`. Every event has an `eventId` — process each one once. Payloads and handling advice for
127
+ each event: [docs/webhooks.md](../../docs/webhooks.md).
128
+
129
+ ```javascript
130
+ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
131
+ gembapay.webhookHandler(async (event) => {
132
+ if (event.test) return; // dashboard "Send test"
133
+ switch (event.event) {
134
+ case 'payment.completed': return markPaid(event.payment.orderId);
135
+ case 'payment.refunded': return recordRefund(event.refund, event.payment.fullyRefunded);
136
+ case 'payment.expired': return cancelIfUnpaid(event.payment.orderId);
137
+ case 'dispute.created': return holdOrder(event.dispute.orderId);
138
+ }
139
+ })
140
+ );
141
+ ```
142
+
143
+ ### Refunds
144
+
145
+ Full or partial refunds of card (incl. Apple Pay / Google Pay) and PayPal payments. The API key needs
146
+ the **`refunds:write`** permission (Dashboard → API Keys → Permissions).
147
+
148
+ ```javascript
149
+ // partial refund — pass your own idempotency key and reuse it if you retry after a timeout
150
+ const refund = await gembapay.createRefund(
151
+ { orderId: 'ORDER-123', amount: '5.00', reason: 'One item returned' },
152
+ { idempotencyKey: `refund-ORDER-123-item-7` }
153
+ );
154
+ console.log(refund.id, refund.status); // 'succeeded' | 'pending'
155
+
156
+ await gembapay.createRefund({ orderId: 'ORDER-123' }); // everything still refundable
157
+ const refunds = await gembapay.listRefunds({ orderId: 'ORDER-123' });
158
+ ```
159
+
160
+ ### Payment Links
161
+
162
+ Create hosted payment links from your own system. The API key needs **`payment_links:write`**; test
163
+ keys create test links, live keys live links.
164
+
165
+ ```javascript
166
+ const link = await gembapay.createPaymentLink({
167
+ amount: 49.9, currency: 'EUR', description: 'Workshop ticket', multiUse: true, maxUses: 100,
168
+ });
169
+ console.log(`https://payment.gembapay.com/link/${link.token}`);
170
+
171
+ await gembapay.setPaymentLinkStatus(link.id, 'disabled');
172
+ await gembapay.deletePaymentLink(link.id);
173
+ ```
174
+
118
175
  ### Transactions & Stats
119
176
 
120
177
  ```javascript
@@ -144,7 +201,6 @@ const gembapay = new GembaPay({
144
201
  console.log(gembapay.isTestMode); // true
145
202
  ```
146
203
 
147
- Claim free test tokens at [Developer Resources](https://gembapay.com/developers).
148
204
 
149
205
  ## Express.js Example
150
206
 
@@ -170,8 +226,8 @@ app.post('/api/checkout', express.json(), async (req, res) => {
170
226
  }
171
227
  });
172
228
 
173
- // Webhook endpoint
174
- app.post('/webhooks/gembapay', express.json(),
229
+ // Webhook endpoint - raw body, so the signature is checked on the exact bytes GembaPay signed
230
+ app.post('/webhooks/gembapay', express.raw({ type: 'application/json' }),
175
231
  gembapay.webhookHandler(async (event) => {
176
232
  if (event.event === 'payment.completed') {
177
233
  await fulfillOrder(event.payment.orderId);
@@ -202,9 +258,16 @@ app.listen(3000);
202
258
  | `getPaymentStatus(orderId)` | Check payment status |
203
259
  | `listTransactions(params?)` | List merchant transactions |
204
260
  | `getStats()` | Get merchant statistics |
205
- | `verifyWebhook(payload, signature)` | Verify webhook signature |
206
- | `parseWebhook(req)` | Parse & verify Express request |
207
- | `webhookHandler(fn)` | Express webhook middleware |
261
+ | `createRefund(params, { idempotencyKey }?)` | Full / partial refund (`refunds:write`) |
262
+ | `listRefunds({ orderId?, limit? })` | List refunds |
263
+ | `getRefund(id)` | Get a refund |
264
+ | `createPaymentLink(params, { idempotencyKey }?)` | Create a payment link (`payment_links:write`) |
265
+ | `listPaymentLinks()` / `getPaymentLink(id)` | Read payment links |
266
+ | `setPaymentLinkStatus(id, status)` / `deletePaymentLink(id)` | Disable / enable / delete a link |
267
+ | `verifyWebhookV2(rawBody, header, { toleranceSec }?)` | Verify `X-GembaPay-Signature-V2` |
268
+ | `verifyWebhook(rawBody, signature)` | Verify the legacy signature |
269
+ | `parseWebhook(req, { requireV2 }?)` | Parse & verify an Express request (V2 when present) |
270
+ | `webhookHandler(fn, { requireV2 }?)` | Express webhook middleware |
208
271
 
209
272
  ## Fee Structure
210
273
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gembapay",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "GembaPay \u2014 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",
package/src/index.d.ts CHANGED
@@ -34,7 +34,7 @@ declare module 'gembapay' {
34
34
 
35
35
  export interface PaymentStatus {
36
36
  orderId: string;
37
- status: 'pending' | 'processing' | 'confirmed' | 'completed' | 'failed' | 'expired';
37
+ status: 'pending' | 'processing' | 'confirmed' | 'completed' | 'failed' | 'expired' | 'refunded';
38
38
  amountUsd: string;
39
39
  network: 'stripe' | 'paypal';
40
40
  paymentProvider: 'stripe' | 'paypal';
@@ -48,22 +48,190 @@ declare module 'gembapay' {
48
48
  /** Stripe may add other values over time - treat unknown ones like 'card'. */
49
49
  export type PaymentMethod = 'card' | 'apple_pay' | 'google_pay' | 'link' | (string & {});
50
50
 
51
- export interface WebhookEvent {
52
- event: 'payment.completed' | 'payment.failed';
51
+ export type WebhookEventType =
52
+ | 'payment.completed' | 'payment.refunded' | 'payment.failed' | 'payment.expired'
53
+ | 'dispute.created' | 'dispute.closed'
54
+ | 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled';
55
+
56
+ /** Fields every webhook carries. */
57
+ interface WebhookEnvelope {
58
+ /** Unique per event — use it as your idempotency key. */
59
+ eventId: string;
60
+ /** true for test-mode payments (test key, test cards, PayPal sandbox) */
53
61
  testMode?: boolean;
62
+ /** true only for dashboard "Send test" samples — never act on them */
63
+ test?: boolean;
64
+ timestamp: string;
65
+ }
66
+
67
+ export interface PaymentCompletedEvent extends WebhookEnvelope {
68
+ event: 'payment.completed';
54
69
  payment: {
55
70
  orderId: string;
56
- reference?: string;
57
- network: string;
71
+ amount: number;
72
+ currency: string;
73
+ amountOriginal?: number | null;
74
+ currencyOriginal?: string | null;
58
75
  usdAmount: number;
59
- tokenAmount?: string;
60
- paymentProvider?: string;
76
+ exchangeRate?: number | null;
77
+ status: 'completed';
78
+ /** Provider payment id: Stripe PaymentIntent (pi_…) or PayPal capture id */
79
+ txHash: string;
80
+ network: string;
81
+ paymentProvider: 'stripe' | 'paypal' | string;
61
82
  /** How the customer paid. null for PayPal and payments recorded before 2026-10-21. */
62
- paymentMethod?: PaymentMethod | null;
83
+ paymentMethod: PaymentMethod | null;
84
+ customerAddress?: string;
85
+ timestamp?: string;
63
86
  };
87
+ }
88
+
89
+ export interface Refund {
90
+ id: string;
91
+ orderId: string;
92
+ amount: number;
93
+ currency: string;
94
+ status: 'succeeded' | 'pending' | 'failed';
95
+ reason: string | null;
96
+ source: 'api' | 'dashboard' | 'provider';
97
+ provider: 'stripe' | 'paypal';
98
+ providerRefundId: string | null;
99
+ failureReason: string | null;
100
+ testMode: boolean;
101
+ createdAt: string;
102
+ }
103
+
104
+ interface PaymentSummary {
105
+ orderId: string;
106
+ amount: number;
107
+ currency: string;
108
+ paymentProvider: 'stripe' | 'paypal' | string;
109
+ paymentMethod: PaymentMethod | null;
110
+ /** Provider payment id (pi_… / PayPal capture id) */
111
+ reference: string;
112
+ }
113
+
114
+ export interface PaymentRefundedEvent extends WebhookEnvelope {
115
+ event: 'payment.refunded';
116
+ refund: Refund;
117
+ payment: PaymentSummary & { refundedTotal: number; remaining: number; fullyRefunded: boolean };
118
+ }
119
+
120
+ export interface PaymentFailedEvent extends WebhookEnvelope {
121
+ event: 'payment.failed';
122
+ payment: {
123
+ orderId: string;
124
+ amount: number;
125
+ currency: string;
126
+ paymentProvider: 'stripe' | 'paypal' | string;
127
+ paymentMethod: PaymentMethod | null;
128
+ failureCode: string | null;
129
+ failureMessage: string | null;
130
+ /** Always false: the customer may retry until expiresAt */
131
+ final: false;
132
+ expiresAt: string | null;
133
+ };
134
+ }
135
+
136
+ export interface PaymentExpiredEvent extends WebhookEnvelope {
137
+ event: 'payment.expired';
138
+ payment: { orderId: string; amount: number; currency: string; status: 'expired'; expiresAt: string };
139
+ }
140
+
141
+ export interface Dispute {
142
+ id: string;
143
+ provider: 'stripe' | 'paypal';
144
+ providerDisputeId: string;
145
+ orderId: string;
146
+ amount: number | null;
147
+ currency: string | null;
148
+ reason: string | null;
149
+ status: string;
150
+ outcome: 'won' | 'lost' | 'other' | null;
151
+ createdAt: string;
152
+ closedAt: string | null;
153
+ }
154
+
155
+ export interface DisputeEvent extends WebhookEnvelope {
156
+ event: 'dispute.created' | 'dispute.closed';
157
+ dispute: Dispute;
158
+ payment: PaymentSummary;
159
+ }
160
+
161
+ /** Subscription events use a flat payload (no `payment`, no orderId). */
162
+ export interface SubscriptionEvent {
163
+ event: 'subscription.activated' | 'subscription.payment' | 'subscription.payment_failed' | 'subscription.canceled';
164
+ eventId: string;
165
+ subscriptionId: string;
166
+ providerSubscriptionId: string | null;
167
+ planId: string | null;
168
+ planToken: string | null;
169
+ customerEmail: string | null;
170
+ status: string | null;
171
+ isTestMode: boolean;
172
+ amount?: number;
173
+ currency?: string;
174
+ paymentMethod?: PaymentMethod | null;
175
+ test?: boolean;
64
176
  timestamp: string;
65
177
  }
66
178
 
179
+ export type WebhookEvent =
180
+ | PaymentCompletedEvent | PaymentRefundedEvent | PaymentFailedEvent | PaymentExpiredEvent
181
+ | DisputeEvent | SubscriptionEvent;
182
+
183
+ export interface CreateRefundParams {
184
+ orderId: string;
185
+ /** In the payment currency; omit to refund everything still refundable */
186
+ amount?: number | string;
187
+ reason?: string;
188
+ }
189
+
190
+ export interface IdempotencyOptions {
191
+ /** Reuse the same key when retrying after a timeout so the operation cannot happen twice. */
192
+ idempotencyKey?: string;
193
+ }
194
+
195
+ export interface CustomerField { enabled: boolean; required: boolean }
196
+
197
+ export interface CreatePaymentLinkParams {
198
+ /** Fixed amount; omit/null to let the payer choose */
199
+ amount?: number | null;
200
+ currency?: string;
201
+ description?: string;
202
+ methods?: ('stripe' | 'paypal')[];
203
+ multiUse?: boolean;
204
+ maxUses?: number | null;
205
+ maxTotalAmount?: number | null;
206
+ expiresAt?: string | null;
207
+ customerFields?: Partial<Record<'name' | 'email' | 'phone' | 'note', CustomerField>>;
208
+ merchantNotify?: boolean;
209
+ }
210
+
211
+ export interface PaymentLink {
212
+ id: string;
213
+ token: string;
214
+ amount: number | null;
215
+ openAmount: boolean;
216
+ currency: string;
217
+ description: string | null;
218
+ methods: string[];
219
+ multiUse: boolean;
220
+ maxUses: number | null;
221
+ maxTotalAmount: number | null;
222
+ expiresAt: string | null;
223
+ merchantNotify: boolean;
224
+ isTestMode: boolean;
225
+ mode: 'test' | 'live';
226
+ status: string;
227
+ rawStatus: 'active' | 'disabled';
228
+ usedCount: number;
229
+ totalCollected: number;
230
+ createdAt: string;
231
+ uses?: any[];
232
+ [key: string]: any;
233
+ }
234
+
67
235
  export interface StatsResponse {
68
236
  [key: string]: any;
69
237
  }
@@ -99,14 +267,29 @@ declare module 'gembapay' {
99
267
  /** Get merchant statistics */
100
268
  getStats(): Promise<StatsResponse>;
101
269
 
102
- /** Verify webhook signature */
270
+ /** Refund a payment fully or partly (key needs "refunds:write") */
271
+ createRefund(params: CreateRefundParams, options?: IdempotencyOptions): Promise<Refund>;
272
+ listRefunds(params?: { orderId?: string; limit?: number }): Promise<Refund[]>;
273
+ getRefund(refundId: string): Promise<Refund>;
274
+
275
+ /** Payment links (key needs "payment_links:write" to create/change) */
276
+ createPaymentLink(params: CreatePaymentLinkParams, options?: IdempotencyOptions): Promise<PaymentLink>;
277
+ listPaymentLinks(): Promise<PaymentLink[]>;
278
+ getPaymentLink(id: string): Promise<PaymentLink>;
279
+ setPaymentLinkStatus(id: string, status: 'active' | 'disabled'): Promise<PaymentLink>;
280
+ deletePaymentLink(id: string): Promise<{ success: boolean; ok: boolean }>;
281
+
282
+ /** Verify the X-GembaPay-Signature-V2 header (timestamped, recommended) */
283
+ verifyWebhookV2(rawBody: string | Buffer, header: string, options?: { toleranceSec?: number }): boolean;
284
+
285
+ /** Verify the legacy X-GembaPay-Signature header (no replay protection) */
103
286
  verifyWebhook(payload: string | Buffer | object, signature: string): boolean;
104
287
 
105
- /** Parse and verify a webhook request */
106
- parseWebhook(req: { headers: Record<string, string>; body: any }): WebhookEvent;
288
+ /** Parse and verify a webhook request — uses Signature-V2 when present */
289
+ parseWebhook(req: { headers: Record<string, string | undefined>; body: any; rawBody?: any }, options?: { requireV2?: boolean }): WebhookEvent;
107
290
 
108
- /** Express middleware for webhook handling */
109
- webhookHandler(handler: (event: WebhookEvent) => Promise<void>): (req: any, res: any) => Promise<void>;
291
+ /** Express middleware for webhook handling (mount with express.raw) */
292
+ webhookHandler(handler: (event: WebhookEvent) => Promise<void>, options?: { requireV2?: boolean }): (req: any, res: any) => Promise<void>;
110
293
  }
111
294
 
112
295
  export default GembaPay;
package/src/index.js CHANGED
@@ -4,7 +4,8 @@ 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.4.0';
8
+ const SIGNATURE_TOLERANCE_SEC = 300;
8
9
 
9
10
  class GembaPayError extends Error {
10
11
  constructor(message, statusCode, code) {
@@ -104,7 +105,37 @@ class GembaPay {
104
105
  // ── Webhooks ─────────────────────────────────────────
105
106
 
106
107
  /**
107
- * Verify webhook signature
108
+ * Verify a webhook's Signature-V2 header (recommended).
109
+ * Header: "t=<unix>,v1=<hex>[,v1=<hex>]", v1 = HMAC-SHA256(secret, "<t>.<raw body>").
110
+ * Rejects timestamps more than `toleranceSec` away from now (replay protection) and accepts any v1
111
+ * (two are sent for 24 h after a secret rotation).
112
+ * @param {string|Buffer} rawBody - Raw request body, exactly as received
113
+ * @param {string} header - Value of the X-GembaPay-Signature-V2 header
114
+ * @param {Object} [options]
115
+ * @param {number} [options.toleranceSec=300]
116
+ * @returns {boolean}
117
+ */
118
+ verifyWebhookV2(rawBody, header, { toleranceSec = SIGNATURE_TOLERANCE_SEC } = {}) {
119
+ if (!this.webhookSecret) {
120
+ throw new GembaPayError('webhookSecret is required for signature verification', null, 'missing_webhook_secret');
121
+ }
122
+ if (typeof header !== 'string' || !header) return false;
123
+ const parts = header.split(',').map((p) => p.trim());
124
+ const t = Number((parts.find((p) => p.startsWith('t=')) || '').slice(2));
125
+ const sigs = parts.filter((p) => p.startsWith('v1=')).map((p) => p.slice(3));
126
+ if (!Number.isInteger(t) || t <= 0 || !sigs.length) return false;
127
+ if (Math.abs(Math.floor(Date.now() / 1000) - t) > toleranceSec) return false;
128
+ const body = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody);
129
+ const expected = Buffer.from(crypto.createHmac('sha256', this.webhookSecret).update(`${t}.${body}`).digest('hex'), 'utf8');
130
+ return sigs.some((s) => {
131
+ const got = Buffer.from(s, 'utf8');
132
+ return got.length === expected.length && crypto.timingSafeEqual(got, expected);
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Verify the legacy X-GembaPay-Signature header (no timestamp → no replay protection).
138
+ * Prefer verifyWebhookV2 / parseWebhook, which use Signature-V2 whenever it is present.
108
139
  * @param {string|Buffer} payload - Raw request body
109
140
  * @param {string} signature - Value of x-gembapay-signature header
110
141
  * @returns {boolean} Whether the signature is valid
@@ -136,15 +167,19 @@ class GembaPay {
136
167
  * @param {Object} req - Express/HTTP request object
137
168
  * @returns {Object} Parsed webhook event { event, payment, testMode }
138
169
  */
139
- parseWebhook(req) {
170
+ parseWebhook(req, { requireV2 = false } = {}) {
140
171
  const signature = req.headers['x-gembapay-signature'];
172
+ const signatureV2 = req.headers['x-gembapay-signature-v2'];
141
173
  // Prefer the RAW body — mount the route with express.raw({ type: 'application/json' }).
142
174
  // Falls back to req.rawBody, then a re-serialized parsed body (least reliable).
143
175
  const raw = Buffer.isBuffer(req.body) ? req.body
144
176
  : (req.rawBody != null ? req.rawBody
145
177
  : (typeof req.body === 'string' ? req.body : JSON.stringify(req.body)));
146
178
 
147
- if (!this.verifyWebhook(raw, signature)) {
179
+ // Signature-V2 (timestamped) whenever GembaPay sent it; the legacy header only as a fallback.
180
+ const valid = signatureV2 ? this.verifyWebhookV2(raw, signatureV2)
181
+ : (!requireV2 && this.verifyWebhook(raw, signature));
182
+ if (!valid) {
148
183
  throw new GembaPayError('Invalid webhook signature', 401, 'invalid_signature');
149
184
  }
150
185
 
@@ -158,10 +193,10 @@ class GembaPay {
158
193
  * @param {Function} handler - async function(event) called on valid webhooks
159
194
  * @returns {Function} Express middleware
160
195
  */
161
- webhookHandler(handler) {
196
+ webhookHandler(handler, options = {}) {
162
197
  return async (req, res) => {
163
198
  try {
164
- const event = this.parseWebhook(req);
199
+ const event = this.parseWebhook(req, options);
165
200
  await handler(event);
166
201
  res.status(200).json({ received: true });
167
202
  } catch (err) {
@@ -174,9 +209,94 @@ class GembaPay {
174
209
  };
175
210
  }
176
211
 
212
+ // ── Refunds (API v1) ─────────────────────────────────
213
+
214
+ /**
215
+ * Refund a completed card or PayPal payment — fully or partly. The API key needs the
216
+ * "refunds:write" permission (Dashboard → API Keys).
217
+ * @param {Object} params
218
+ * @param {string} params.orderId - Your order id
219
+ * @param {number|string} [params.amount] - In the payment currency; omit to refund everything left
220
+ * @param {string} [params.reason]
221
+ * @param {Object} [options]
222
+ * @param {string} [options.idempotencyKey] - Pass the SAME key when you retry after a timeout, so the
223
+ * refund cannot happen twice. Default: a new random key (no retry protection).
224
+ * @returns {Promise<Object>} The refund
225
+ */
226
+ async createRefund({ orderId, amount, reason } = {}, { idempotencyKey } = {}) {
227
+ if (!orderId) throw new GembaPayError('orderId is required', null, 'missing_param');
228
+ const body = { orderId };
229
+ if (amount !== undefined && amount !== null) body.amount = amount;
230
+ if (reason) body.reason = reason;
231
+ const res = await this._request('POST', '/api/v1/refunds', body, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
232
+ return res.refund;
233
+ }
234
+
235
+ /**
236
+ * List refunds (newest first; this key's mode only).
237
+ * @param {Object} [params] - { orderId, limit }
238
+ * @returns {Promise<Object[]>}
239
+ */
240
+ async listRefunds({ orderId, limit } = {}) {
241
+ const q = new URLSearchParams();
242
+ if (orderId) q.set('orderId', orderId);
243
+ if (limit) q.set('limit', String(limit));
244
+ const res = await this._request('GET', '/api/v1/refunds' + (q.toString() ? `?${q}` : ''));
245
+ return res.refunds;
246
+ }
247
+
248
+ /** @param {string} refundId @returns {Promise<Object>} */
249
+ async getRefund(refundId) {
250
+ if (!refundId) throw new GembaPayError('refundId is required', null, 'missing_param');
251
+ const res = await this._request('GET', `/api/v1/refunds/${encodeURIComponent(refundId)}`);
252
+ return res.refund;
253
+ }
254
+
255
+ // ── Payment links (API v1) ───────────────────────────
256
+
257
+ /**
258
+ * Create a payment link (paid at https://payment.gembapay.com/link/<token>). The API key needs the
259
+ * "payment_links:write" permission. Test keys create test links, live keys live links.
260
+ * @param {Object} params - { amount?, currency?, description?, methods?, multiUse?, maxUses?,
261
+ * maxTotalAmount?, expiresAt?, customerFields?, merchantNotify? }
262
+ * @param {Object} [options] - { idempotencyKey }
263
+ * @returns {Promise<Object>} The payment link
264
+ */
265
+ async createPaymentLink(params = {}, { idempotencyKey } = {}) {
266
+ const res = await this._request('POST', '/api/v1/payment-links', params, { 'Idempotency-Key': idempotencyKey || crypto.randomUUID() });
267
+ return res.paymentLink;
268
+ }
269
+
270
+ /** @returns {Promise<Object[]>} Payment links of this key's mode */
271
+ async listPaymentLinks() {
272
+ const res = await this._request('GET', '/api/v1/payment-links');
273
+ return res.paymentLinks;
274
+ }
275
+
276
+ /** @param {string} id @returns {Promise<Object>} The link with its completed payments (uses) */
277
+ async getPaymentLink(id) {
278
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
279
+ const res = await this._request('GET', `/api/v1/payment-links/${encodeURIComponent(id)}`);
280
+ return res.paymentLink;
281
+ }
282
+
283
+ /** @param {string} id @param {'active'|'disabled'} status @returns {Promise<Object>} */
284
+ async setPaymentLinkStatus(id, status) {
285
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
286
+ if (!['active', 'disabled'].includes(status)) throw new GembaPayError('status must be "active" or "disabled"', null, 'invalid_param');
287
+ const res = await this._request('PATCH', `/api/v1/payment-links/${encodeURIComponent(id)}`, { status });
288
+ return res.paymentLink;
289
+ }
290
+
291
+ /** Delete a link (its payment history is kept). @param {string} id */
292
+ async deletePaymentLink(id) {
293
+ if (!id) throw new GembaPayError('id is required', null, 'missing_param');
294
+ return this._request('DELETE', `/api/v1/payment-links/${encodeURIComponent(id)}`);
295
+ }
296
+
177
297
  // ── Internal ─────────────────────────────────────────
178
298
 
179
- _request(method, path, body) {
299
+ _request(method, path, body, extraHeaders = {}) {
180
300
  return new Promise((resolve, reject) => {
181
301
  const url = new URL(this.baseUrl + path);
182
302
 
@@ -189,6 +309,7 @@ class GembaPay {
189
309
  'Authorization': `Bearer ${this.apiKey}`,
190
310
  'Content-Type': 'application/json',
191
311
  'User-Agent': `gembapay-node/${VERSION}`,
312
+ ...extraHeaders,
192
313
  },
193
314
  };
194
315