Created
May 12, 2024 11:39
Revisions
-
mthri created this gist
May 12, 2024 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,28 @@ 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