# Authorization via Telegram Gateway: Quick-start Guide

The [Telegram Gateway API](/gateway.md) allows any service to send authorization codes through Telegram instead of traditional SMS, offering a more **affordable**, **secure**, and **reliable** alternative. This guide will help you quickly integrate the API into your service. For more information, see:

- [Full Gateway API Reference for Developers](/gateway/api.md)
- [Gateway Overview](/gateway.md)
- [Gateway FAQ](/gateway.md#faq)
- [Gateway Terms of Service](https://telegram.org/tos/gateway)

### Index
- [Before you Start](#before-you-start)
- [Sending Auth Codes](#sending-auth-codes)
- [Checking the Authorization Status](#checking-the-authorization-status)
- [Receiving Reports](#receiving-reports)

### Before you Start
> **TLDR**: open [this page](https://gateway.telegram.org) and log in with your Telegram phone number, then fund your account [here](https://gateway.telegram.org/account/budget) and note down your [API token](https://gateway.telegram.org/account/api).

Before getting started, you'll need to **create an account** on our [dedicated gateway platform](https://gateway.telegram.org). To do this, navigate to the Gateway platform and click ‘*Log in to Start*’, then confirm your login via Telegram. If this is your first time using the platform, you'll be prompted to provide some basic information about yourself and your business.

> For testing purposes, you’ll be able to send **free verification messages** to the Telegram account tied to the number you used to log in.

#### Funding your Account
To send messages to other Telegram users via the Gateway API, you’ll need to fund your account. To do so, simply navigate to [this page](https://gateway.telegram.org/account/budget) and click *‘Add Funds on Fragment’*, then follow the instructions on Fragment.

On the same page you’ll find a detailed transaction history showing your deposits and expenses.

#### Obtaining your API Token
Before invoking API methods, you must obtain an access token in your Telegram Gateway account settings. To do so, open [this page](https://gateway.telegram.org/account/api) and click ‘*Copy Token*’.

The token must be passed in every request in one of two ways:

- In the HTTP header: `Authorization: Bearer <token>`
- As the `access_token` parameter.

In this guide, we’ll assume you decided to use a *bearer token*.

> To increase security, you can limit which IPs or IP ranges are allowed to use your API token from [this page](https://gateway.telegram.org/account/api).

#### Querying the API
The API can be queried with GET and POST HTTP methods with your language or framework of choice. Throughout this guide, we’ll use Python as an example and assume you defined the following:

```
import requests

# Base API url, your Gateway API token and a phone number
BASE_URL = 'https://gatewayapi.telegram.org/'
TOKEN = 'AAEFAAAAQKI_mDsJppSEQRr3kLOz9SatBxq48BgQLSHLRv'
PHONE = '+391234567890'
HEADERS = {
    'Authorization': f'Bearer {TOKEN}',
    'Content-Type': 'application/json'
}

# Function to query the API
def post_request_status(endpoint, json_body):
    url = f"{BASE_URL}{endpoint}"
    response = requests.post(url, headers=HEADERS, json=json_body)
    if response.status_code == 200:
        response_json = response.json()
        if response_json.get('ok'):
            res = response_json.get('result', {})
            return res
        else:
            error_message = response_json.get('error', 'Unknown error')
            print(f"Error: {error_message}")
            return None
    else:
        print(f"Failed to get request status: HTTP {response.status_code}")
        return None
```

### Sending Auth Codes
> **TLDR**: Pass a phone number ([E.164](https://en.wikipedia.org/wiki/E.164) format) to [this method](/gateway/api.md#sendverificatiomessage) to directly send an auth code to the user. If you need a dry run to verify your code can be delivered, use [this method](/gateway/api.md#checksendability).

To send the user a code generated by Telegram, you can use the [sendVerificationMessage](/gateway/api.md#sendverificatiomessage) method:

```
endpoint = 'sendVerificationMessage'

json_body = {
    'phone_number': PHONE,         # Must be the one tied to request_id
    'code_length': 6,              # Ignored if you specify your own 'code'
    'ttl': 60,                     # 1 minute
    'payload': 'my_payload_here',  # Not shown to users
    'callback_url': 'https://my.webhook.here/auth'
}

result = post_request_status(endpoint, json_body)
```

> If the method returns an error (e.g., because the user cannot receive codes), you **will not be charged**. On success, it will return a [RequestStatus](/gateway/api.md#requeststatus) object.

You can optionally specify the `sender_username` parameter, designating a **verified channel** you own as the one from which the code will be sent to the user. When sending codes to yourself for testing purposes, the channel does not need to be verified.

#### Checking that codes can be delivered 
Before sending, you can also optionally use the [checkSendAbility](/gateway/api.md#checksendability) method to verify that the user you want to target can receive messages on Telegram. This is especially useful when you generated a code yourself but need to check that it can be delivered before sending it out to the user through the Gateway API.

```
endpoint = 'checkSendAbility'

json_body = {
    'phone_number': PHONE # E.164 format
}

result = post_request_status(endpoint, json_body)

if result:
    request_id = result.get('request_id')
    print(f"Request ID: {request_id}")
```

> You will be **automatically charged** in advance for the price of **one message** if the method indicates that the user can be contacted – regardless of whether you eventually send one. If the method returns an error (e.g., because the user cannot receive codes), you **will not be charged**. 

If the check succeeds and you ultimately decide to send a message, use the `request_id` returned by the `checkSendAbility` method to avoid paying the message fee again.

#### Revoking Codes

You can optionally revoke codes even before they expire by passing the relevant `request_id` to the [revokeVerificationMessage](/gateway/api.md#revokeverificatiomessage) method. Messages which were already read will not be deleted.

> Note that revoked codes are not refunded. If you need to send codes free of charge for testing purposes, direct them to your own phone number.

### Checking the Authorization Status

If you let Telegram generate a code for you (i.e., you did not provide a `code` param in your request), you can use the [checkVerificationStatus](/gateway/api.md#checkverificationstatus) method to verify the OTP submitted by your user.

```
endpoint = 'checkVerificationStatus'

json_body = {
    'request_id': request_id, # Relevant request id
    'code': CODE,             # The code the user entered in your app
}

result = post_request_status(endpoint, json_body)

# Assuming the request was successful
status = result.get('verification_status', {}).get('status')
print(status == 'code_valid') # True if the user entered the correct code
```

> Even if you set the code yourself, you should call this method after the user has entered a code, so that we can display accurate statistics on your Gateway interface.

### Receiving Reports
When you include a `callback_url` parameter in your [sendVerificationMessage](/gateway/api.md#sendverificatiomessage) request, the Gateway API will send a POST request to that URL containing a [delivery report](/gateway/api.md#reportdelivery) for the message. The payload of the POST request will be a JSON object representing the relevant [RequestStatus](/gateway/api.md#requeststatus) object.
When processing reports, you **must** verify the integrity of the data you receive as documented [here](/gateway/api.md#checking-report-integrity).

----

> **Note**: The latest API documentation is available [here](/gateway/api.md), with in-depth explanations for each method and parameter. This guide is intended to get you started quickly and assumes you’re familiar with programming, correctly handling errors, adequately securing and storing phone numbers, responses and credentials.

