From c6a974fa8c0d981254af6c62d55f14b36e28a6d8 Mon Sep 17 00:00:00 2001
From: geyun <1556375442@qq.com>
Date: Sun, 16 Nov 2025 21:39:26 +0800
Subject: [PATCH] =?UTF-8?q?=E5=BE=AE=E4=BF=A1=E5=85=AC=E4=BC=97=E5=8F=B7?=
=?UTF-8?q?=E5=92=8C=E7=BD=91=E9=A1=B5=E7=AB=AF=E7=9A=84AI=E7=99=BB?=
=?UTF-8?q?=E5=BD=95=E5=88=A4=E6=96=AD=E6=96=B9=E5=BC=8F=20=20=E8=9E=8D?=
=?UTF-8?q?=E5=90=88=E5=A4=9A=E5=B9=B3=E5=8F=B0?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
.env | 2 +-
index.html | 117 +++++++++++------
server2.js | 374 +++++++++++++++++++++++++++++++++++++++--------------
3 files changed, 358 insertions(+), 135 deletions(-)
diff --git a/.env b/.env
index 662608a..a9bb6f8 100644
--- a/.env
+++ b/.env
@@ -1,2 +1,2 @@
WECHAT_APPID=wx364b8ebf17fe45fe
-WECHAT_SECRET=1edcd083ba75e15a753521da73a38bed
\ No newline at end of file
+WECHAT_SECRET=9b7476020991a2c71f1416da7f011d31
\ No newline at end of file
diff --git a/index.html b/index.html
index c717f87..b832382 100755
--- a/index.html
+++ b/index.html
@@ -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() {
diff --git a/server2.js b/server2.js
index 4a663b7..36dea8d 100755
--- a/server2.js
+++ b/server2.js
@@ -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(`
-//
-//
-// ${Date.now()}
-//
-//
-// `);
-// } 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 = `
-
-
-
- ${Date.now()}
-
-
-
- `;
- res.send(reply);
- return;
+ try {
+ // 方案一:简单文本回复(推荐,避免超时)
+ const reply = `
+
+
+
+ ${Date.now()}
+
+ 立即进入AI智能体]]>
+
+ `;
+ 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 = `
+
+
+
+ ${Date.now()}
+
+
+
+ `;
+ res.send(reply);
+ return;
+ */
+ } catch (err) {
+ console.error("处理AI_INTELLIGENT错误:", err);
+ // 出错时返回标准回复
+ const errorReply = `
+
+
+
+ ${Date.now()}
+
+
+
+ `;
+ 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 = `
+// //
+// //
+// //
+// // ${Date.now()}
+// //
+// //
+// //
+// // `;
+// // 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 = `
+//
+//
+//
+// ${Date.now()}
+//
+//
+//
+// `;
+// 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({