// Node.js 20+. Run with NUEPAY_TEST_KEY set. This example accepts test keys only. import { randomUUID } from 'node:crypto'; const key = process.env.NUEPAY_TEST_KEY || ''; const base = (process.env.NUEPAY_BASE_URL || 'https://api.nuepay.net/v1').replace(/\/$/, ''); if (!/^np_test_[a-f0-9]{48}$/.test(key)) throw new Error('Set NUEPAY_TEST_KEY to your sandbox key.'); async function nuepay(method, path, body, idempotency) { const response = await fetch(base + path, { method, redirect: 'error', signal: AbortSignal.timeout(30000), headers: { Authorization: `Bearer ${key}`, Accept: 'application/json', 'Content-Type': 'application/json', ...(idempotency ? { 'Idempotency-Key': idempotency } : {}) }, ...(body ? { body: JSON.stringify(body) } : {}), }); const json = await response.json(); if (!response.ok) throw new Error(`${json.code}: ${json.message} Request ID: ${json.request_id}`); return json.data; } // Persist this UUID with the order before sending; reuse it after a connection error. const idempotency = randomUUID(); const payment = await nuepay('POST', '/collections', { amount: '500.00', currency: 'UGX', phone: '0772000000', merchant_reference: 'example-order' }, idempotency); const result = await nuepay('POST', `/sandbox/transactions/${payment.reference}/simulate`, { outcome: 'success' }); console.log(JSON.stringify(result, null, 2));