Skip to content

Instantly share code, notes, and snippets.

@mthri
Created May 12, 2024 11:39
Show Gist options
  • Save mthri/1696b8cbf1f70de3b4efe50f7220f7c1 to your computer and use it in GitHub Desktop.
Save mthri/1696b8cbf1f70de3b4efe50f7220f7c1 to your computer and use it in GitHub Desktop.
Extracting and Verifying Telegram Web App Data in Python
import hashlib
import hmac
TELEGRAM_BOT_TOKEN = 'BOT_TOKEN
def extract_telegram_web_app_data(telegram_init_data: str) -> dict:
return dict(qc.split('=') for qc in telegram_init_data.split('&'))
def verify_telegram_web_app_data(telegram_init_data: str) -> bool:
init_data = dict(qc.split('=') for qc in telegram_init_data.split('&'))
hash_value = init_data.pop('hash', None)
data_to_check = '\n'.join(f'{key}={init_data[key]}' for key in sorted(init_data.keys()) if key != 'hash')
secret_key_stage1 = hmac.new(
key=bytes('WebAppData', 'utf-8'),
msg=bytes(TELEGRAM_BOT_TOKEN, 'utf-8'),
digestmod=hashlib.sha256
).digest()
computed_hash = hmac.new(
key=secret_key_stage1,
msg=bytes(data_to_check, 'utf-8'),
digestmod=hashlib.sha256
).hexdigest()
return computed_hash == hash_value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment