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

Telegram授权哈希不匹配问题排查及API响应差异疑问

Telegram授权哈希不匹配问题排查与疑问

我尝试用JavaScript实现Telegram的PHP授权示例,但始终遇到哈希不匹配的问题。甚至运行原示例的PHP代码也失败,而且我生成的哈希和示例返回的完全一致。我怀疑是机器人设置的问题,试过将域名设为127.0.0.1及其他HTTPS域名,均无效,陷入困境。

我的JavaScript代码

'use strict';

const sha256 = require('crypto-js/sha256');
const hmacSHA256 = require('crypto-js/hmac-sha256');
const Hex = require('crypto-js/enc-hex');

const { ValidationError } = require('objection');

const data = {
id: 5528016998,
first_name: 'Lê Văn',
last_name: 'Hùng',
username: 'HungLV46',
photo_url: 'https://t.me/i/userpic/320/gy_L5Q2zLLZyUrtCw0Fh9D0oy0CuabiM2A0-68FY27Inz94yP7ypxCrAF7G7_asy.jpg',
auth_date: 1670774122,
hash: '893e4bd66128d8696d63aa285b0aff6e8b970cbe9c9e43dacfa9e2da7420c16c'
};

function verifyAuthorization(params) {
if ((new Date() - new Date(params.auth_date * 1000)) > 86400000) { // 毫秒单位
    throw new ValidationError('Authorization data is outdated');
}

const verificationParams = { ...params };
delete verificationParams.hash;

const message = Object.keys(verificationParams)
    .map(key => `${key}=${verificationParams[key]}`)
    .sort().join('\n');
const secretKey = sha256('xxxx'); // 替换为我的机器人token
const hash = Hex.stringify(hmacSHA256(message, secretKey));

if (hash !== params.hash) {
    throw new ValidationError('Authorization data is not from telegram!');
}
}

verifyAuthorization(data);

补充发现与疑问

测试登录组件一段时间后,我将返回值打印到Chrome开发者控制台(按F12进入控制台标签页),再运行代码发现两个哈希完全匹配!

最初我是从网络面板中POST https://oauth.telegram.org/auth/get?bot_id=xxx接口的响应中获取用户信息和哈希,结果发现该接口响应与控制台打印的内容不一致。之后我又测试了几次,该接口响应突然能与我的函数正常匹配了,想知道这是什么原因?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 15:45:39