Skip to content

Create a test order

Add test funds, see the amount held, and create one order that a retry can never duplicate.

Sandbox: test money only. No request moves real money.

This page goes further with the order of step 5: check your limits and your test funds, create the order with its idempotency key and an optional ceiling, see its amount held, and run the whole order as one program. No real money moves and nothing is delivered; the sandbox simulates the outcome. Showing a price before purchase is the advanced section at the end.

Check your limits

An order must fit the account. Read it first: limits.max_queued is how many orders may be in progress at once.

It also confirms the key works, and names its organisation.

Code for Check your limits
GET /v1/accountSandbox, test key
// npm install axiosimport axios from 'axios';try {  const { status, data: account } = await axios.get(    'https://sandbox-api.nasfampay.com/v1/account',    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,      },    },  );  console.log(status, account);} catch (error) {  if (!axios.isAxiosError(error) || !error.response) throw error;  const problem = error.response.data;  throw new Error(`${problem.status} ${problem.code}: ${problem.title} (request ${problem.request_id})`);}

Add synthetic money

An order is paid from your available balance. If you have not yet, add test funds: in your dashboard, open Balance and press Add test funds. It credits synthetic money to your workspace, and nothing else can spend it.

Then read GET /balance: the funds are in available, in USD. Read currency on every amount, and never assume it.

Funding by API is a simulated deposit; see Funding with GRAM.

Code for Add synthetic money
GET /v1/balanceSandbox, test key
// npm install axiosimport axios from 'axios';try {  const { status, data: balance } = await axios.get(    'https://sandbox-api.nasfampay.com/v1/balance',    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,      },    },  );  console.log(status, balance);} catch (error) {  if (!axios.isAxiosError(error) || !error.response) throw error;  const problem = error.response.data;  throw new Error(`${problem.status} ${problem.code}: ${problem.title} (request ${problem.request_id})`);}

Create the order

The request is the one you sent in Send your own API order: the product (telegram_stars or telegram_premium), the username and how much, with an Idempotency-Key you stored before you sent anything. A reference of your own (up to 64 characters) lets you find the order again with GET /orders?reference=.

Without max_amount the server bounds the order: it is priced from the price book at fresh rates (or refused with pricing_unavailable, nothing held), and it must fit your organisation's order limit (order_limit_exceeded) and the environment's per-order and daily USD limits. max_amount, in USD cents, is your own strict ceiling: an order whose charge, its settlement, would be more is refused with price_changed and nothing is held.

The answer is 202 Accepted. The order is processing, and its amount was held on your balance before the response was sent.

  • One key, one order. If the connection drops, send the same request with the same key. You get 200 with Idempotent-Replayed: true and the order as it is now, never a second order. The answer below is that replay.
  • A new key is a new order. Never make a fresh key to retry.

Every order without a quote also draws on your organisation's quotes bucket, which all its keys share, as a quote does: Rate limits gives the figures. A GRAM workspace orders from a quote, below.

Code for Create the order
A retry with the same key
JSON
200 OKSynthetic sandbox data
{  "id": "ord_01K7SAMP000000000000000093",  "environment": "sandbox",  "status": "succeeded",  "status_reason": null,  "product": "telegram_stars",  "selection": {    "quantity": 50  },  "recipient": {    "telegram_username": "nasfam_test_ok"  },  "amount": {    "amount": 75,    "currency": "USD"  },  "quote_id": null,  "pricing_version": "sandbox-synthetic-v1",  "reference": null,  "version": 2,  "estimated_completion_at": "2026-10-10T10:15:05.000Z",  "created_at": "2026-10-10T10:15:02.000Z",  "updated_at": "2026-10-10T10:15:05.000Z",  "completed_at": "2026-10-10T10:15:05.000Z"}

See the hold on your balance

While the order is in progress its amount is not spent and not free: it is held. On GET /balance, available has fallen by the order's amount and held has risen by it.

The statement shows the same movement as an order_reserve that names the order_id. When the order ends, a second movement follows: an order_capture if it succeeded, an order_release back to available if it failed.

Funding your account shows the request.

