Telegram Web App Data

User Information (JSON):

Init Data:

Environment Information (JSON):

Theme Information (JSON):

How to Verify initData on Backend

Telegram sends initData to your Web App, which can be verified on your backend using the following steps:

  1. Extract the hash from the initData.
  2. Sort and concatenate the key-value pairs in the remaining initData (excluding the hash).
  3. Generate a SHA-256 HMAC using your bot token.
  4. Compare the result with the received hash.

Example Backend Code (Python)

import hashlib
import hmac

def verify_init_data(init_data, bot_token):
    # Parse the initData and extract the 'hash' parameter
    params = dict([item.split('=') for item in init_data.split('&')])
    received_hash = params.pop('hash', None)

    # Sort the remaining params and concatenate them
    sorted_params = sorted([f'{k}={v}' for k, v in params.items()])
    data_check_string = '\n'.join(sorted_params)

    # Generate HMAC-SHA256 using the bot token as the key
    secret_key = hmac.new(key=bot_token.encode(), msg=data_check_string.encode(), digestmod=hashlib.sha256).hexdigest()

    # Compare the generated hash with the received hash
    return hmac.compare_digest(secret_key, received_hash)
        

Usage:

# Example usage in a backend API
init_data = "user_id=12345&auth_date=1631545578&hash=d70a1e5c..."
bot_token = "YOUR_BOT_TOKEN"

if verify_init_data(init_data, bot_token):
    print("Init data is verified and valid.")
else:
    print("Init data verification failed.")