Telegram sends initData to your Web App, which can be verified on your backend using the following steps:
hash from the initData.initData (excluding the hash).hash.
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.")