Code for See the hold on your balance
The statement: the reserve, above the credit
JSON
200 OKSynthetic sandbox data
{  "data": [    {      "id": "btx_01K7SAMP000000000000000091",      "type": "order_reserve",      "amount": {        "amount": -75,        "currency": "USD"      },      "available_after": {        "amount": 9925,        "currency": "USD"      },      "order_id": "ord_01K7SAMP000000000000000090",      "funding_id": null,      "created_at": "2026-10-10T10:15:02.000Z"    },    {      "id": "btx_01K7SAMP000000000000000090",      "type": "funding_credit",      "amount": {        "amount": 10000,        "currency": "USD"      },      "available_after": {        "amount": 10000,        "currency": "USD"      },      "order_id": null,      "funding_id": "fnd_01K7SAMP000000000000000090",      "created_at": "2026-10-10T10:14:00.000Z"    }  ],  "has_more": false,  "next_cursor": null}

Run it as one program

The same order as one program for your server, for Telegram Stars or Telegram Premium, in cURL, Node.js, TypeScript, Python or PHP. It authenticates, checks the recipient, orders and tracks the order to its end, reading again after a longer wait each time. It reads the key from NASFAM_SANDBOX_KEY (NASFAM_LIVE_KEY when you choose Live above). Run it on your server, never in a browser or an app.

It writes one Idempotency-Key, your reference and the request down before it sends anything. A run that stops before the order is final is resumed by the next: the same request, the same key. Once the order succeeds or fails, the next run is a new order. Every answer is handled in one place:

  • 202: accepted and processing, with the amount held. It is tracked, never sent again.
  • 400, or any other 4xx: the request is wrong. It checks your reference for an order, then stops; the request is never sent again unchanged.
  • 401: the key is missing, wrong or for the other environment. Fix the key variable (NASFAM_SANDBOX_KEY or NASFAM_LIVE_KEY); see invalid_api_key.
  • 429, or idempotency_in_progress: it waits the seconds in Retry-After, then sends the same request with the same key.
  • No answer, a timeout or a 5xx: the outcome is unknown. It sends the same request with the same key, never a new one, and then looks the order up by your reference. Finding nothing yet, it stops: run it again to resume the same order.

The test recipients in Sandbox scenarios choose what the simulated provider does. Money here is synthetic.

Code for Run it as one program

First order: Telegram Stars

