Skip to content

Your first Live order as one program

Every step of a first Live order in one program for your server, for Telegram Stars or Telegram Premium.

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

The steps of Your first Live order in one program, in cURL, Node.js, TypeScript, Python or PHP. It runs on your server and reads the key from NASFAM_LIVE_KEY; never put the key in code, a browser or an app.

What it does

  1. Reads GET /balance, so a wrong key stops it before anything else.
  2. Checks the recipient with GET /recipients/lookup, prints the account found, and stops unless a person types yes. Nothing is priced or held before that.
  3. Makes one Idempotency-Key, stores it with your reference and the body, and only then sends the order.
  4. Tracks the order until it is succeeded or failed, reading again after a longer wait each time, at most every 30 seconds.

Replace @customer with your customer's username before you run it.

What it does with each answer

  • No answer, a timeout or a 5xx: UNKNOWN. The same request with the same key, at most three times, then the order is looked up by your reference. Finding nothing yet, it stops: run it again to resume the same order.
  • 429, or idempotency_in_progress: it waits the seconds in Retry-After, then sends the same request with the same key.
  • 401: it stops. Fix NASFAM_LIVE_KEY; see invalid_api_key.
  • Any other 4xx: the request is wrong. It checks your reference for an order, then stops; nothing is sent again unchanged.
  • under_review: the money stays held. It stops tracking and leaves the attempt open; never order again.

The program

In Live, Premium is sold to a workspace allowed to buy it. GET /products with your Live key lists it with available true when yours is; until then an order for it is refused and nothing is held.

Code for The program

First Live order: Telegram Stars

Runs on your server, with your key in the environment variable it namesLive, real money
// Your first Live 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_LIVE_KEY. Never put a key in code, a browser or an app.// Live money is real: an order holds real funds and delivers to a real Telegram account.import { randomUUID } from 'node:crypto';import { appendFileSync, existsSync, readFileSync } from 'node:fs';import { createInterface } from 'node:readline/promises';const API = 'https://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_LIVE_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_LIVE_KEY; do not resend.    if (response.status === 401) throw new Error(`401 ${code}: check NASFAM_LIVE_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=%40customer&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);}// A person confirms the account found is your customer's before anything is priced or held. Anything but yes stops here.const ask = createInterface({ input: process.stdin, output: process.stdout });const closed = new Promise((resolve) => { ask.once('close', () => resolve('')); });const answer = await Promise.race([ask.question(`Is ${check.display_name ?? check.username} your customer's Telegram account? Type yes to order: `), closed]);ask.close();if (answer.trim() !== 'yes') {  console.log('Stopped before anything was priced, held or ordered.');  process.exit(0);}// 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: '@customer',    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 Live order: Telegram Premium

Runs on your server, with your key in the environment variable it namesLive, real money
// Your first Live 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_LIVE_KEY. Never put a key in code, a browser or an app.// Live money is real: an order holds real funds and delivers to a real Telegram account.import { randomUUID } from 'node:crypto';import { appendFileSync, existsSync, readFileSync } from 'node:fs';import { createInterface } from 'node:readline/promises';const API = 'https://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_LIVE_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_LIVE_KEY; do not resend.    if (response.status === 401) throw new Error(`401 ${code}: check NASFAM_LIVE_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=%40customer&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);}// A person confirms the account found is your customer's before anything is priced or held. Anything but yes stops here.const ask = createInterface({ input: process.stdin, output: process.stdout });const closed = new Promise((resolve) => { ask.once('close', () => resolve('')); });const answer = await Promise.race([ask.question(`Is ${check.display_name ?? check.username} your customer's Telegram account? Type yes to order: `), closed]);ask.close();if (answer.trim() !== 'yes') {  console.log('Stopped before anything was priced, held or ordered.');  process.exit(0);}// 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: '@customer',    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 ?? '');

What you should see

After a person types yes, the program prints the order's status: processing when it is accepted, then succeeded:

Code for What you should see
The order the program ends on
JSON
200 OKSynthetic sandbox data
{  "id": "ord_01K7SAMP000000000000000091",  "environment": "live",  "status": "succeeded",  "status_reason": null,  "product": "telegram_stars",  "selection": {    "quantity": 50  },  "recipient": {    "telegram_username": "customer"  },  "amount": {    "amount": 75,    "currency": "USD"  },  "quote_id": "quo_01K7SAMP000000000000000091",  "pricing_version": "example",  "reference": "TEST-0002",  "version": 2,  "estimated_completion_at": "2026-10-10T10:15:35.000Z",  "created_at": "2026-10-10T10:15:30.000Z",  "updated_at": "2026-10-10T10:15:35.000Z",  "completed_at": "2026-10-10T10:15:35.000Z",  "recipient_lookup": "rlk_01K7SAMP000000000000000090"}

If it fails

What you seeWhat to check
key_environment_mismatchA sandbox key is in NASFAM_LIVE_KEY. Use your Live key.
recipient_not_eligibleLive refuses every nasfam_test_ name. Replace @customer with your customer's username.
It stops before the orderNobody typed yes to the account found. Nothing was priced, held or ordered.
It stops while trackingThe order exists. Run it again: it resumes the same order with the same key.

Next step

Live step 5 of 5: Monitor orders and webhooks. Register your Live webhook endpoint, follow every order to its end, and reconcile the money each day.