Skip to content

Instantly share code, notes, and snippets.

@MakStashkevich
Last active November 30, 2024 09:37
Show Gist options
  • Save MakStashkevich/7ae71729adbe3cbe2a662a7e16df6ea2 to your computer and use it in GitHub Desktop.
Save MakStashkevich/7ae71729adbe3cbe2a662a7e16df6ea2 to your computer and use it in GitHub Desktop.
Telegram Web App Bot (Validate hash function) on Javascript (JS or NodeJs)
// Bot token
const bot_token = '0123456789:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
// https://core.telegram.org/bots/webapps#validating-data-received-via-the-web-app
function isValidHash() {
// Parse query data
const parsedData = Telegram.Utils.urlParseQueryString(Telegram.WebApp.initData)
// Get Telegram hash
const hash = parsedData.hash
// Remove 'hash' value & Sort alphabetically
const data_keys = Object.keys(parsedData).filter(v => v !== 'hash').sort()
// Create line format key=<value>
const items = data_keys.map(key => key + '=' + parsedData[key])
// Create check string with a line feed
// character ('\n', 0x0A) used as separator
// result: 'auth_date=<auth_date>\nquery_id=<query_id>\nuser=<user>'
const data_check_string = items.join('\n')
function HMAC_SHA256(value, key) {
const crypto = require('crypto');
return crypto.createHmac('sha256', key).update(value).digest()
}
function hex(bytes) {
return bytes.toString('hex');
}
// Generate secret key
const secret_key = HMAC_SHA256(bot_token, 'WebAppData')
// Generate hash to validate
const hashGenerate = hex(HMAC_SHA256(data_check_string, secret_key))
// Return bool value is valid
return Boolean(hashGenerate === hash)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment