/** * SwiftUPI Node.js SDK (Node 18+, no dependencies). * * const SwiftUPI = require('./swiftupi'); * const gw = new SwiftUPI('sk_live_xxx'); * const order = await gw.createOrder({ amount: '499.00', client_order_id: 'order_1024' }); * res.redirect(order.payment_url); * * // Express webhook (use the RAW body): * app.post('/upi-webhook', express.raw({ type: 'application/json' }), (req, res) => { * const ok = SwiftUPI.verifyWebhook(req.body.toString(), req.get('X-Gateway-Timestamp'), req.get('X-Gateway-Signature'), 'whsec_xxx'); * if (!ok) return res.sendStatus(400); * const event = JSON.parse(req.body); // event.event === 'payment.success' * res.sendStatus(200); * }); */ const crypto = require('crypto'); class SwiftUPI { constructor(apiKey, baseUrl = 'https://app.swiftupi.com') { this.key = apiKey; this.base = baseUrl.replace(/\/$/, ''); } createOrder(data, idempotencyKey) { return this._req('POST', '/api/orders', data, idempotencyKey || data.client_order_id); } getOrder(id) { return this._req('GET', '/api/orders/' + encodeURIComponent(id)); } refund(orderId, amount, reason = '', reference = '') { return this._req('POST', `/api/orders/${encodeURIComponent(orderId)}/refunds`, { amount, reason, reference }); } static verifyWebhook(rawBody, timestamp, signature, secret, toleranceSec = 300) { if (!timestamp || !signature || Math.abs(Date.now() / 1000 - Number(timestamp)) > toleranceSec) return false; const expected = crypto.createHmac('sha256', secret).update(`${timestamp}.${rawBody}`).digest('hex'); const a = Buffer.from(expected), b = Buffer.from(String(signature)); return a.length === b.length && crypto.timingSafeEqual(a, b); } async _req(method, path, body, idem) { const headers = { 'X-API-Key': this.key, Accept: 'application/json' }; if (idem) headers['Idempotency-Key'] = idem; if (body) headers['Content-Type'] = 'application/json'; const r = await fetch(this.base + path, { method, headers, body: body ? JSON.stringify(body) : undefined }); const data = await r.json().catch(() => ({})); if (!r.ok) throw new Error(`SwiftUPI error ${r.status}: ${data.error || r.statusText}`); return data; } } module.exports = SwiftUPI;