Skip to content

Your first Telegram Premium order

One Telegram Premium order from your key to delivery: look the recipient up, confirm, order, track, retry safely and handle the webhook.

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

This tutorial takes one Telegram Premium order from your key to delivery, in the Sandbox. The money is synthetic, the provider is simulated and nothing reaches Telegram. Every answer shown is a Sandbox answer, and says so.

Choose your language and HTTP client on any code panel. The examples read the key from NASFAM_SANDBOX_KEY, on your server.

Before you start

  • A Sandbox key, in NASFAM_SANDBOX_KEY: Create an API key.
  • Test funds on your balance: in your dashboard, open Balance and press Add test funds. An order is paid from available.
  • A server of your own to call the API from. A browser is refused.

Your page talks to your server, and your server talks to Nasfam Business. The API key is never in a page, an app or anything your customer can open.

1. Authenticate

Every request sends the key in the Authorization header, as Bearer followed by the key. There is no session and no other credential. Read your balance first: a 200 proves the key and the host, and available is what an order can spend.

Code for 1. Authenticate
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})`);}

2. Name the product

The product is telegram_premium, bought by months of Premium: 3, 6 or 12. Offer it only when GET /products lists it with available true, and read its bounds there. Telegram Premium is the product's own guide.

3. Look up the recipient (optional)

Send POST /recipient-lookups with product set to telegram_premium, the telegram_username exactly as your customer typed it, and the months. The answer is the account found: its display_name and photo_url, each null when the provider returned none.

The lookup is recommended, not required. An order checks the recipient itself, and refuses with nothing held when nobody has the username. The lookup lets your customer catch a mistyped username before they pay. Check and confirm the recipient is the full guide to this step, and Recipient lookup lists every field, error and test username.

CaseWhat the lookup answersWhat to show and do
No photo201 with photo_url null. display_name may be null too.Draw initials from the name in place of the photo. With no name either, show the username with its @. It is still an account found: ask your customer to confirm it.
Username not found422 recipient_not_found. The short check answers 200 with found false and the same reason.Tell your customer nobody has that username and let them correct it. Do not order. Nothing was held.
The provider cannot verify503 provider_unavailable, with Retry-After.It says nothing about the account, so never show "not found". Wait the seconds in Retry-After and look up again, or let your customer continue without the preview and show the username exactly as typed.
Code for 3. Look up the recipient (optional)
POST /v1/recipient-lookupsSandbox, test key
// npm install axiosimport axios from 'axios';try {  const { status, data: lookup } = await axios.post(    'https://sandbox-api.nasfampay.com/v1/recipient-lookups',    {      product: 'telegram_premium',      telegram_username: '@nasfam_test_ok',      months: 3,    },    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,      },    },  );  console.log(status, lookup);} 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})`);}

4. Have your customer confirm

  1. Your customer types a Telegram username on your page.
  2. Your server looks the username up with POST /recipient-lookups, using your key.
  3. Your page shows the name, and the photo when there is one.
  4. Your customer confirms it is the account they mean.
  5. Your server creates the order.
  6. Your page shows the order's status until it is final.

A lookup finds the account at a username. It does not prove who owns that account, and it is not a promise of delivery. Say "Account found", never "Verified", and let your customer be the one who confirms.

5. Create the order

Send POST /orders with three fields and an Idempotency-Key header. In one request the server checks the recipient, prices the order, checks your limits and your balance, and holds the amount. No quote and no lookup id is needed.

FieldDescription
Productproduct ยท string ยท requiredtelegram_premium.
Usernameusername ยท string ยท requiredThe Telegram username: name, @name or t.me/name.
Monthsmonths ยท integer ยท required3, 6 or 12. GET /products gives the months in force as selection.allowed.
Max amountmax_amount ยท objectOptional. The most the order may charge, as an amount in US cents with its currency of USD.
Referencereference ยท stringOptional. Your own id for the purchase, up to 64 characters. It finds the order again with GET /orders?reference=.

