Skip to content

Instantly share code, notes, and snippets.

@shlyk
Last active April 28, 2022 08:27
Show Gist options
  • Save shlyk/0facaccd939c613da736d677bb41b3fa to your computer and use it in GitHub Desktop.
Save shlyk/0facaccd939c613da736d677bb41b3fa to your computer and use it in GitHub Desktop.
Web Apps for Telegram Bots: Validating data received via the Web App
import { createHmac } from 'crypto';
function isValidSignature(checkString) {
const decoded = decodeURIComponent(checkString)
.split('&')
.map(chunk => chunk.split('='))
.reduce((accumulator, [key, value]) => ({ ...accumulator, [key]: value }), {});
const user = JSON.parse(decoded.user);
const dataCheckString = Object.entries(decoded)
.filter(([key]) => key !== 'hash')
.map(([key, value]) => `${key}=${value}`)
.sort()
.join('\n');
const secretKey = createHmac('sha256', 'WebAppData')
.update(process.env.TELEGRAM_BOT_TOKEN)
.digest();
const hmac = createHmac('sha256', secretKey)
.update(dataCheckString, 'utf-8')
.digest('hex');
const isValid = hmac === decoded.hash;
return { isValid, user };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment