@thepayulink/server 1.0.0 → 2.0.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.
Files changed (3) hide show
  1. package/README.md +75 -87
  2. package/package.json +5 -5
  3. package/src/index.js +143 -63
package/README.md CHANGED
@@ -1,10 +1,12 @@
1
1
  # @thepayulink/server
2
2
 
3
- Server-side SDK for Elite Yatra / PayuLink. Create orders with a **fixed amount**,
4
- check payment status, and verify signatures & webhooks — all with your secret key.
5
- This is the backend half of the checkout, analogous to the `razorpay` Node SDK.
3
+ Backend SDK for the [PayuLink](https://payulink.io) Checkout API. Create orders
4
+ with a **server-fixed amount**, check status, and verify payment signatures and
5
+ webhooks. This is the backend half of the checkout, analogous to the `razorpay`
6
+ Node SDK.
6
7
 
7
- > The **secret key never leaves your backend.** The client SDK only ever receives an `order_id`.
8
+ > Your **`key_secret` never leaves your backend.** The client SDK only ever
9
+ > receives an `order_id`.
8
10
 
9
11
  ## Install
10
12
 
@@ -17,118 +19,104 @@ Node 18+ (uses global `fetch`). Works with `import` and `require`.
17
19
  ## Quick start
18
20
 
19
21
  ```js
20
- import Payulink from '@thepayulink/server';
22
+ import PayuLink, { rupees } from '@thepayulink/server';
21
23
 
22
- const ey = new Payulink({
23
- keyId: process.env.PAYULINK_PUBLISHABLE_KEY, // pl_pk_(optional)
24
- keySecret: process.env.PAYULINK_SECRET_KEY, // pl_sk_… (required, backend only)
25
- apiBase: 'https://eliteyatra.vip',
24
+ const pl = new PayuLink({
25
+ keyId: process.env.PAYULINK_KEY_ID, // pl_live_/ pl_test_…
26
+ keySecret: process.env.PAYULINK_KEY_SECRET, // backend only never ship this
26
27
  });
27
28
 
28
- // 1) Create an order for the TRUE amount (computed on your server).
29
- const order = await ey.orders.create({
30
- amount: 19900, // rupees
31
- item: 'Kailash Mansarovar Yatra 2 travellers',
32
- customer: { name: 'Asha', mobile: '9876543210' },
29
+ // 1) Create an order for the TRUE amount, computed on your server.
30
+ const order = await pl.orders.create({
31
+ amount: rupees(199.5), // PAISE — 19950. rupees() keeps you honest.
32
+ receipt: 'booking_1042', // your reference; also your idempotency key
33
+ notes: { packageId: 'kailash' },
33
34
  });
34
- // -> { order_id, key_id, amount, item, status: 'created' }
35
+ // -> { id: 'order_…', amount: 19950, currency: 'INR', status: 'created', }
35
36
 
36
- // 2) Send order.order_id to your client open it in the client SDK.
37
+ // 2) Hand order.id to the client SDK (@thepayulink/checkout) with your key_id.
37
38
 
38
- // 3) Later, confirm the payment authoritatively before fulfilment.
39
- const status = await ey.orders.fetch(order.order_id);
40
- if (status.paid) {
41
- // deliver the booking — this reflects PayuLink's webhook-verified status
42
- }
43
- ```
44
-
45
- ### Express example
46
-
47
- ```js
48
- import express from 'express';
49
- import Payulink from '@thepayulink/server';
50
-
51
- const ey = new Payulink({ keySecret: process.env.PAYULINK_SECRET_KEY });
52
- const app = express();
53
- app.use(express.json());
54
-
55
- // Client asks your backend to start a payment.
56
- app.post('/create-order', async (req, res) => {
57
- const pkg = await db.getPackage(req.body.packageId); // trusted price
58
- const order = await ey.orders.create({
59
- amount: pkg.bookingAmount * (req.body.travellers || 1),
60
- item: pkg.title,
61
- customer: req.body.customer,
62
- });
63
- res.json({ orderId: order.order_id, keyId: order.key_id });
64
- });
65
-
66
- // Client reports success → confirm before trusting it.
67
- app.post('/confirm', async (req, res) => {
68
- const s = await ey.orders.fetch(req.body.orderId);
69
- res.json({ paid: s.paid, utr: s.utr });
39
+ // 3) Verify the handoff before you fulfil.
40
+ app.post('/verify', express.json(), (req, res) => {
41
+ if (!pl.verifyPaymentSignature(req.body)) return res.status(400).send('bad signature');
42
+ fulfil(req.body.payulink_order_id);
43
+ res.sendStatus(200);
70
44
  });
71
45
  ```
72
46
 
73
- ## Verifying a payment
74
-
75
- Two equivalent ways, pick one:
47
+ ## Amounts are in paise
76
48
 
77
- **A. Fetch the order (simplest, always correct):**
49
+ `19950` is ₹199.50 same convention as Razorpay. Use the `rupees()` helper and
50
+ you can't get the factor of 100 wrong:
78
51
 
79
52
  ```js
80
- const s = await ey.orders.fetch(orderId);
81
- if (s.paid) { /* confirmed */ }
53
+ import { rupees, toRupees } from '@thepayulink/server';
54
+ rupees(199.5); // 19950
55
+ toRupees(19950); // 199.5
82
56
  ```
83
57
 
84
- **B. Verify the signature from the client success callback (Razorpay-style):**
58
+ ## API
85
59
 
86
- The client success payload includes `{ order_id, utr, signature }`. Verify it:
60
+ | Method | Returns | Purpose |
61
+ | --- | --- | --- |
62
+ | `orders.create({ amount, currency?, receipt?, notes? })` | order | Create an amount-fixed order. |
63
+ | `orders.fetch(orderId)` | order | Authoritative status. |
64
+ | `orders.isPaid(orderId)` | boolean | Convenience. |
65
+ | `verifyPaymentSignature({ payulink_order_id, payulink_payment_id, payulink_signature })` | boolean | Verify the client success handoff. |
66
+ | `webhooks.constructEvent(rawBody, headers)` | event | Verify + parse a webhook (throws if invalid or stale). |
87
67
 
88
- ```js
89
- const ok = ey.verifyPaymentSignature({ order_id, utr, signature });
90
- if (ok) { /* authentic success */ }
91
- ```
68
+ ### Idempotency
92
69
 
93
- ## Webhooks
70
+ `receipt` is unique per merchant. Reusing one returns the **same** order instead
71
+ of creating a second — so a double-clicked button or a retried request can't
72
+ charge twice. Reusing it with a *different* amount is a `409`.
94
73
 
95
- Set `PAYULINK_MERCHANT_WEBHOOK_URL` on the pay server to your endpoint. It receives
96
- signed events; verify with the raw body and the `x-payulink-signature` header:
74
+ ### Signatures
75
+
76
+ `signature = HMAC_SHA256(order_id + "|" + payment_id, key_secret)` — the same
77
+ check as Razorpay's `razorpay_signature`. Only someone holding your `key_secret`
78
+ could have produced it, which is why the browser callback alone is never proof.
79
+
80
+ ### Webhooks
97
81
 
98
82
  ```js
99
- // Use a raw body parser on this route so the signature matches byte-for-byte.
100
- app.post('/webhooks/eliteyatra', express.raw({ type: '*/*' }), (req, res) => {
83
+ app.post('/webhooks/payulink', express.raw({ type: '*/*' }), (req, res) => {
101
84
  let event;
102
85
  try {
103
- event = ey.webhooks.constructEvent(req.body, req.get('x-payulink-signature'));
86
+ event = pl.webhooks.constructEvent(req.body, req.headers); // throws if bad or stale
104
87
  } catch (e) {
105
- return res.status(400).send('Invalid signature');
106
- }
107
-
108
- if (event.event === 'payin.verified') {
109
- // event.data: { order_id, status, utr, amount, item }
110
- fulfilBooking(event.data.order_id);
88
+ return res.status(400).send(e.message);
111
89
  }
112
- res.sendStatus(200);
90
+ if (event.event_type === 'payin.verified') fulfil(event.data.merchant_order_no);
91
+ res.sendStatus(200); // 2xx = delivered; anything else is retried
113
92
  });
114
93
  ```
115
94
 
116
- Events: `payin.verified` (paid), `payin.failed`, `payin.expired`, `payin.cancelled`.
95
+ Pass the **raw** body a re-serialised object won't match the signature.
96
+ `constructEvent` also rejects timestamps outside ±5 minutes, so a captured
97
+ webhook can't be replayed later. Deliveries retry 8 times over ~30h, so
98
+ **dedupe on `X-PayuLink-Event-Id`**.
117
99
 
118
- ## API
100
+ ## Errors
119
101
 
120
- | Method | Returns | Notes |
121
- | --- | --- | --- |
122
- | `orders.create({ amount, item?, customer? })` | `Order` | Amount is fixed server-side. |
123
- | `orders.fetch(orderId)` | `OrderStatus` | Authoritative status; `.paid` boolean. |
124
- | `orders.isPaid(orderId)` | `boolean` | Convenience. |
125
- | `payments.fetch(orderId)` | `OrderStatus` | Alias of `orders.fetch`. |
126
- | `verifyPaymentSignature({ order_id, utr, signature })` | `boolean` | Verify client success handoff. |
127
- | `webhooks.constructEvent(rawBody, signature)` | `WebhookEvent` | Throws on bad signature. |
128
- | `webhooks.verify(rawBody, signature)` | `boolean` | Non-throwing check. |
102
+ Failures throw `PayuLinkError` with `.status`, `.code` and `.body`:
103
+
104
+ ```js
105
+ import { PayuLinkError } from '@thepayulink/server';
106
+ try { await pl.orders.create({ amount: 5 }); }
107
+ catch (e) { if (e instanceof PayuLinkError) console.error(e.code, e.message); }
108
+ ```
109
+
110
+ ## Upgrading from 1.x
129
111
 
130
- Errors throw `PayulinkError` with `.status` and `.body`.
112
+ 1.x talked to a self-hosted proxy, used `pl_sk_…` keys and **rupee** amounts.
131
113
 
132
- ## License
114
+ | 1.x | 2.x |
115
+ | --- | --- |
116
+ | `new Payulink({ keySecret: 'pl_sk_…' })` | `new PayuLink({ keyId: 'pl_live_…', keySecret })` |
117
+ | `amount: 19900` (rupees) | `amount: rupees(199)` (paise) |
118
+ | `order.order_id` | `order.id` |
119
+ | `verifyPaymentSignature({ order_id, utr, signature })` | `verifyPaymentSignature({ payulink_order_id, payulink_payment_id, payulink_signature })` |
120
+ | `webhooks.constructEvent(body, sig)` | `webhooks.constructEvent(body, headers)` — timestamp checked |
133
121
 
134
- UNLICENSED — internal to Elite Yatra.
122
+ License: MIT
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@thepayulink/server",
3
- "version": "1.0.0",
4
- "description": "Server-side SDK for Elite Yatra / PayuLink — create orders, check payment status, and verify signatures & webhooks with your secret key.",
3
+ "version": "2.0.0",
4
+ "description": "PayuLink server SDK \u2014 create orders and verify payments/webhooks with your key_secret.",
5
5
  "type": "module",
6
6
  "main": "./dist/payulink-server.cjs",
7
7
  "module": "./src/index.js",
@@ -25,7 +25,6 @@
25
25
  "build": "node build.mjs"
26
26
  },
27
27
  "keywords": [
28
- "eliteyatra",
29
28
  "payulink",
30
29
  "payment",
31
30
  "server",
@@ -34,9 +33,10 @@
34
33
  "orders",
35
34
  "webhooks"
36
35
  ],
37
- "author": "Elite Yatra",
36
+ "author": "PayuLink",
38
37
  "license": "MIT",
39
38
  "devDependencies": {
40
39
  "esbuild": "^0.23.0"
41
- }
40
+ },
41
+ "homepage": "https://payulink.io"
42
42
  }
package/src/index.js CHANGED
@@ -1,60 +1,77 @@
1
- // @thepayulink/server — backend SDK for Elite Yatra / PayuLink.
1
+ // @thepayulink/server — backend SDK for the PayuLink Checkout API (v1).
2
2
  //
3
- // import Payulink from '@thepayulink/server';
4
- // const ey = new Payulink({ keyId: 'pl_pk_…', keySecret: 'pl_sk_…' });
5
- // const order = await ey.orders.create({ amount: 19900, item: 'Kailash Yatra' });
6
- // // …open `order.order_id` in the client SDK…
7
- // const status = await ey.orders.fetch(order.order_id); // { paid, status, utr, … }
3
+ // import PayuLink from '@thepayulink/server';
4
+ // const pl = new PayuLink({ keyId: 'pl_live_…', keySecret: '…' });
5
+ //
6
+ // // 1. Create an order on YOUR server. The amount is fixed here and the
7
+ // // client can never change it.
8
+ // const order = await pl.orders.create({ amount: 19950, receipt: 'rcpt#1' }); // ₹199.50 in PAISE
9
+ //
10
+ // // 2. Hand order.id to the client SDK, which opens it with the PUBLISHABLE key_id.
11
+ //
12
+ // // 3. Verify the success handoff before you fulfil anything.
13
+ // if (pl.verifyPaymentSignature(req.body)) fulfil(order.id);
8
14
  //
9
15
  // Requires Node 18+ (global fetch).
10
16
  import crypto from 'node:crypto';
11
17
 
12
- export class PayulinkError extends Error {
13
- constructor(message, { status, body } = {}) {
18
+ /** Amount helpers the API speaks PAISE, like Razorpay. */
19
+ export const rupees = (r) => Math.round(Number(r) * 100);
20
+ export const toRupees = (paise) => Number(paise) / 100;
21
+
22
+ export class PayuLinkError extends Error {
23
+ constructor(message, { status, code, body } = {}) {
14
24
  super(message);
15
- this.name = 'PayulinkError';
25
+ this.name = 'PayuLinkError';
16
26
  this.status = status;
27
+ this.code = code;
17
28
  this.body = body;
18
29
  }
19
30
  }
20
31
 
21
32
  function safeEqual(a, b) {
22
- const ba = Buffer.from(String(a || ''));
23
- const bb = Buffer.from(String(b || ''));
33
+ const ba = Buffer.from(String(a ?? ''));
34
+ const bb = Buffer.from(String(b ?? ''));
24
35
  return ba.length === bb.length && ba.length > 0 && crypto.timingSafeEqual(ba, bb);
25
36
  }
26
37
 
27
- export default class Payulink {
38
+ export default class PayuLink {
28
39
  /**
29
40
  * @param {object} opts
30
- * @param {string} opts.keySecret Secret key (pl_sk_). Required. Backend only.
31
- * @param {string} [opts.keyId] Publishable key (pl_pk_…). Optional.
32
- * @param {string} [opts.apiBase] Pay server URL. Default https://eliteyatra.vip.
33
- * @param {string} [opts.webhookSecret] Secret used to verify inbound webhooks (defaults to keySecret).
34
- * @param {number} [opts.timeout] Request timeout in ms. Default 15000.
41
+ * @param {string} opts.keyId Publishable key (pl_live_/ pl_test_…).
42
+ * @param {string} opts.keySecret Secret key. BACKEND ONLY — never ship this.
43
+ * @param {string} [opts.apiBase] Default https://payulink.io/api
44
+ * @param {string} [opts.webhookSecret] Webhook signing secret (webhook_secret_v2 from your
45
+ * merchant panel). Falls back to keySecret.
46
+ * @param {number} [opts.timeout] Request timeout ms. Default 15000.
35
47
  */
36
48
  constructor(opts = {}) {
37
- if (!opts.keySecret) throw new PayulinkError('`keySecret` (pl_sk_…) is required');
49
+ if (!opts.keyId) throw new PayuLinkError('`keyId` (pl_live_ / pl_test_…) is required');
50
+ if (!opts.keySecret) throw new PayuLinkError('`keySecret` is required and must stay on your server');
51
+ this.keyId = opts.keyId;
38
52
  this.keySecret = opts.keySecret;
39
- this.keyId = opts.keyId || null;
40
- this.apiBase = String(opts.apiBase || 'https://eliteyatra.vip').replace(/\/$/, '');
53
+ this.apiBase = String(opts.apiBase || 'https://payulink.io/api').replace(/\/$/, '');
41
54
  this.webhookSecret = opts.webhookSecret || opts.keySecret;
42
55
  this.timeout = opts.timeout || 15000;
56
+ this.mode = /^pl_test_/.test(opts.keyId) ? 'test' : 'live';
43
57
 
44
58
  this.orders = {
45
59
  create: (params) => this._createOrder(params),
46
60
  fetch: (orderId) => this._fetchOrder(orderId),
47
- isPaid: async (orderId) => (await this._fetchOrder(orderId)).paid === true,
61
+ isPaid: async (orderId) => (await this._fetchOrder(orderId)).status === 'paid',
48
62
  };
49
- // Alias for Razorpay-familiar naming.
50
- this.payments = { fetch: (orderId) => this._fetchOrder(orderId) };
51
63
  this.webhooks = {
52
- verify: (rawBody, signature, secret) => this._verifyWebhook(rawBody, signature, secret),
53
- constructEvent: (rawBody, signature, secret) => this._constructEvent(rawBody, signature, secret),
64
+ verify: (rawBody, signature, timestamp, secret) =>
65
+ this._verifyWebhook(rawBody, signature, timestamp, secret),
66
+ constructEvent: (rawBody, headers, secret) => this._constructEvent(rawBody, headers, secret),
54
67
  };
55
68
  }
56
69
 
57
- async _request(method, path, { body, auth } = {}) {
70
+ get _authHeader() {
71
+ return 'Basic ' + Buffer.from(`${this.keyId}:${this.keySecret}`).toString('base64');
72
+ }
73
+
74
+ async _request(method, path, { body } = {}) {
58
75
  const ctrl = new AbortController();
59
76
  const t = setTimeout(() => ctrl.abort(), this.timeout);
60
77
  let res;
@@ -63,74 +80,137 @@ export default class Payulink {
63
80
  method,
64
81
  headers: {
65
82
  'Content-Type': 'application/json',
66
- ...(auth ? { Authorization: `Bearer ${this.keySecret}` } : {}),
67
- ...(this.keyId ? { 'x-payulink-key': this.keyId } : {}),
83
+ Authorization: this._authHeader,
68
84
  },
69
85
  body: body ? JSON.stringify(body) : undefined,
70
86
  signal: ctrl.signal,
71
87
  });
72
88
  } catch (e) {
73
89
  clearTimeout(t);
74
- throw new PayulinkError(`Network error: ${e.message}`);
90
+ throw new PayuLinkError(`Network error: ${e.message}`);
75
91
  }
76
92
  clearTimeout(t);
93
+
77
94
  let data = {};
78
95
  try { data = await res.json(); } catch { /* non-JSON */ }
79
- if (!res.ok) throw new PayulinkError(data.error || `Request failed (HTTP ${res.status})`, { status: res.status, body: data });
96
+ if (!res.ok) {
97
+ const err = data && data.error ? data.error : {};
98
+ throw new PayuLinkError(err.description || `Request failed (HTTP ${res.status})`,
99
+ { status: res.status, code: err.code, body: data });
100
+ }
80
101
  return data;
81
102
  }
82
103
 
83
104
  /**
84
- * Create an order with a server-fixed amount. The client only receives the
85
- * returned `order_id` and cannot change the amount.
86
- * @param {object} params { amount (rupees), item?, customer? }
87
- * @returns {Promise<{order_id, key_id, amount, item, status}>}
105
+ * Create an order with a server-fixed amount.
106
+ * @param {object} p
107
+ * @param {number} p.amount Amount in PAISE (19950 = ₹199.50). Minimum 100.
108
+ * @param {string} [p.currency] INR (default).
109
+ * @param {string} [p.receipt] Your reference. Unique per merchant — reusing it
110
+ * returns the SAME order, which makes retries safe.
111
+ * @param {object} [p.notes] Arbitrary key/value metadata.
88
112
  */
89
- _createOrder(params = {}) {
90
- const amount = Math.round(Number(params.amount) || 0);
91
- if (!(amount >= 1)) throw new PayulinkError('`amount` (in rupees) is required and must be >= 1');
92
- return this._request('POST', '/api/orders', {
93
- auth: true,
94
- body: { amount, item: params.item, customer: params.customer },
113
+ _createOrder(p = {}) {
114
+ const amount = Math.round(Number(p.amount));
115
+ if (!Number.isFinite(amount) || amount < 100) {
116
+ throw new PayuLinkError('`amount` is required, in PAISE, and must be >= 100 (₹1). '
117
+ + 'Tip: use the `rupees()` helper — rupees(199.5) === 19950.');
118
+ }
119
+ return this._request('POST', '/v1/orders', {
120
+ body: {
121
+ amount,
122
+ currency: p.currency || 'INR',
123
+ receipt: p.receipt,
124
+ notes: p.notes,
125
+ customer_name: p.customer?.name,
126
+ customer_mobile: p.customer?.contact,
127
+ customer_email: p.customer?.email,
128
+ notify_url: p.notifyUrl,
129
+ },
95
130
  });
96
131
  }
97
132
 
98
- /**
99
- * Fetch the authoritative status of an order.
100
- * @returns {Promise<{merchant_order_no, status, status_label, paid, utr, amount, signature}>}
101
- */
133
+ /** Authoritative order status. */
102
134
  _fetchOrder(orderId) {
103
- if (!orderId) throw new PayulinkError('orderId is required');
104
- return this._request('GET', `/api/order/${encodeURIComponent(orderId)}`);
135
+ if (!orderId) throw new PayuLinkError('orderId is required');
136
+ return this._request('GET', `/v1/orders/${encodeURIComponent(orderId)}`);
105
137
  }
106
138
 
107
139
  /**
108
- * Verify a payment handoff signature returned to the client on success.
109
- * Mirrors Razorpay's signature check.
110
- * @param {object} p { order_id, utr, signature }
111
- * @returns {boolean}
140
+ * Verify the success handoff the client SDK returns. Mirrors Razorpay's
141
+ * `validatePaymentVerification`.
142
+ *
143
+ * signature = hex(HMAC_SHA256(order_id + "|" + payment_id, key_secret))
144
+ *
145
+ * ALWAYS do this on your server before fulfilling. The client callback alone
146
+ * is not proof of payment.
147
+ *
148
+ * @param {object} p { payulink_order_id, payulink_payment_id, payulink_signature }
149
+ * (also accepts order_id / payment_id / signature)
112
150
  */
113
- verifyPaymentSignature({ order_id, utr, signature } = {}) {
114
- if (!order_id || !signature) return false;
115
- const expected = crypto.createHmac('sha256', this.keySecret).update(`${order_id}|${utr || ''}`).digest('hex');
151
+ verifyPaymentSignature(p = {}) {
152
+ const orderId = p.payulink_order_id || p.order_id;
153
+ const paymentId = p.payulink_payment_id || p.payment_id;
154
+ const signature = p.payulink_signature || p.signature;
155
+ if (!orderId || !paymentId || !signature) return false;
156
+ const expected = crypto.createHmac('sha256', this.keySecret)
157
+ .update(`${orderId}|${paymentId}`).digest('hex');
116
158
  return safeEqual(expected, signature);
117
159
  }
118
160
 
119
- _verifyWebhook(rawBody, signature, secret) {
120
- const expected = crypto.createHmac('sha256', secret || this.webhookSecret).update(String(rawBody)).digest('hex');
161
+ /**
162
+ * Verify a webhook. PayuLink signs webhooks Stripe-style:
163
+ * X-PayuLink-Signature: sha256=<hex> over `${timestamp}.${rawBody}`
164
+ * X-PayuLink-Timestamp: <epoch ms>
165
+ */
166
+ _verifyWebhook(rawBody, signature, timestamp, secret) {
167
+ if (!signature || !timestamp) return false;
168
+ const key = secret || this.webhookSecret;
169
+ const expected = 'sha256=' + crypto.createHmac('sha256', key)
170
+ .update(`${timestamp}.${String(rawBody)}`).digest('hex');
121
171
  return safeEqual(expected, signature);
122
172
  }
123
173
 
124
174
  /**
125
- * Verify an inbound webhook and return the parsed event. Throws if the
126
- * signature is invalid. Pass the RAW request body (string/Buffer) and the
127
- * `x-payulink-signature` header.
175
+ * Verify + parse a webhook. Throws if the signature is bad or the timestamp is
176
+ * outside the tolerance window (replay protection).
177
+ *
178
+ * Pass the RAW body (string/Buffer) — a re-serialised object will not match.
179
+ *
180
+ * app.post('/webhook', express.raw({type:'*\/*'}), (req, res) => {
181
+ * const event = pl.webhooks.constructEvent(req.body, req.headers);
182
+ * if (event.event_type === 'payin.verified') fulfil(event);
183
+ * res.sendStatus(200);
184
+ * });
185
+ *
186
+ * @param {string|Buffer} rawBody
187
+ * @param {object} headers The request headers object.
188
+ * @param {string} [secret]
189
+ * @param {number} [toleranceSec=300]
128
190
  */
129
- _constructEvent(rawBody, signature, secret) {
130
- if (!this._verifyWebhook(rawBody, signature, secret)) {
131
- throw new PayulinkError('Invalid webhook signature', { status: 401 });
191
+ _constructEvent(rawBody, headers = {}, secret, toleranceSec = 300) {
192
+ const get = (n) => headers[n] || headers[n.toLowerCase()] ||
193
+ (typeof headers.get === 'function' ? headers.get(n) : undefined);
194
+ const signature = get('X-PayuLink-Signature');
195
+ const timestamp = get('X-PayuLink-Timestamp');
196
+ if (!signature) throw new PayuLinkError('Missing X-PayuLink-Signature', { status: 401 });
197
+ if (!timestamp) throw new PayuLinkError('Missing X-PayuLink-Timestamp', { status: 401 });
198
+
199
+ // Replay window: a captured webhook must not be replayable forever.
200
+ const ageSec = Math.abs(Date.now() - Number(timestamp)) / 1000;
201
+ if (!Number.isFinite(ageSec) || ageSec > toleranceSec) {
202
+ throw new PayuLinkError(`Webhook timestamp outside tolerance (${Math.round(ageSec)}s)`, { status: 401 });
203
+ }
204
+ if (!this._verifyWebhook(rawBody, signature, timestamp, secret)) {
205
+ throw new PayuLinkError('Invalid webhook signature', { status: 401 });
206
+ }
207
+ try {
208
+ const event = JSON.parse(String(rawBody));
209
+ event.id = event.id || get('X-PayuLink-Event-Id');
210
+ event.event_type = event.event_type || get('X-PayuLink-Event-Type');
211
+ return event;
212
+ } catch {
213
+ throw new PayuLinkError('Invalid webhook JSON', { status: 400 });
132
214
  }
133
- try { return JSON.parse(String(rawBody)); }
134
- catch { throw new PayulinkError('Invalid webhook JSON', { status: 400 }); }
135
215
  }
136
216
  }