Runs on your server, with your key in the environment variable it names
// Your first sandbox order of Telegram Stars: authenticate, check the recipient, order, track.// Save it as quickstart.js beside a package.json with "type": "module"; run node quickstart.js on Node.js 18 or later.// Run it on your server: it reads the key from NASFAM_SANDBOX_KEY. Never put a key in code, a browser or an app.// Sandbox money is synthetic: nothing real is charged or delivered.import { randomUUID } from 'node:crypto';import { appendFileSync, existsSync, readFileSync } from 'node:fs';const API = 'https://sandbox-api.nasfampay.com/v1';const pause = (seconds) => new Promise((resolve) => { setTimeout(resolve, seconds * 1000); });/** No final answer: the request may have worked. */class Unknown extends Error {}/** Refused: the request was wrong, and nothing was done. */class Refused extends Error {}// One request, and what to do with each answer. A retry always sends the same request with the same key.async function send(method, path, body = null, idempotencyKey = null) {  for (let attempt = 1; attempt <= 3; attempt += 1) {    let response = null;    let answer = null;    try {      response = await fetch(`${API}${path}`, {        method,        headers: {          Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,          ...(body && { 'Content-Type': 'application/json' }),          ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),        },        body: body && JSON.stringify(body),        signal: AbortSignal.timeout(30_000),      });      // A body cut off part way is no answer too.      answer = await response.json();    } catch {      response = null;    }    // No answer (a timeout or a lost connection) or a 5xx: UNKNOWN. Send the same request again with the same key, never a new one.    if (!response || response.status >= 500) {      await pause(2);      continue;    }    if (response.ok) return answer;    // 429, or the first request with this key still running: wait Retry-After, then send the same request with the same key.    if (response.status === 429 || answer.code === 'idempotency_in_progress') {      await pause(Number(response.headers.get('Retry-After') ?? 1));      continue;    }    const { code, title, request_id: requestId } = answer;    // 401: the key is missing, wrong or for another environment. Fix NASFAM_SANDBOX_KEY; do not resend.    if (response.status === 401) throw new Error(`401 ${code}: check NASFAM_SANDBOX_KEY (request ${requestId})`);    // Any other 4xx, most often 400 or 422: the request is wrong. Fix it; never resend it unchanged.    throw new Refused(`${response.status} ${code}: ${title} (request ${requestId})`);  }  // Still no final answer: UNKNOWN. Read it back before doing anything else.  throw new Unknown(`No final answer to ${method} ${path}`);}// 1. Authenticate: a 200 means the key works. `available` is what an order can spend.const balance = await send('GET', '/balance');console.log('Available:', balance.available);// 2. Check the recipient (optional: the order checks it again). Show your customer the account found.const check = await send('GET', '/recipients/lookup?username=nasfam_test_ok&product=telegram_stars');console.log('Found:', check.display_name);if (check.eligibility !== 'not_refused') {  console.log(`The provider refused this account for this product (${check.reason}): nothing was ordered.`);  process.exit(1);}// 3. Order: the product, the username and how much. Make one Idempotency-Key for this order and store it with your reference and the body BEFORE sending.//    A retry, and a run after one that stopped short (its last attempt has no final status), resends that same request//    with that key. (One file here; your database in production.) A 202 means accepted and processing, with the amount//    held: never send it again, track it.const last = existsSync('order-attempts.jsonl') ? readFileSync('order-attempts.jsonl', 'utf8').trim().split('\n').at(-1) : '';let attempt = last ? JSON.parse(last) : null;if (attempt?.status) attempt = null;if (attempt) {  console.log(`Resuming ${attempt.reference}: the same request with its stored key.`);} else {  const reference = `order-${Date.now()}`;  const body = {    product: 'telegram_stars',    username: 'nasfam_test_ok',    quantity: 50,    reference: reference,  };  attempt = { reference, idempotencyKey: randomUUID(), body };  appendFileSync('order-attempts.jsonl', `${JSON.stringify(attempt)}\n`);}const { reference } = attempt;const settle = (status) => appendFileSync('order-attempts.jsonl', `${JSON.stringify({ reference, status })}\n`);let order;try {  order = await send('POST', '/orders', attempt.body, attempt.idempotencyKey);} catch (error) {  if (!(error instanceof Unknown || error instanceof Refused)) throw error;  // No order in the answer: it may still exist. Find it by your reference, and never place another.  [order] = (await send('GET', `/orders?reference=${encodeURIComponent(reference)}`)).data;  if (!order && error instanceof Refused) {    // Refused, and no order under the reference: close the attempt.    settle('refused');    throw error;  }}if (!order) throw new Error(`No order ${reference} yet: run this program again. It resends the same request with its stored key, never a new one.`);// 4. Track it to its final state. A webhook tells you the same without asking.// Read it again after a longer wait each time, at most 30 seconds: how often you read never changes the outcome.let wait = 2;try {  while (order.status === 'processing') {    await pause(wait);    wait = Math.min(wait * 2, 30);    order = await send('GET', `/orders/${order.id}`);  }} catch (error) {  if (!(error instanceof Unknown)) throw error;  throw new Error(`No answer while tracking ${reference}: look it up with GET /orders?reference=${reference}. Run this again to resume it; it never places another.`);}// succeeded: delivered. failed: not delivered, and the held amount is back in available.// under_review: being confirmed, with the money held. Do not order again: it ends succeeded or failed.// A final status closes the attempt. under_review is not final: a run resumes it.if (order.status === 'succeeded' || order.status === 'failed') settle(order.status);console.log(order.status, order.status_reason ?? '');

First order: Telegram Premium

