微信公众号和网页端的AI登录判断方式 融合多平台

This commit is contained in:
2025-11-16 21:39:26 +08:00
parent e1b1c4ca1f
commit c6a974fa8c
3 changed files with 358 additions and 135 deletions

2
.env
View File

@@ -1,2 +1,2 @@
WECHAT_APPID=wx364b8ebf17fe45fe
WECHAT_SECRET=1edcd083ba75e15a753521da73a38bed
WECHAT_SECRET=9b7476020991a2c71f1416da7f011d31

View File

@@ -1109,9 +1109,17 @@
// ✅ 先 URL 解码,再 Base64 解码,再 UTF-8 解码
const userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
let userId;
if (from == "weixin") {
userId = encodedUserId;
document.querySelector('.logout').style.display = 'none';
} else {
userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
}
setCookie("userId", userId);
getUserName(userId);
// const userId = encodedUserId;
let sendParam = {
imageBase64: '',
@@ -1143,46 +1151,90 @@
// } else {
if (getCookie("userId")) {
getSessionList();
if (from == "weixin") {
getUserByOpenId(userId)
} else {
getSessionList();
}
} else {
deleteCookie('userId');
window.location.href = 'http://ri.satabot.com/#/login?goRemote=1&clear=1';
if (from == "weixin") {
} else {
window.location.href = 'http://ri.satabot.com/#/login?goRemote=1&clear=1';
}
}
// }
const questions = document.querySelectorAll(".question");
// 获取到用户名称
function getUserName(userId) {
function getUserByOpenId(id) {
try {
fetch("/api/user", {
fetch("/api/getuserByopenid", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
userId,
userId: id,
})
}).then(res => res.json()).then(data => {
if (data.code === 0) {
document.querySelectorAll('.username').forEach((e) => {
e.textContent = data.userName;
})
console.log("成功找到该用户:", data.userName, data.userId);
if (data.code == 0) {
userId = data.userId;
sendParam.userId = userId;
getSessionList();
} else {
console.error("未找到该用户:",);
}
})
} catch (err) {
console.error("请求异常:", err);
}
}
const questions = document.querySelectorAll(".question");
// 获取到用户名称
function getUserName(userId) {
if (from == "weixin") {
document.querySelectorAll('.username').forEach((e) => {
e.textContent = userId;
})
} else {
try {
fetch("/api/user", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
userId,
})
}).then(res => res.json()).then(data => {
if (data.code === 0) {
document.querySelectorAll('.username').forEach((e) => {
e.textContent = data.userName;
})
console.log("成功找到该用户:", data.userName, data.userId);
} else {
window.location.href = data.error;
return;
console.error("未找到该用户:",);
}
})
} catch (err) {
console.error("请求异常:", err);
}
}
}
questions.forEach(q => {
@@ -1196,7 +1248,7 @@
// }
}
isPre = true;
isPre = true;//s是否预设题目
console.log(isUpload, 88)
if (!sendParam.imageBase64 && !fileInput.files.length) {
// if (!isUpload[activeChatId]) {
@@ -1458,6 +1510,7 @@
function sendMessage(isPre) {
debugger;
console.log("发送消息1122");
if (controller) {
showToast("请先停止对话");
@@ -1532,7 +1585,10 @@
sessId = sendParam.sessionId;
sendParam.imageBase64 = img;
// sendParam.userId= encodedUserId;
sendParam.userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
if (from != "weixin") {
sendParam.userId = decodeURIComponent(Number(escape(atob(encodedUserId))));
}
// ✅ 创建 AbortController
controller = new AbortController();
sendParam.requestId = crypto.randomUUID();
@@ -1789,6 +1845,7 @@
}).then(res => res.json()).then(data => {
// chats = data.messages;
// renderChatList();
if (controller) return;
renderMessages(data.messages)
})
@@ -1830,27 +1887,7 @@
// window.location.href = url; // 跳转到微信授权页面
// }
// simulateWechatLogin()
// 页面加载时立即执行:检查是否有微信返回的 code
document.addEventListener('DOMContentLoaded', function () {
const params = new URLSearchParams(window.location.search);
const code = params.get('code');
const state = params.get('state');
if (code) {
console.log('微信返回 code:', code);
// 发送 code 到后端换取用户信息(这里才会执行)
fetch('/api/wechat-login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ code })
})
.then(res => res.json())
.then(data => {
console.log('微信用户信息:', data.userInfo);
})
.catch(err => console.error(err));
}
});
// 触发登录时执行:跳转微信授权页
function simulateWechatLogin() {

View File

@@ -106,52 +106,19 @@ const client1 = new OpenAI({
});
// 公众号
function getMenuForPlatform(req) {
const userAgent = req.headers['user-agent'];
// 判断请求是否来自微信客户端
if (/MicroMessenger/i.test(userAgent)) {
// 微信菜单
return {
button: [
{
type: 'click',
name: '获取 OpenID',
key: 'GET_OPENID',
},
{
type: 'view',
name: '访问官网',
url: 'https://www.example.com',
sub_button: [ // 二级菜单
{
type: 'view',
name: '关于我们',
url: 'https://www.example.com/about',
},
{
type: 'view',
name: '联系我们',
url: 'https://www.example.com/contact',
}
]
}
]
};
}
}
// 获取 access_token
async function getAccessToken() {
try {
const res = await axios.get(accessTokenUrl);
const url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appid}&secret=${secret}`;
const res = await axios.get(url);
if (res.data.access_token) {
console.log('✅ 获取 access_token 成功');
return res.data.access_token;
} catch (error) {
console.error('获取 access_token 失败:', error);
} else {
throw new Error('❌ 获取 access_token 失败: ' + JSON.stringify(res.data));
}
}
// 创建菜单的接口
app.post('/create-menu', async (req, res) => {
const accessToken = await getAccessToken();
@@ -167,68 +134,248 @@ app.post('/create-menu', async (req, res) => {
}
});
// 处理微信自定义菜单点击事件
// app.post('/wechat', (req, res) => {
// const xmlData = req.body.xml;
// console.log(xmlData,"接受消息")
// if (xmlData.Event === 'CLICK' && xmlData.EventKey === 'GET_OPENID') {
// const openid = xmlData.FromUserName;
// console.log(`用户的 openid: ${openid}`);
// res.send(`<xml>
// <ToUserName><![CDATA[${openid}]]></ToUserName>
// <FromUserName><![CDATA[${xmlData.ToUserName}]]></FromUserName>
// <CreateTime>${Date.now()}</CreateTime>
// <MsgType><![CDATA[text]]></MsgType>
// <Content><![CDATA[您的 OpenID 是:${openid}]]></Content>
// </xml>`);
// } else {
// res.send('未处理的事件');
// }
// });
app.post('/wechat', async (req, res) => {
try {
console.log(req,"收到恢复")
try {
console.log("收到请求:", req.body);
const xml = req.body;
console.log(xml);
const data = await xml2js.parseStringPromise(xml, { explicitArray: false });
const message = data.xml;
const message = xml.xml;
// 修复语法错误:移除msgtype前的空格
const msgType = message.msgtype;
const fromUser = message.fromusername; // openid
const toUser = message.tousername; // 公众号原始ID
console.log("消息类型:", msgType);
console.log("用户OpenID:", fromUser);
const msgType = message.MsgType;
const fromUser = message.FromUserName; // openid
// 菜单点击事件
if (msgType === 'event' && message.Event === 'CLICK') {
const key = message.EventKey;
if (msgType === 'event' && message.event === 'CLICK') {
const key = message.eventkey;
console.log("菜单点击Key:", key);
if (key === 'AI_INTELLIGENT') {
const token = await getAccessToken();
// 获取用户信息
const userInfoRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`);
const user = userInfoRes.data;
// 回复文本消息
const reply = `
<xml>
<ToUserName><![CDATA[${fromUser}]]></ToUserName>
<FromUserName><![CDATA[${message.ToUserName}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好,${user.nickname}!欢迎使用 AI智能体]]></Content>
</xml>
`;
res.send(reply);
return;
try {
// 方案一:简单文本回复(推荐,避免超时)
const reply = `
<xml>
<ToUserName><![CDATA[${fromUser}]]></ToUserName>
<FromUserName><![CDATA[${toUser}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[欢迎使用AI智能体!正在为您准备服务...<a href="https://ai.satabot.com?userId=${fromUser}&from=weixin" target="_blank">立即进入AI智能体</a>]]></Content>
</xml>
`;
res.send(reply);
return;
// 启动异步任务处理耗时操作
setTimeout(async () => {
try {
const token = await getAccessToken();
console.log("获取到Token:", token);
// 获取用户信息
const userRes = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
params: {
access_token:token,
fromUser,
lang: 'zh_CN'
}
});
console.log(userRes, 'user000000000000');
// res.redirect('https://ai.satabot.com');
const { nickname, errcode: userErrCode } = userRes.data;
console.log(nickname, 'nickname');
return;
if (userErrCode) return res.status(500).send(`获取用户信息失败:${userErrCode}`);
const userInfoRes = await axios.get(
`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
);
const user = userInfoRes.data;
console.log("用户信息:", user);
// 使用客服消息接口发送详细回复
if (user && user.nickname) {
await sendCustomerServiceMessage(fromUser, `你好,${user.nickname}!欢迎使用AI智能体`);
}
} catch (err) {
console.error("异步处理错误:", err);
}
}, 0);
return;
// 方案二:直接回复(如果能确保5秒内完成)
/*
const token = await getAccessToken();
console.log("Token:", token);
const userInfoRes = await axios.get(
`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`
);
const user = userInfoRes.data;
console.log("用户信息:", user);
const reply = `
<xml>
<ToUserName><![CDATA[${fromUser}]]></ToUserName>
<FromUserName><![CDATA[${toUser}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好,${user.nickname || '用户'}!欢迎使用AI智能体]]></Content>
</xml>
`;
res.send(reply);
return;
*/
} catch (err) {
console.error("处理AI_INTELLIGENT错误:", err);
// 出错时返回标准回复
const errorReply = `
<xml>
<ToUserName><![CDATA[${fromUser}]]></ToUserName>
<FromUserName><![CDATA[${toUser}]]></FromUserName>
<CreateTime>${Date.now()}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[服务暂时不可用,请稍后再试]]></Content>
</xml>
`;
res.send(errorReply);
return;
}
}
}
// 默认回复空串(表示不处理)
res.send('');
} catch (err) {
console.error("服务器错误:", err);
// 异常情况下回复空串
res.send('');
}
});
// 默认回复空
res.send('success');
// 新增:发送客服消息的函数
async function sendCustomerServiceMessage(openid, content) {
try {
const token = await getAccessToken();
const url = `https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=${token}`;
const data = {
touser: openid,
msgtype: 'text',
text: {
content: content
}
};
await axios.post(url, data, {
headers: {
'Content-Type': 'application/json'
}
});
console.log("客服消息发送成功");
} catch (err) {
console.error("发送客服消息失败:", err);
}
}
// app.post('/wechat', async (req, res) => {
// try {
// console.log(req,"收到恢复")
// const xml = req.body;
// console.log(xml);
// const message = xml.xml;
// const msgType = message.msgtype;
// const fromUser = message.fromusername; // openid
// // 菜单点击事件
// if (msgType === 'event' && message.event === 'CLICK') {
// const key = message.eventkey;
// if (key === 'AI_INTELLIGENT') {
// const redirectUri = encodeURIComponent(`https://ai.satabot.com/api/wechat/oauth/callback`);
// const state = fromUser; // 可用 openid 做状态标识
// console.log(state,"state")
// // const oauthUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
// // console.log("oauthUrl",oauthUrl)
// // // 回复用户点击菜单提示,引导跳转
// // const reply = `
// // <xml>
// // <ToUserName><![CDATA[${fromUser}]]></ToUserName>
// // <FromUserName><![CDATA[${message.ToUserName}]]></FromUserName>
// // <CreateTime>${Date.now()}</CreateTime>
// // <MsgType><![CDATA[text]]></MsgType>
// // <Content><![CDATA[请点击以下链接授权获取昵称:${oauthUrl}]]></Content>
// // </xml>
// // `;
// // res.send(reply);
// // return;
// const token = await getAccessToken();
// console.log(token,"token")
// // 获取用户信息
// // https://api.weixin.qq.com/cgi-bin/user/info?access_token=ACCESS_TOKEN&openid=o6_bmjrPTlm6_2sgVt7hMZOPfL2M&lang=zh_CN
// const userInfoRes = await axios.get(`https://api.weixin.qq.com/cgi-bin/user/info?access_token=${token}&openid=${fromUser}&lang=zh_CN`);
// // https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=ENCODED_URL&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
// const user = userInfoRes.data;
// console.log(userInfoRes,'用户信息')
// // 回复文本消息
// const reply = `
// <xml>
// <ToUserName><![CDATA[${fromUser}]]></ToUserName>
// <FromUserName><![CDATA[${message.fromUser}]]></FromUserName>
// <CreateTime>${Date.now()}</CreateTime>
// <MsgType><![CDATA[text]]></MsgType>
// <Content><![CDATA[你好,${user.nickname}!欢迎使用 AI智能体]]></Content>
// </xml>
// `;
// res.send(xml);
// return;
// }
// }
// // 默认回复空
// res.send('success');
// } catch (err) {
// console.error(err);
// res.send('success');
// }
// });
// OAuth2 回调
app.get('/wechat/oauth/callback', async (req, res) => {
try {
const { code, state } = req.query;
console.log(code,"code")
// 用 code 换取 access_token 和 openid
const tokenResp = await axios.get(
`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${code}&grant_type=authorization_code`
);
const { access_token, openid } = tokenResp.data;
// 拉取用户信息
const userInfoResp = await axios.get(
`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`
);
const user = userInfoResp.data;
console.log(user, "获取到用户信息");
// 你可以直接跳转到前端页面并带上用户信息
res.redirect(`https://ai.satabot.com?nickname=${encodeURIComponent(user.nickname)}&openid=${openid}`);
} catch (err) {
console.error(err);
res.send('success');
res.send("获取用户信息失败");
}
});
@@ -286,8 +433,13 @@ app.post("/user", async (req, res) => {
[userId]
);
if (rows.length === 0) {
return res.status(404).send("未找到该用户");
if (rows.length === 0) {
res.json({
code: 300,
error: "http://ri.satabot.com/#/login?goRemote=1",
msg:"未找到该用户"
});
return;
}
res.json({ code:0,userId, userName: rows[0].user_name });
@@ -296,6 +448,40 @@ app.post("/user", async (req, res) => {
res.status(500).send("服务器错误");
}
});
app.post("/getuserByopenid", async (req, res) => {
try {
const { userId } = req.body; // 从请求体里拿到 user_id
if (!userId) {
return res.status(400).send("缺少 user_id");
}
// 查询 user_name
const [rows] = await pool.query(
"SELECT * FROM sys_user WHERE openId = ?",
[userId]
);
if (rows.length > 0) {
// 用户存在,直接返回
res.json({ code: 0, msg: "找到该用户",userId:rows[0].user_id });
return
} else {
// 用户不存在,插入新用户
const [result] = await pool.query(
"INSERT INTO sys_user (openId,user_name,nick_name) VALUES (?,?,?)",
[userId,userId,userId]
);
console.log(result,"udgwehvdh")
res.json({code:0,msg:"新增该用户",userId:result.insertId});
return ;
}
} catch (err) {
console.error(err);
res.status(500).send("服务器错误");
}
});
const TOKEN = 'my_token_123'; // 与公众号后台配置一致
@@ -316,7 +502,7 @@ app.get("/sessions", async (req, res) => {
console.log("收到的 userId:", req.query.userId);
try {
const userId = req.query.userId;
if (!userId || userId == "NaN" || isNaN(Number(userId)))
if (!userId || userId == "NaN" )
{
console.log("userId:", req.query.userId);
res.json({