You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Telegram授权验证哈希不匹配问题求助(Node.js)

Telegram Web App授权验证哈希不匹配问题解决

问题根源

你遇到的哈希不匹配主要来自三个核心错误:

  • 错误拆解user字段:Telegram授权数据中user是独立键,值为用户对象的原始字符串形式,你将其拆分为first_name、id等单独字段,导致验证字符串完全不符合规则。
  • 遗漏query_id字段:验证必须包含所有除hash外的原始字段,你去掉了query_id,直接破坏了哈希计算的数据源。
  • 时间戳单位不匹配:auth_date是秒级时间戳,Date.now()返回毫秒级,直接相减会导致过期判断逻辑错误(比如1天阈值会被误判为86秒)。

修正后的验证代码

const crypto = require('crypto');

const checkTelegramAuthorization = (authData) => {
  try {
    const BOT_TOKEN = '7343419643...'; // 替换为你的机器人Token
    const checkHash = authData.hash;
    // 复制原始数据,避免修改原对象
    const data = {...authData};
    delete data.hash;

    // 按键名字典序升序排列,生成"key=value"格式的字符串数组
    const dataCheckArray = Object.entries(data)
      .sort(([keyA], [keyB]) => keyA.localeCompare(keyB))
      .map(([key, value]) => {
        // user字段需转为无缩进的JSON字符串,和Telegram传递格式完全一致
        if (key === 'user' && typeof value === 'object') {
          return `${key}=${JSON.stringify(value)}`;
        }
        return `${key}=${value}`;
      });

    const dataCheckString = dataCheckArray.join('\n');

    // 生成验证密钥:先以"WebAppData"为密钥对BOT_TOKEN做HMAC-SHA256,取二进制结果作为后续哈希密钥
    const secretKey = crypto.createHmac('sha256', 'WebAppData').update(BOT_TOKEN).digest();
    const calculatedHash = crypto.createHmac('sha256', secretKey).update(dataCheckString).digest('hex');

    // 哈希匹配验证
    if (calculatedHash !== checkHash) {
      console.log('哈希不匹配');
      return false;
    }

    // 授权过期验证(统一转为秒级时间戳)
    const now = Math.floor(Date.now() / 1000);
    if (now - parseInt(data.auth_date) > 86400) { // 超过1天视为过期
      console.log('授权已过期');
      return false;
    }

    return true;
  } catch (error) {
    console.error('验证出错:', error);
    return false;
  }
};

关键注意事项

  • 确保user字段的JSON字符串无缩进、键名用双引号,和Telegram传递的原始格式完全一致。
  • 机器人Token必须准确,不能包含多余空格或字符。
  • 必须使用完整的原始auth_data结构,禁止自行修改或删除字段。

内容的提问来源于stack exchange,提问作者TuanAnh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 04:43:15