Runs on your server, with your key in the environment variable it names
// Your first sandbox order of Telegram Premium: authenticate, check the recipient, order, track.// Save it as quickstart.js beside a package.json with "type": "module"; run node quickstart.js on Node.js 18 or later.// Run it on your server: it reads the key from NASFAM_SANDBOX_KEY. Never put a key in code, a browser or an app.// Sandbox money is synthetic: nothing real is charged or delivered.import { randomUUID } from 'node:crypto';import { appendFileSync, existsSync, readFileSync } from 'node:fs';const API = 'https://sandbox-api.nasfampay.com/v1';const pause = (seconds) => new Promise((resolve) => { setTimeout(resolve, seconds * 1000); });/** No final answer: the request may have worked. */class Unknown extends Error {}/** Refused: the request was wrong, and nothing was done. */class Refused extends Error {}// One request, and what to do with each answer. A retry always sends the same request with the same key.async function send(method, path, body = null, idempotencyKey = null) {  for (let attempt = 1; attempt <= 3; attempt += 1) {    let response = null;    let answer = null;    try {      response = await fetch(`${API}${path}`, {        method,        headers: {          Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,          ...(body && { 'Content-Type': 'application/json' }),          ...(idempotencyKey && { 'Idempotency-Key': idempotencyKey }),        },        body: body && JSON.stringify(body),        signal: AbortSignal.timeout(30_000),      });      // A body cut off part way is no answer too.      answer = await response.json();    } catch {      response = null;    }    // No answer (a timeout or a lost connection) or a 5xx: UNKNOWN. Send the same request again with the same key, never a new one.    if (!response || response.status >= 500) {      await pause(2);      continue;    }    if (response.ok) return answer;    // 429, or the first request with this key still running: wait Retry-After, then send the same request with the same key.    if (response.status === 429 || answer.code === 'idempotency_in_progress') {      await pause(Number(response.headers.get('Retry-After') ?? 1));      continue;    }    const { code, title, request_id: requestId } = answer;    // 401: the key is missing, wrong or for another environment. Fix NASFAM_SANDBOX_KEY; do not resend.    if (response.status === 401) throw new Error(`401 ${code}: check NASFAM_SANDBOX_KEY (request ${requestId})`);    // Any other 4xx, most often 400 or 422: the request is wrong. Fix it; never resend it unchanged.    throw new Refused(`${response.status} ${code}: ${title} (request ${requestId})`);  }  // Still no final answer: UNKNOWN. Read it back before doing anything else.  throw new Unknown(`No final answer to ${method} ${path}`);}// 1. Authenticate: a 200 means the key works. `available` is what an order can spend.const balance = await send('GET', '/balance');console.log('Available:', balance.available);// 2. Check the recipient (optional: the order checks it again). Show your customer the account found.const check = await send('GET', '/recipients/lookup?username=nasfam_test_ok&product=telegram_premium');console.log('Found:', check.display_name);if (check.eligibility !== 'not_refused') {  console.log(`The provider refused this account for this product (${check.reason}): nothing was ordered.`);  process.exit(1);}// 3. Order: the product, the username and how much. Make one Idempotency-Key for this order and store it with your reference and the body BEFORE sending.//    A retry, and a run after one that stopped short (its last attempt has no final status), resends that same request//    with that key. (One file here; your database in production.) A 202 means accepted and processing, with the amount//    held: never send it again, track it.const last = existsSync('order-attempts.jsonl') ? readFileSync('order-attempts.jsonl', 'utf8').trim().split('\n').at(-1) : '';let attempt = last ? JSON.parse(last) : null;if (attempt?.status) attempt = null;if (attempt) {  console.log(`Resuming ${attempt.reference}: the same request with its stored key.`);} else {  const reference = `order-${Date.now()}`;  const body = {    product: 'telegram_premium',    username: 'nasfam_test_ok',    months: 3,    reference: reference,  };  attempt = { reference, idempotencyKey: randomUUID(), body };  appendFileSync('order-attempts.jsonl', `${JSON.stringify(attempt)}\n`);}const { reference } = attempt;const settle = (status) => appendFileSync('order-attempts.jsonl', `${JSON.stringify({ reference, status })}\n`);let order;try {  order = await send('POST', '/orders', attempt.body, attempt.idempotencyKey);} catch (error) {  if (!(error instanceof Unknown || error instanceof Refused)) throw error;  // No order in the answer: it may still exist. Find it by your reference, and never place another.  [order] = (await send('GET', `/orders?reference=${encodeURIComponent(reference)}`)).data;  if (!order && error instanceof Refused) {    // Refused, and no order under the reference: close the attempt.    settle('refused');    throw error;  }}if (!order) throw new Error(`No order ${reference} yet: run this program again. It resends the same request with its stored key, never a new one.`);// 4. Track it to its final state. A webhook tells you the same without asking.// Read it again after a longer wait each time, at most 30 seconds: how often you read never changes the outcome.let wait = 2;try {  while (order.status === 'processing') {    await pause(wait);    wait = Math.min(wait * 2, 30);    order = await send('GET', `/orders/${order.id}`);  }} catch (error) {  if (!(error instanceof Unknown)) throw error;  throw new Error(`No answer while tracking ${reference}: look it up with GET /orders?reference=${reference}. Run this again to resume it; it never places another.`);}// succeeded: delivered. failed: not delivered, and the held amount is back in available.// under_review: being confirmed, with the money held. Do not order again: it ends succeeded or failed.// A final status closes the attempt. under_review is not final: a run resumes it.if (order.status === 'succeeded' || order.status === 'failed') settle(order.status);console.log(order.status, order.status_reason ?? '');

