Files
PropertyDeployment/resources/Web/WechatOwnerService/html/static/tgapp1.html
2025-12-09 20:22:03 +08:00

57 lines
1.8 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Telegram Mini App Login</title>
<script src="https://telegram.org/js/telegram-web-app.js?59"></script>
</head>
<body>
<h2>Telegram Mini App 登录示例</h2>
<div id="user-info"></div>
<button onclick="sendToServer()">回调到服务器</button>
<script>
// 获取初始化数据Telegram 客户端注入)
const tg = window.Telegram.WebApp;
const initDataUnsafe = tg.initDataUnsafe; // 结构化的对象
const initData = tg.initData; // 原始字符串(校验用)
// 展示用户信息
const infoDiv = document.getElementById("user-info");
if (initDataUnsafe && initDataUnsafe.user) {
const u = initDataUnsafe.user;
infoDiv.innerHTML = `
<p>欢迎 ${u.first_name} ${u.last_name || ""}</p>
<p>用户名:@${u.username || "未设置"}</p>
<p>Telegram ID: ${u.id}</p>
`;
} else {
infoDiv.innerHTML = "<p>⚠️ 没有获取到用户信息</p>";
}
// 点击按钮回调服务器
function sendToServer() {
fetch("https://bi.toncent.net/local/hello", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
initData: initData, // 原始签名数据(必传,后端要校验)
user: initDataUnsafe.user || {} // 方便调试
})
})
.then(res => res.json())
.then(data => {
alert("后端返回:" + JSON.stringify(data));
})
.catch(err => {
console.error("回调失败:", err);
alert("回调失败:" + err);
});
}
</script>
</body>
</html>