PHP如何获取Telegram Bot Web App中#tgWebAppData的GET数据?
如何获取Telegram Web App的#tgWebAppData数据
URL中#后面的部分叫锚点(Fragment),浏览器在发送HTTP请求时不会把这部分内容传递给服务器,所以你在PHP的$_SERVER或$_GET里根本找不到它——用.htaccess也解决不了,因为服务器从始至终都没收到这串数据。
要拿到这部分数据,必须通过前端JavaScript先获取,再传递给PHP后端,具体步骤如下:
第一步:前端JS获取并解析锚点数据
用window.location.hash提取锚点内容,再解析出tgWebAppData里的具体参数。示例代码:// 去掉锚点开头的#,获取完整参数字符串 const hashContent = window.location.hash.slice(1); // 解析成参数对象 const hashParams = new URLSearchParams(hashContent); // 提取tgWebAppData的值 const tgWebAppData = hashParams.get('tgWebAppData'); // 进一步解析tgWebAppData里的具体字段 const tgParams = new URLSearchParams(tgWebAppData); const queryId = tgParams.get('query_id'); const user = JSON.parse(decodeURIComponent(tgParams.get('user'))); const authDate = tgParams.get('auth_date'); const hashStr = tgParams.get('hash');第二步:把数据传递给PHP后端
有两种常用实现方式:AJAX POST请求
把解析好的数据通过POST发送到PHP接口,示例:fetch('process_tg_data.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, body: new URLSearchParams({ query_id: queryId, user: JSON.stringify(user), auth_date: authDate, hash: hashStr }) }) .then(res => res.json()) .then(result => { // 处理后端返回结果 });对应PHP端(process_tg_data.php):
$queryId = $_POST['query_id']; $user = json_decode($_POST['user'], true); $authDate = $_POST['auth_date']; $hash = $_POST['hash'];页面重定向(转成URL查询参数)
如果需要页面加载时就把数据传给PHP,可以把锚点数据转成URL查询参数后重定向:if (window.location.hash) { const hashParams = new URLSearchParams(window.location.hash.slice(1)); const tgData = hashParams.get('tgWebAppData'); window.location.href = window.location.pathname + '?' + tgData; }之后PHP直接通过
$_GET获取:$queryId = $_GET['query_id']; $user = json_decode($_GET['user'], true); $authDate = $_GET['auth_date']; $hash = $_GET['hash'];
关键注意事项
拿到数据后必须验证hash的真实性,防止恶意伪造:- 把
query_id、user、auth_date按键名排序,拼成key=value格式并用换行符连接; - 用HMAC-SHA256算法,以你的Bot Token后半段(
:之后的部分)作为密钥,对拼接字符串哈希; - 对比生成的哈希值和传入的
hash,一致则数据有效。
- 把
内容的提问来源于stack exchange,提问作者Adhambey Gamer
相关产品推荐
相关产品推荐

