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

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

{
    "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"
}

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.

FieldTypeMeaning
external_refstring, optionalYour own reference for this user, at most 100 characters. It is stored with the subscription, and you can send codes to it.
msisdnstring, optionalThe 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_phoneboolean, optionaltrue: 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.
ttlinteger, optionalHow 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)

FieldMeaning
urlThe link to show to the user: https://t.me/<bot>?start=<token>.
tokenThe token inside the link.
codeThe pairing code: 6 letters and digits, without 0, O, 1 and I. The user opens the bot and types it; capitals do not matter.
botThe bot the user will talk to, for example @Two_Factor_io_Bot.
external_ref, msisdn, require_phoneWhat the link was made with. msisdn comes back as digits only.
noteOne sentence about what the user will be asked.
expires_atWhen 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.

ParameterReturns subscriptions with
refthis external_ref
msisdnthis phone number
usernamethis Telegram username, with or without @
statusthis 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
}
FieldMeaning
statuspending: 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.
msisdnThe phone number, digits only, or null.
msisdn_verifiedtrue when the user shared the number of the Telegram account; false when the number came from your link.
telegram_usernameThe Telegram username, or null. Users can change it.
languageThe language of the user's Telegram app when connecting, as far as we have texts for it: en or nl.
consent_atWhen 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.

FieldTypeMeaning
tostring, requiredThe recipient: a phone number, your external_ref, a Telegram @username or id:<subscription id>. See Who receives the code.
codestring, requiredThe code: 4 to 16 letters, digits or hyphens.
minutesinteger, optionalHow 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.
languagestring, optionalLanguage of the standard text: en or nl. Default: the language of the subscription, otherwise en.
textstring, optionalYour 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_idstring, optionalYour 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.
channelsarray or string, optionalWhich 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.

FieldMeaning
idThe id of this message.
kindAlways otp.
channeltelegram or sms: how it was sent.
statusSee Message status.
toThe recipient as you sent it.
request_idYour request id, or null.
subscription_idThe subscription that was found for to, or null.
errorWhy it failed, or null.
created_at, status_atWhen 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 sendWe look for
@janedoethe subscription with this Telegram username
id:311the 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 0031612345678the subscription with this phone number. When there is none, the digits are tried as an external_ref.
anything elsethe 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

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"]}'
AnswerWhat happened
201Telegram accepted the message. You are done.
404 no_subscriptionThe user is not connected to the bot: never connected, stopped, or blocked the bot.
409 blockedThe user has blocked the bot, and we found out when sending.
502 send_failedTelegram 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.

Message status

StatusMeaning
sentTelegram accepted the message, or the SMS was handed to the network. For Telegram this is the final status: Telegram does not report delivery.
deliveredSMS only: the network reported the SMS as delivered.
failedNot sent or not delivered; error says why.
expiredSMS only: the network gave up delivering the SMS.
blockedThe user has blocked the bot. The subscription is set to blocked as well.
queuedAccepted 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

What happens next depends on require_phone:

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"
        }
    }
}
EventWhendata
subscription.createdA 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.blockedThe user blocked the bot.subscription
subscription.restoredThe user unblocked the bot.subscription
subscription.removedThe user sent /stop, or you ended the subscription through the API.subscription
reply.receivedThe 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.expiredThe delivery report of an SMS fallback came in.message_id, channel, status

Three things to keep in mind:

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:

HeaderValue
X-TwoFactor-Eventthe event, for example subscription.created
X-TwoFactor-Timestampthe time of sending, in seconds since 1970
X-TwoFactor-Signaturesha256= 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

StatuserrorMeaning
400invalid_jsonThe body is not valid JSON.
400invalid_parameterA field is missing, too long or has a wrong value. The message names the field.
401unauthorizedNo API key was sent.
401invalid_keyThe key is unknown, the service is not active, or Two-Factor is switched off for the account.
402insufficient_creditThe credit of your BudgetSMS account is too low for this message. Nothing was sent.
402fee_unpaidThe monthly fee could not be taken from your credit for more than 7 days. Top up to continue.
403destination_blockedCodes 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.
403phone_not_verifiedYour 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.
404not_foundUnknown address, or no subscription or code with this id for your service.
404no_subscriptionNo active subscription matches to, and SMS was not possible. Adds message_id and to.
404telegram_not_allowedA subscription was found, but channels leaves Telegram out and SMS was not possible. Adds message_id and to.
405method_not_allowedThe address exists, but not with this method. The Allow header lists the right ones.
409blockedThe user has blocked the bot and SMS was not possible. Adds message_id.
502send_failedTelegram did not accept the message and SMS was not possible. Adds message_id.
502sms_failedTelegram was not possible and the SMS fallback failed; the message says why. Adds message_id.
503bot_unavailableThe bot of your service is not available right now.
503no_priceNo Telegram price is set for this destination. Contact us.
500server_errorSomething 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

Your own prices and fees are in the BudgetSMS control panel under Two-Factor (Telegram).

Rules of use