Your first Telegram Stars order
One Telegram Stars 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 Stars 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.
// 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_stars, bought by a quantity of Stars. Offer it only when GET /products lists it with available true, and read its bounds there. Telegram Stars is the product's own guide.
3. Look up the recipient (optional)
Send POST /recipient-lookups with product set to telegram_stars, the telegram_username exactly as your customer typed it, and the quantity. 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.
| Case | What the lookup answers | What to show and do |
|---|---|---|
| No photo | 201 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 found | 422 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 verify | 503 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. |
// npm install axiosimport axios from 'axios';try { const { status, data: lookup } = await axios. post( 'https:// sandbox-api. nasfampay. com/ v1/ recipient-lookups', { product: 'telegram_ stars', telegram_ username: 'nasfam_ test_ ok', quantity: 50, }, { 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
- Your customer types a Telegram username on your page.
- Your server looks the username up with
POST /recipient-lookups, using your key. - Your page shows the name, and the photo when there is one.
- Your customer confirms it is the account they mean.
- Your server creates the order.
- 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.
| Field | Description |
|---|---|
| Productproduct ยท string ยท required | telegram_stars. |
| Usernameusername ยท string ยท required | The Telegram username: name, @name or t.me/name. |
| Quantityquantity ยท integer ยท required | How many Stars. GET /products gives the min, max and step in force. |
| Max amountmax_ | Optional. The most the order may charge, as an amount in US cents with its currency of USD. |
| Referencereference ยท string | Optional. 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.
// 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_ stars', username: 'nasfam_ test_ ok', quantity: 50, }, { 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. Onlysucceededmeans 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.
{ "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}7. Track the order
Read the order with GET /orders/{id} until its status is final. Wait longer between reads each time.
| Status | Your money | What to do |
|---|---|---|
| Processingprocessing | Held. Delivery is in progress. | Wait for the next state. |
| Succeededsucceeded | Captured. The order is paid for. | Nothing. completed_at is set. |
| Failedfailed | Released back to available. | Read status_reason; order again if it makes sense. |
| Under reviewunder_ | Your 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.
// 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: trueand 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:
- Verify the signature over the raw body, and refuse a stale timestamp.
- Answer quickly, then do the work.
- Record the event
idand ignore one you have seen. An event can arrive more than once. - Ignore an event type you do not handle, and act on no test event. New types will be added.
- Keep the highest
versionyou 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.
// 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 see | What to do |
|---|---|
insufficient_funds | The order costs more than available. Nothing was held. Add test funds, then send the same request with the same key. |
recipient_not_found | Nobody has this username. Nothing was held. Ask your customer to check it. |
recipient_not_eligible | The account cannot receive this product. Nothing was held. Do not retry. |
invalid_request | param names the field at fault. Check quantity against the product's selection on GET /products. |
price_changed | The order would cost more than your max_amount. Nothing was held. Raise the ceiling or drop it, with a new key. |
idempotency_key_reused | This key was sent before with a different body. One key per purchase, and the same body on every retry. |
idempotency_in_progress | The first attempt is still running. Wait the seconds in Retry-After, then send the same request with the same key. |
rate_limited | Wait the seconds in Retry-After, then send the same request with the same key. |
key_environment_mismatch | The 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 5xx | UNKNOWN, 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.
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.
Related guides
- Telegram Stars: the product, its bounds and its advanced flow.
- Check and confirm the recipient: the confirmation screen, case by case.
- Create a test order: the whole order as one program for your server.
- Idempotency and safe retries: what a key binds, and for how long.
- Quotes: show your customer a price that holds, before the order.
