# Node.js SDK

Create payments, check their status and verify webhooks from Node.js: Express, NestJS, Fastify, Next.js API routes
or serverless functions.

- **Package:** [`razcrypto-node`](https://www.npmjs.com/package/razcrypto-node) on npm
- **Version:** 3.0.0 · TypeScript types included · ESM and CommonJS
- **Requires:** Node.js 18+ (built-in `fetch`). No runtime dependencies.
- **Key:** Secret key `sk_…` (server only) + webhook signing secret `whsec_…`
- **Download:** [razcrypto-node-sdk.zip](https://razcryptogateway.com/downloads/razcrypto-node-sdk.zip) · [Source on GitHub](https://github.com/WorldxGrowth/razcrypto-node-sdk) · MIT

## 1. Install

### From npm (recommended)

```bash
npm install razcrypto-node
```

### From the download (local / offline)

```bash
curl -L -o razcrypto-node-sdk.zip https://razcryptogateway.com/downloads/razcrypto-node-sdk.zip
unzip razcrypto-node-sdk.zip                 # creates razcrypto-node-sdk/
cd razcrypto-node-sdk && npm install && npm run build && npm pack   # creates razcrypto-node-3.0.0.tgz
cd ../your-app && npm install ../razcrypto-node-sdk/razcrypto-node-3.0.0.tgz
```

### From GitHub (development)

```bash
git clone https://github.com/WorldxGrowth/razcrypto-node-sdk.git
cd razcrypto-node-sdk && npm install && npm test && npm run build
```

## 2. Keys

```bash
# .env (server only)
RAZCRYPTO_SECRET_KEY=sk_test_xxxxxxxxxxxxxxxx
RAZCRYPTO_WEBHOOK_SECRET=whsec_xxxxxxxxxxxxxxxx
```

Get them in **Dashboard → API apps**.

## 3. Quick example

```js
import { RazCrypto } from 'razcrypto-node';
// CommonJS: const { RazCrypto } = require('razcrypto-node');

const rc = new RazCrypto(process.env.RAZCRYPTO_SECRET_KEY);

const payment = await rc.payments.create(
  {
    amount: '49.00',               // decimal string
    currency: 'USD',               // or INR, EUR …; converted to crypto at checkout
    reference_id: 'order_1042',    // your order id
    redirect_url: 'https://shop.example/thanks', // website flow only
  },
  { idempotencyKey: 'order_1042' }, // a retry never creates a duplicate
);

// Website: res.redirect(payment.checkout_url) or open checkout.js with payment.id
// App: return { payment_id: payment.id, checkout_url: payment.checkout_url }
```

```js
const p = await rc.payments.retrieve('pay_…');   // server truth
if (p.status === 'paid') { /* fulfil */ }

for await (const p of rc.payments.all({ status: 'paid' })) console.log(p.id, p.amount);
```

## 4. Verify webhooks

```js
import express from 'express';
import { webhooks } from 'razcrypto-node';

// Use the RAW body on this route only
app.post('/webhooks/razcrypto', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = webhooks.verify(req.body, req.headers, process.env.RAZCRYPTO_WEBHOOK_SECRET);
  } catch {
    return res.sendStatus(400);
  }
  const payment = event.data.object;         // the full payment object
  if (event.type === 'payment.paid') await markOrderPaid(payment.reference_id, payment.id);
  res.sendStatus(200);
});
```

`webhooks.verify` throws `SignatureVerificationError` if the signature is wrong, the body changed or the timestamp
is more than 5 minutes off. Store the `webhook-id` header and skip repeats. NestJS: enable `rawBody: true` in
`NestFactory.create` and pass `req.rawBody`.

## 5. Verify the checkout signature

```js
import { isValidCheckoutSignature, verifyCheckoutSignature } from 'razcrypto-node';

// body from the app SDK / checkout.js onSuccess: { payment_id, reference_id, status, signature }
if (!isValidCheckoutSignature(body, process.env.RAZCRYPTO_WEBHOOK_SECRET)) return res.sendStatus(400);
// verifyCheckoutSignature(body, secret) does the same but throws
```

## Full integration for a mobile app

The app ([Flutter](/docs/flutter-sdk), [Android](/docs/android-sdk), [React Native](/docs/react-native-sdk)) calls
these endpoints. Express + any database; `db` stands for your own data layer (Prisma, Sequelize, Mongoose …).

```js
import express from 'express';
import { RazCrypto, webhooks, isValidCheckoutSignature } from 'razcrypto-node';

const rc = new RazCrypto(process.env.RAZCRYPTO_SECRET_KEY, { timeoutMs: 20_000, maxRetries: 2 });
const SECRET = process.env.RAZCRYPTO_WEBHOOK_SECRET;
const appStatus = (s) => (s === 'paid' ? 'completed' : s === 'expired' || s === 'cancelled' ? 'failed' : 'pending');

// Webhook first: it needs the raw body
app.post('/webhooks/razcrypto', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try { event = webhooks.verify(req.body, req.headers, SECRET); } catch { return res.sendStatus(400); }
  if (await db.webhookSeen(req.headers['webhook-id'])) return res.sendStatus(200);
  if (event.type.startsWith('payment.')) await sync(event.data.object);
  await db.rememberWebhook(req.headers['webhook-id']);
  res.sendStatus(200);
});

app.use(express.json());

app.post('/payments/razcrypto/create', auth, async (req, res) => {
  const order = await db.createOrder({ userId: req.user.id, amount: Number(req.body.amount), gateway: 'razcrypto' });
  const p = await rc.payments.create(
    { amount: order.amount.toFixed(2), currency: 'INR', reference_id: String(order.id) },
    { idempotencyKey: `order_${order.id}` },
  );
  await db.updateOrder(order.id, { gatewayPaymentId: p.id, gatewayStatus: 'pending' });
  res.json({ order_id: order.id, payment_id: p.id, checkout_url: p.checkout_url });
});

app.post('/payments/razcrypto/verify', auth, async (req, res) => {
  if (!isValidCheckoutSignature(req.body, SECRET)) return res.sendStatus(400);
  const order = await db.orderByPaymentId(req.body.payment_id, req.user.id);
  if (!order) return res.sendStatus(404);
  const p = await rc.payments.retrieve(order.gatewayPaymentId);
  await sync(p);
  res.json({ status: appStatus(p.status) });
});

app.get('/payments/razcrypto/status/:id', auth, async (req, res) => {
  const order = await db.orderByPaymentId(req.params.id, req.user.id);
  if (!order) return res.sendStatus(404);
  if (order.gatewayStatus === 'paid') return res.json({ status: 'completed' });
  const p = await rc.payments.retrieve(req.params.id);
  await sync(p);
  res.json({ status: appStatus(p.status) });
});

/** Apply a payment to its order. Safe to call many times (use a transaction / row lock). */
async function sync(p) {
  const order = await db.orderByPaymentId(p.id);
  if (!order || order.gatewayStatus === 'paid') return;
  if (p.status !== 'paid') return db.updateOrder(order.id, { gatewayStatus: p.status });
  if (String(order.id) !== p.reference_id) return;
  await db.updateOrder(order.id, { gatewayStatus: 'paid', paidAt: new Date() });
  // fulfil here, exactly once
}
```

Make RazCrypto an admin setting (on/off, test/live, keys stored encrypted) the same way as in the
[Laravel example](/docs/php-sdk#admin-panel-settings), and expose `GET /payment-gateways` so the app builds its
payment options from the server.

## API

| Area | Methods |
|---|---|
| Payments | `payments.create(params, { idempotencyKey })`, `retrieve(id)`, `list({ status, reference_id, chain, coin, limit, starting_after })`, `all(params)` (async iterator), `methods(id)`, `quote(id, { chain, coin })`, `cancel(id)`, `simulate(id, outcome)` (test mode) |
| Payment links | `paymentLinks.create(…)`, `retrieve`, `list`, `update`, `deactivate` |
| Others | `chains.list()`, `rates.list({ coins, currency })`, `rates.convert({ amount, from, to })`, `events.retrieve/list`, `merchant.retrieve()`, `webhookEndpoints.test()` |

**Errors.** API errors throw `RazCryptoApiError` (`status`, `code`, `message`, `param`, `requestId`). Network problems
throw `RazCryptoConnectionError`. Network errors, `429` and `5xx` are retried (option `maxRetries`, default 2) with the
same idempotency key. Option `timeoutMs` (default 30000). See [Errors](/docs/errors).

## Test

```js
const rc = new RazCrypto(process.env.RAZCRYPTO_SECRET_KEY); // sk_test_…
await rc.payments.simulate('pay_…', 'paid');                 // also: underpaid, expired, cancelled
```

The webhook arrives like in live mode. Check **Dashboard → API apps → Webhooks**. More in [Test mode](/docs/test-mode).
