我正在尝试使用 javascript 来实现这个 Telegram PHP 示例,但哈希值不匹配。我运行了示例的 php 代码;它也失败了,并且示例和我的返回的哈希值是相同的。我想知道这是否与我的机器人设置有关(我将域设置为 127.0.0.1 并尝试另一个 https 域 - 仍然失败)。我完全陷入困境,不知道如何让它发挥作用。
我的代码如下:
'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) { // milisecond
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'); // replace with the token of my bot
const hash = Hex.stringify(hmacSHA256(message, secretKey));
if (hash !== params.hash) {
throw new ValidationError('Authorization data is not from telegram!');
}
}
verifyAuthorization(data);
编辑:
在尝试登录小部件一段时间后,我尝试将返回值打印到 Chrome 的开发者控制台(按 f12,控制台选项卡),然后再次运行我的代码。 2 个哈希值非常匹配!
我最初从网络选项卡中
POST https://oauth.telegram.org/auth/get?bot_id=xxx
的API响应中获取了用户信息和哈希值,结果发现网络选项卡中API的响应与控制台选项卡中打印的响应不同。
我又尝试了一些时间,API 的响应突然与我的功能配合得很好。现在我只是好奇为什么?
对于那些想要寻找这个问题答案的人。作者忘记按字母顺序对键进行排序
const sortedKeys = Object.keys(verificationParams).sort();
const message = sortedKeys
.map(key => `${key}=${verificationParams[key]}`)
.join('\n');