Two-Factor API
Deliver your verification codes in Telegram, with SMS from your BudgetSMS account as the fallback. You generate the code and check what the user types. We deliver it.
curl https://api.two-factor.io/v1/codes \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"to": "31612345678", "code": "482913"}'
Two-Factor bot
Acme: your verification code is 482913. It is valid for 5 minutes. If you did not request this, ignore this message.
Not connected in Telegram? The same text arrives as an SMS.
Acme: your verification code is 482913. It is valid for 5 minutes. If you did not request this, ignore this message.
The API lives at https://api.two-factor.io. Every endpoint is under /v1, answers in JSON and needs the API key of one of your services.
Before you start
- A BudgetSMS account with Two-Factor switched on. Two-Factor is part of BudgetSMS. Contact us and we switch it on for your account.
- A service. We create it for you. A service is what your users see in the bot: its name stands in front of every code. Most customers need one service per app or website.
- The API key of that service. You get it when the service is created. It is shown only once. In the BudgetSMS control panel, under Two-Factor (Telegram), you can make a new key at any time; the old key stops working at once.
- Credit. Telegram messages, SMS fallbacks and the monthly fee are paid from the credit of your BudgetSMS account.
Your users talk to a bot we operate: the shared bot @Two_Factor_io_Bot, or a bot in your own name. GET /v1/me tells you which bot your service uses.
Quick start
1. Create a link for your user
A user has to connect to the bot once before you can reach them in Telegram. Ask for a link and give it your own reference for this user, for example your user id.
curl https://api.two-factor.io/v1/links \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"external_ref": "user-4821"}'
{
"token": "kq3ZxW8mB1nT5vYc2LrA9dHe",
"url": "https://t.me/Two_Factor_io_Bot?start=kq3ZxW8mB1nT5vYc2LrA9dHe",
"code": "K7WQ4N",
"bot": "@Two_Factor_io_Bot",
"external_ref": "user-4821",
"msisdn": null,
"require_phone": false,
"note": "The user only taps Start; a number you pass is stored as given by you, not verified by Telegram.",
"expires_at": "2026-11-25 14:02:11"
}
2. Let the user connect
Show url as a button or a QR code. The user opens it in Telegram and taps Start. On another device, the user can open the bot and type the pairing code from code instead.
3. Send a code
Generate a code, send it, and check what the user types on your side, exactly as you do with SMS codes.
curl https://api.two-factor.io/v1/codes \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"to": "user-4821", "code": "482913"}'
{
"message": {
"id": 1042,
"kind": "otp",
"channel": "telegram",
"status": "sent",
"to": "user-4821",
"request_id": null,
"subscription_id": 311,
"error": null,
"created_at": "2026-11-24 14:05:37",
"status_at": "2026-11-24 14:05:37"
}
}
Authentication
Send the API key of your service with every request:
Authorization: Bearer YOUR_API_KEY
If your HTTP client cannot set the Authorization header, send the key as X-Api-Key: YOUR_API_KEY.
A key belongs to one service. Without a key the answer is 401 unauthorized. An unknown key, a service that is not active or an account on which Two-Factor is switched off gives 401 invalid_key. Keep the key on your server; never put it in a web page or an app.
Requests and responses
- Send the body as JSON with
Content-Type: application/json. A form-encoded body is accepted as well. - Every answer is JSON. A successful create returns
201, other successful calls200. - An error has an
errorcode for your program and amessagefor a person. Some errors add fields such asmessage_id. See Errors. - Times in answers are in Dutch local time (Europe/Amsterdam), written as
YYYY-MM-DD HH:MM:SS. Onlysent_atin a webhook carries a time zone.
{
"error": "invalid_parameter",
"message": "code is required: 4 to 16 letters, digits or hyphens, generated and checked by you."
}
Your service
GET/v1/me
Returns the service the key belongs to, its bot and a few counts. A good first call to test your key.
{
"service": {
"id": 12,
"name": "Acme",
"slug": "acme",
"callback_url": "https://example.com/hooks/two-factor",
"created_at": "2026-11-24 13:40:02"
},
"bot": {
"username": "Two_Factor_io_Bot",
"shared": true,
"link": "https://t.me/Two_Factor_io_Bot"
},
"subscriptions": {
"active": 311,
"blocked": 4
},
"messages_30d": 1873,
"environment": "production"
}
Create a subscribe link
POST/v1/links
Makes a link and a pairing code with which one user connects to your service. A link works once and until it expires.
| Field | Type | Meaning |
|---|---|---|
external_ref | string, optional | Your own reference for this user, at most 100 characters. It is stored with the subscription, and you can send codes to it. |
msisdn | string, optional | The phone number you have for this user, in international format: 6 to 20 digits, with or without a leading + or 00. It is stored with the subscription as given by you, not verified. |
require_phone | boolean, optional | true: the user has to share the phone number of the Telegram account with a button in the bot. That number is stored as verified. Default true when you give neither external_ref nor msisdn, otherwise false. |
ttl | integer, optional | How long the link is valid, in seconds: 60 to 604800 (7 days). Default 86400 (one day). |
Give at least an external_ref or an msisdn, or leave require_phone on. Otherwise you could not address the subscription later, and the call returns 400 invalid_parameter.
Answer (201)
| Field | Meaning |
|---|---|
url | The link to show to the user: https://t.me/<bot>?start=<token>. |
token | The token inside the link. |
code | The pairing code: 6 letters and digits, without 0, O, 1 and I. The user opens the bot and types it; capitals do not matter. |
bot | The bot the user will talk to, for example @Two_Factor_io_Bot. |
external_ref, msisdn, require_phone | What the link was made with. msisdn comes back as digits only. |
note | One sentence about what the user will be asked. |
expires_at | When the link and the pairing code stop working. |
List subscriptions
GET/v1/subscriptions
A subscription is one Telegram chat connected to your service. The list returns at most 100 subscriptions, newest first. Narrow it down with query parameters; all are optional and can be combined.
| Parameter | Returns subscriptions with |
|---|---|
ref | this external_ref |
msisdn | this phone number |
username | this Telegram username, with or without @ |
status | this status: pending, active, blocked or stopped |
curl "https://api.two-factor.io/v1/subscriptions?ref=user-4821" \
-H "Authorization: Bearer YOUR_API_KEY"
{
"subscriptions": [
{
"id": 311,
"status": "active",
"msisdn": "31612345678",
"msisdn_verified": true,
"external_ref": "user-4821",
"telegram_username": "janedoe",
"language": "en",
"consent_at": "2026-11-24 14:03:20",
"last_message_at": "2026-11-24 14:05:37",
"created_at": "2026-11-24 14:03:05"
}
],
"count": 1
}
| Field | Meaning |
|---|---|
status | pending: the user opened the link but has not shared the phone number yet. active: connected. blocked: the user blocked the bot. stopped: ended by the user or by you. |
msisdn | The phone number, digits only, or null. |
msisdn_verified | true when the user shared the number of the Telegram account; false when the number came from your link. |
telegram_username | The Telegram username, or null. Users can change it. |
language | The language of the user's Telegram app when connecting, as far as we have texts for it: en or nl. |
consent_at | When the user connected. |
End a subscription
DELETE/v1/subscriptions/{id}
Sets the subscription to stopped and returns it. You will not reach this user in Telegram until they connect again through a new link. An unknown id returns 404 not_found.
curl -X DELETE https://api.two-factor.io/v1/subscriptions/311 \
-H "Authorization: Bearer YOUR_API_KEY"
Send a code
POST/v1/codes
Delivers a code you generated. We do not store the code and do not check what the user types: that stays on your side.
| Field | Type | Meaning |
|---|---|---|
to | string, required | The recipient: a phone number, your external_ref, a Telegram @username or id:<subscription id>. See Who receives the code. |
code | string, required | The code: 4 to 16 letters, digits or hyphens. |
minutes | integer, optional | How long the code is valid according to you, 1 to 1440. Default 5. It only fills in the text; the code does not expire on our side. |
language | string, optional | Language of the standard text: en or nl. Default: the language of the subscription, otherwise en. |
text | string, optional | Your own text instead of the standard one, at most 1000 characters. It must contain {code}; {service} and {minutes} are optional. In the shared bot the name of your service is put in front when your text does not contain {service}. |
request_id | string, optional | Your own id for this request, at most 64 characters. A second request with the same id sends nothing and returns the first message with "duplicate": true and status 200. Use it when you retry after a timeout. |
channels | array or string, optional | Which channels may be used: telegram, sms or both, as an array or a comma-separated string. Default both. See Telegram first, SMS as fallback. |
The standard text is: Acme: your verification code is 482913. It is valid for 5 minutes. If you did not request this, ignore this message. In a bot of your own, the name of the service is left out.
Answer (201)
The message, with the channel it went through and its status. Keep message.id if you want to ask for the status later.
| Field | Meaning |
|---|---|
id | The id of this message. |
kind | Always otp. |
channel | telegram or sms: how it was sent. |
status | See Message status. |
to | The recipient as you sent it. |
request_id | Your request id, or null. |
subscription_id | The subscription that was found for to, or null. |
error | Why it failed, or null. |
created_at, status_at | When the message was made and when the status last changed. |
The earlier name POST /v1/otp still works and does the same.
Status of a code
GET/v1/codes/{id}
Returns the message in the same form as when you sent it, with its current status. An unknown id returns 404 not_found.
curl https://api.two-factor.io/v1/codes/1042 \
-H "Authorization: Bearer YOUR_API_KEY"
Who receives the code
We look for an active subscription of your service that matches to:
| You send | We look for |
|---|---|
@janedoe | the subscription with this Telegram username |
id:311 | the subscription with this id, as returned by the list and the webhooks. Works even when the user has no number, reference or username. |
31612345678, +31612345678 or 0031612345678 | the subscription with this phone number. When there is none, the digits are tried as an external_ref. |
| anything else | the subscription with this external_ref |
When several subscriptions match, the newest one is used. When none matches and to is a phone number, the code can still go out as an SMS.
A reference that consists of 6 to 20 digits looks like a phone number. If you use numeric user ids as external_ref, send codes to id:<subscription id>, or make sure the subscription has a phone number: the number of the subscription is always used for the SMS fallback and for the price.
Telegram first, SMS as fallback
- Telegram is used when
channelscontainstelegramand the recipient has an active subscription. - SMS is used when Telegram is not possible or does not accept the message, and all of these are true:
channelscontainssms, SMS fallback is on for your service, and we have a phone number. That is the number of the subscription, ortoitself when it is a phone number.
The SMS is sent through your own BudgetSMS account: at your SMS price, over your routes, with the sender ID Two-Factor. If your BudgetSMS account only accepts API calls from certain IP addresses, the address that calls Two-Factor has to be one of them.
When neither channel is possible, the answer is 404 no_subscription (no subscription was found for to) or 404 telegram_not_allowed (a subscription exists, but channels leaves Telegram out). When the user has blocked the bot and SMS is not possible, the answer is 409 blocked.
You switch SMS fallback on or off per service in the BudgetSMS control panel. Send "channels": ["telegram"] for a code that must never cost an SMS.
Telegram only, with your own SMS as fallback
You can also keep the SMS in your own hands: ask us for Telegram only, and send the SMS yourself through the BudgetSMS API when Telegram is not possible. You choose the sender ID and the text of the SMS, and we do not need the phone number of your user.
curl https://api.two-factor.io/v1/codes \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{"to": "user-4821", "code": "482913", "request_id": "login-77120", "channels": ["telegram"]}'
| Answer | What happened |
|---|---|
201 | Telegram accepted the message. You are done. |
404 no_subscription | The user is not connected to the bot: never connected, stopped, or blocked the bot. |
409 blocked | The user has blocked the bot, and we found out when sending. |
502 send_failed | Telegram did not accept the message. |
The rule for your program: any answer other than 201 means that nothing went out through Telegram, so you send the SMS. A failed attempt costs nothing.
- No answer at all. After a timeout, repeat the request with the same
request_id. If the first request reached us, you get200with that message: statussentmeans the code is in Telegram, any other status means you send the SMS. Use a newrequest_idfor every new code. - Sent is not read. Telegram does not tell us whether the user saw the message. Give your user a way to ask for the code by SMS, such as a button next to the field where the code is typed.
- For every code of a service. Switch SMS fallback off for the service in the control panel and you can leave
channelsout. - The price without a phone number. A Telegram message to a subscription without a number costs the price of the country of your account. See Prices and billing.
Message status
| Status | Meaning |
|---|---|
sent | Telegram accepted the message, or the SMS was handed to the network. For Telegram this is the final status: Telegram does not report delivery. |
delivered | SMS only: the network reported the SMS as delivered. |
failed | Not sent or not delivered; error says why. |
expired | SMS only: the network gave up delivering the SMS. |
blocked | The user has blocked the bot. The subscription is set to blocked as well. |
queued | Accepted and on its way; you only see this for a moment. |
The status of an SMS follows the delivery reports of the network and is updated every minute. Ask for it with GET /v1/codes/{id}, or receive the code.delivered, code.failed and code.expired webhooks.
How users connect
- With the link. The user opens
urland taps Start in Telegram. - With the pairing code. The user opens the bot and types the 6 characters from
code. Useful when your page is on a computer and Telegram is on the phone.
What happens next depends on require_phone:
- Without it, tapping Start is the user's consent and the subscription is active at once. A number you passed in
msisdnis stored as not verified. - With it, the bot asks the user to share the phone number of the Telegram account with one tap. The subscription is
pendinguntil then, and the number is stored as verified. A bot can never read a phone number by itself; the share button is Telegram's own way of asking.
In the bot the user can send /services to see what is connected, /stop to end a connection and /help for an explanation. Anything else the user types is passed on to you as a reply.received webhook.
Webhooks
Set a callback URL for your service in the BudgetSMS control panel and we tell you when something happens. Each webhook is a POST with a JSON body:
{
"event": "subscription.created",
"service": "acme",
"sent_at": "2026-11-24T14:03:20+01:00",
"data": {
"subscription": {
"id": 311,
"status": "active",
"msisdn": "31612345678",
"msisdn_verified": true,
"external_ref": "user-4821",
"telegram_username": "janedoe",
"language": "en",
"consent_at": "2026-11-24 14:03:20",
"last_message_at": "2026-11-24 14:03:20",
"created_at": "2026-11-24 14:03:05"
}
}
}
| Event | When | data |
|---|---|---|
subscription.created | A user connected to your service: the subscription became active. Sent again, with the same id, when a user who stopped or was blocked connects again. | subscription |
subscription.blocked | The user blocked the bot. | subscription |
subscription.restored | The user unblocked the bot. | subscription |
subscription.removed | The user sent /stop, or you ended the subscription through the API. | subscription |
reply.received | The user sent a text message in the bot that is not a command or a pairing code. When the user is connected to several services in the same bot, it goes to the one with the most recent activity. | subscription, text, telegram_message_id |
code.delivered, code.failed, code.expired | The delivery report of an SMS fallback came in. | message_id, channel, status |
Three things to keep in mind:
- No webhook is sent when a user who is already connected opens another link of yours: the subscription stays active and takes the
external_refof the new link. No webhook is sent either when you stop a subscription with the button in the control panel. - Events are not kept for later. What happens while your service has no callback URL is not sent afterwards; read the current state with
GET /v1/subscriptions. - Webhooks do not always arrive in order. A retry carries the original body, so a retried webhook can arrive after newer events for the same subscription. Compare
sent_atwith the last event you applied, or look the subscription up.
Check that a webhook comes from us
Each service has a callback secret; you find it in the control panel next to the callback URL. We sign every webhook with it. The request carries these headers:
| Header | Value |
|---|---|
X-TwoFactor-Event | the event, for example subscription.created |
X-TwoFactor-Timestamp | the time of sending, in seconds since 1970 |
X-TwoFactor-Signature | sha256= followed by the HMAC-SHA256, in hexadecimal, of the timestamp, a dot and the raw body, with your callback secret as the key |
Compute the same signature over the body exactly as you received it, before parsing it, and compare. Refuse a webhook whose timestamp is more than a few minutes old.
PHP
$body = file_get_contents('php://input');
$timestamp = $_SERVER['HTTP_X_TWOFACTOR_TIMESTAMP'] ?? '';
$expected = 'sha256=' . hash_hmac('sha256', $timestamp . '.' . $body, $callbackSecret);
if (!hash_equals($expected, $_SERVER['HTTP_X_TWOFACTOR_SIGNATURE'] ?? '') || abs(time() - (int) $timestamp) > 300) {
http_response_code(400);
exit;
}
$event = json_decode($body, true);
Node.js
const crypto = require('crypto');
// rawBody: the body exactly as received (a Buffer or string), not the parsed JSON.
// In Express, read it with express.raw({ type: 'application/json' }). headers: req.headers.
function isFromTwoFactor(rawBody, headers, callbackSecret) {
const timestamp = String(headers['x-twofactor-timestamp'] || '');
const expected = Buffer.from('sha256=' + crypto.createHmac('sha256', callbackSecret)
.update(timestamp + '.').update(rawBody).digest('hex'));
const given = Buffer.from(String(headers['x-twofactor-signature'] || ''));
return given.length === expected.length
&& crypto.timingSafeEqual(given, expected)
&& Math.abs(Date.now() / 1000 - Number(timestamp)) <= 300;
}
Python
import hashlib, hmac, time
# headers: the request headers of your framework (request.headers in Flask, Django or FastAPI).
# In a plain dict the names are lower case: use "x-twofactor-timestamp" and "x-twofactor-signature".
def is_from_two_factor(raw_body: bytes, headers, callback_secret: str) -> bool:
timestamp = headers.get("X-TwoFactor-Timestamp", "")
given = headers.get("X-TwoFactor-Signature", "")
expected = "sha256=" + hmac.new(callback_secret.encode(), timestamp.encode() + b"." + raw_body, hashlib.sha256).hexdigest()
fresh = timestamp.isdigit() and abs(time.time() - int(timestamp)) <= 300
return fresh and hmac.compare_digest(expected.encode(), given.encode())
Answering and retries
Answer with a status in the 200 range within 8 seconds, connecting included; answer first and do slow work afterwards. The first attempt is made at once: the subscription.removed for a DELETE of yours reaches you before that call returns. Any other answer, a redirect or no answer counts as failed. We then try again with growing pauses of 1, 5, 15 and 60 minutes and 4, 12 and 24 hours: 8 attempts in all. After that the webhook is dropped. A webhook can arrive more than once, so make your handler safe to run twice.
Errors
| Status | error | Meaning |
|---|---|---|
| 400 | invalid_json | The body is not valid JSON. |
| 400 | invalid_parameter | A field is missing, too long or has a wrong value. The message names the field. |
| 401 | unauthorized | No API key was sent. |
| 401 | invalid_key | The key is unknown, the service is not active, or Two-Factor is switched off for the account. |
| 402 | insufficient_credit | The credit of your BudgetSMS account is too low for this message. Nothing was sent. |
| 402 | fee_unpaid | The monthly fee could not be taken from your credit for more than 7 days. Top up to continue. |
| 403 | destination_blocked | Codes to phone numbers from this country are not available for your account, by Telegram or by SMS. Nothing was sent or charged. Adds message_id and to. |
| 403 | phone_not_verified | Your account only delivers to users who shared the phone number of their Telegram account with the bot, and this user has not. Create a new link and let the user open it; the bot then asks for the number. Adds message_id and to. |
| 404 | not_found | Unknown address, or no subscription or code with this id for your service. |
| 404 | no_subscription | No active subscription matches to, and SMS was not possible. Adds message_id and to. |
| 404 | telegram_not_allowed | A subscription was found, but channels leaves Telegram out and SMS was not possible. Adds message_id and to. |
| 405 | method_not_allowed | The address exists, but not with this method. The Allow header lists the right ones. |
| 409 | blocked | The user has blocked the bot and SMS was not possible. Adds message_id. |
| 502 | send_failed | Telegram did not accept the message and SMS was not possible. Adds message_id. |
| 502 | sms_failed | Telegram was not possible and the SMS fallback failed; the message says why. Adds message_id. |
| 503 | bot_unavailable | The bot of your service is not available right now. |
| 503 | no_price | No Telegram price is set for this destination. Contact us. |
| 500 | server_error | Something went wrong on our side. It has been logged. |
A failed attempt that got as far as choosing a channel is stored as a message with status failed; its id is in message_id.
Prices and billing
- Per Telegram message. The price depends on the country of the recipient's phone number. When the subscription has no number, the country of your BudgetSMS account counts. The amount is taken from your credit before sending and returned when Telegram does not accept the message.
- Per SMS fallback. Your normal BudgetSMS price for that destination. No Telegram price is charged for a code that went out as an SMS.
- Per month. A fee for using the shared bot, or a higher fee per bot in your own name.
Your own prices and fees are in the BudgetSMS control panel under Two-Factor (Telegram).
Rules of use
- Send only codes and messages the user is waiting for. No advertising.
- Never ask a user for a password, a code or payment details through the bot.
- Do not put links in the text of a code.
- Do not pretend to be someone else: the name of your service has to be the name your users know you by.
- A user can stop at any time with
/stop. Respect it: do not send that user new links unless they ask.