Advanced: quote before purchase

For a business that must show its customer a price before it buys: quote first, then order from the quote.

A quote checks the Telegram username and locks a price for up to 60 seconds. The username may carry a leading @; the server normalises it. quantity is for telegram_stars; telegram_premium takes months of 3, 6 or 12. The bounds in force are the ones List products answers, and an order buys one of the packages GET /prices lists.

Read recipient.found, the amount in the minor unit of its currency and expires_at before you order. The display name is returned on the quote only; it is never stored on the order or sent in a webhook.

Then order with the quote's id as quote_id, your reference and an Idempotency-Key. A quote is used once: a second order from it is refused with quote_already_used; past its expires_at, with quote_expired. Orders shows the order from a quote.

Code for Advanced: quote before purchase
POST /v1/quotesSandbox, test key
// npm install axiosimport axios from 'axios';try {  const { status, data: quote } = await axios.post(    'https://sandbox-api.nasfampay.com/v1/quotes',    {      product: 'telegram_stars',      telegram_username: 'nasfam_test_ok',      quantity: 50,    },    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,      },    },  );  console.log(status, quote);} catch (error) {  if (!axios.isAxiosError(error) || !error.response) throw error;  const problem = error.response.data;  throw new Error(`${problem.status} ${problem.code}: ${problem.title} (request ${problem.request_id})`);}

What you should see

The order request answers 202 with an order whose status is processing and whose version is 1. Keep its id: the next step follows it to the end.

Code for What you should see
An accepted order
JSON
202 AcceptedSynthetic sandbox data
{  "id": "ord_01K7SAMP000000000000000093",  "environment": "sandbox",  "status": "processing",  "status_reason": null,  "product": "telegram_stars",  "selection": {    "quantity": 50  },  "recipient": {    "telegram_username": "nasfam_test_ok"  },  "amount": {    "amount": 75,    "currency": "USD"  },  "quote_id": null,  "pricing_version": "sandbox-synthetic-v1",  "reference": null,  "version": 1,  "estimated_completion_at": "2026-10-10T10:15:05.000Z",  "created_at": "2026-10-10T10:15:02.000Z",  "updated_at": "2026-10-10T10:15:02.000Z",  "completed_at": null}

If it fails

What you seeWhat to check
insufficient_fundsThe order costs more than available. Add test funds, then send the same order again.
quote_expiredThe quote is past its expires_at. Create a new quote and order from it.
quote_already_usedThe quote already became an order. Find that order instead of ordering again.
idempotency_key_reusedYou sent this key before with a different body. Use one key per order, and never change the body between retries.
idempotency_in_progressYour first attempt is still being processed. Wait a moment and send the same request with the same key.
duplicate_referenceAnother order already carries this reference. Fetch it with GET /orders?reference=.
recipient_not_foundNo Telegram account has this username. Check the spelling.
invalid_request or unknown_fieldparam names the field at fault. Check the selection against the bounds on GET /products.
No answer: a timeout or a dropped connectionThe outcome is unknown, not failed. Send the same request with the same key.

Next step

Sandbox step 6 of 7: Verify order status. An order finishes after the response. Read its final state, receive the event, and retry without creating a second order.