The Idempotency-Key. Make one key per purchase and store it with the purchase before you send anything. The examples read it from IDEMPOTENCY_KEY. 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.

Code for 5. Create the order
POST /v1/ordersSandbox, test key
// npm install axiosimport axios from 'axios';// One key per purchase: make it once, keep it with the purchase, and send the same key on every retry.const idempotencyKey = process.env.IDEMPOTENCY_KEY;if (!idempotencyKey) throw new Error('Set IDEMPOTENCY_KEY once for this purchase (a new UUID) and keep it for every retry');try {  const { status, data: order } = await axios.post(    'https://sandbox-api.nasfampay.com/v1/orders',    {      product: 'telegram_premium',      username: 'nasfam_test_ok',      months: 3,    },    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,        'Idempotency-Key': idempotencyKey,      },    },  );  console.log(status, order);} 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})`);}

6. Read the order id and the response

The answer is 202 Accepted. It means accepted, not delivered.

  • id: the order. Store it with the purchase.
  • status: processing. Only succeeded means delivered.
  • settlement: what the order charges, held on your balance now.
  • version: 1. It rises by one on every change of status.

This is a Sandbox answer: its environment is sandbox and its amounts are synthetic.

Code for 6. Read the order id and the response
Sandbox: an accepted order
JSON
202 AcceptedSynthetic sandbox data
{  "id": "ord_01K7SAMP000000000000000094",  "environment": "sandbox",  "status": "processing",  "status_reason": null,  "product": "telegram_premium",  "selection": {    "months": 3  },  "recipient": {    "telegram_username": "nasfam_test_ok"  },  "amount": {    "amount": 1599,    "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}

7. Track the order

Read the order with GET /orders/{id} until its status is final. Wait longer between reads each time.

StatusYour moneyWhat to do
ProcessingprocessingHeld. Delivery is in progress.Wait for the next state.
SucceededsucceededCaptured. The order is paid for.Nothing. completed_at is set.
FailedfailedReleased back to available.Read status_reason; order again if it makes sense.
Under reviewunder_reviewYour funds stay held.No action needed.

Tell your customer it is delivered only at succeeded. In the Sandbox the outcome is simulated, and the test usernames choose it.

Code for 7. Track the order
GET /v1/orders/{id}Sandbox, test key
// npm install axiosimport axios from 'axios';try {  const { status, data: order } = await axios.get(    'https://sandbox-api.nasfampay.com/v1/orders/ord_01K7SAMP000000000000000090',    {      headers: {        Authorization: `Bearer ${process.env.NASFAM_SANDBOX_KEY}`,      },    },  );  console.log(status, order);} 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})`);}

8. Retry safely

  • No answer is unknown, never failed. Send the same request with the same key and the same body.
  • The same key is the same order. The retry answers 200 with Idempotent-Replayed: true and the order as it is now.
  • A new key is a new purchase. Never make a fresh key to retry.
  • Lost the key? Find the order with GET /orders?reference= before you do anything else.

Idempotency and safe retries shows the replay, and what a key binds.

9. Handle the webhook

A webhook tells you the outcome without asking. Register an https:// endpoint for order.succeeded, order.failed and order.under_review; Webhooks shows the request. The handler below does what every receiver must:

  1. Verify the signature over the raw body, and refuse a stale timestamp.
  2. Answer quickly, then do the work.
  3. Record the event id and ignore one you have seen. An event can arrive more than once.
  4. Ignore an event type you do not handle, and act on no test event. New types will be added.
  5. Keep the highest version you have seen for each order and ignore anything lower.

Read GET /orders/{id} before you release value to your customer. Testing webhooks sends your endpoint a test event before your first order.

Code for 9. Handle the webhook
Runs on your server, at the URL you registered
// Node.js 18 or later, no package. NASFAM_WEBHOOK_SECRET is the endpoint's whsec_ secret, read from the environment.import { createHmac, timingSafeEqual } from 'node:crypto';import { createServer } from 'node:http';const secret = Buffer.from(process.env.NASFAM_WEBHOOK_SECRET.slice('whsec_'.length), 'base64'); // the secret's bytes, not its textconst handled = new Set(); // event ids already handled: use your databaseconst versions = new Map(); // the highest version seen per order// Standard Webhooks v1: one signature in the header is the HMAC of this body, and the timestamp is within 5 minutes.function verified(body, headers) {  const header = (name) => String(headers[name] ?? '');  const id = header('webhook-id');  const timestamp = header('webhook-timestamp');  if (!id || !/^[0-9]+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) return false;  const expected = createHmac('sha256', secret).update(`${id}.${timestamp}.`).update(body).digest();  return header('webhook-signature').split(' ').some((signature) => {    const [version, value = ''] = signature.split(',');    const given = Buffer.from(value, 'base64');    return version === 'v1' && given.length === expected.length && timingSafeEqual(given, expected);  });}createServer((req, res) => {  const chunks = [];  req.on('data', (chunk) => chunks.push(chunk));  req.on('end', () => {    // Verify the raw body before you parse it: a body parsed and written again is not what was signed.    const body = Buffer.concat(chunks);    if (!verified(body, req.headers)) {      res.writeHead(400).end();      return;    }    // Answer at once and do the work afterwards: a slow answer is retried.    res.writeHead(200).end();    const event = JSON.parse(body.toString('utf8'));    // A test event is marked and its object is synthetic: acknowledge it and act on nothing.    if (event.test === true) {      console.log('test', event.type, event.id);      return;    }    // Retries and replays carry the same webhook-id, so the same event can arrive twice.    if (handled.has(event.id)) return;    handled.add(event.id);    // Ignore a type you do not handle: new ones will be added.    if (!event.type.startsWith('order.')) return;    // Order events are ordered by version, never by timestamp.    const order = event.data.object;    if (order.version <= (versions.get(order.id) ?? 0)) return;    versions.set(order.id, order.version);    // Fetch the order with GET /orders/{id} before you release value to your customer.    console.log(event.type, order.id, order.status);  });}).listen(Number(process.env.PORT ?? 3000));

Common failures

What you seeWhat to do
insufficient_fundsThe order costs more than available. Nothing was held. Add test funds, then send the same request with the same key.
recipient_not_foundNobody has this username. Nothing was held. Ask your customer to check it.
recipient_not_eligibleThe account cannot receive this product. Nothing was held. Do not retry.
invalid_requestparam names the field at fault. Check months against the product's selection on GET /products.
price_changedThe order would cost more than your max_amount. Nothing was held. Raise the ceiling or drop it, with a new key.
idempotency_key_reusedThis key was sent before with a different body. One key per purchase, and the same body on every retry.
idempotency_in_progressThe first attempt is still running. Wait the seconds in Retry-After, then send the same request with the same key.
rate_limitedWait the seconds in Retry-After, then send the same request with the same key.
key_environment_mismatchThe key and the host belong to different environments. A nbk_test_ key works on the Sandbox host only.
No answer: a timeout, a dropped connection or a 5xxUNKNOWN, never failed. Send the same request with the same key, or find the order with GET /orders?reference=. Never a new order.

Recovering from failures has the full recovery for each case.

What Live serves

Live serves this order as it is written here: the same body, sent to the Live host with your Live key. A workspace that spends USD or GRAM orders this way. A workspace still on its legacy currency orders from a quote instead: spending_currency on GET /balance says which yours is.

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.

Switch every example to Live with the selector under the title. It changes the host and the key variable a sample prints, and grants nothing: a Live key exists only in a workspace activated for Live. Live refuses every nasfam_test_ username.

Next step

Prepare for Live: what activation asks for, and the checklist to make true before a real order.