|
@@ -0,0 +1,57 @@
|
|
|
+const express = require("express");
|
|
|
+const axios = require("axios"); // 用于发起网络请求
|
|
|
+const router = express.Router();
|
|
|
+
|
|
|
+// 假设已经有了微信的 AppID 和 AppSecret
|
|
|
+
|
|
|
+// const { WECHAT_APPID, WECHAT_SECRET } = { WECHAT_APPID: "wx2d69589899b7ecd6", WECHAT_SECRET: "99fd14315d0b41375be4d4a17c830001" }; //cocorobo公众号
|
|
|
+// const { WECHAT_APPID, WECHAT_SECRET } = {
|
|
|
+// WECHAT_APPID: "wx3a8dd28881c2c41f",
|
|
|
+// WECHAT_SECRET: "e6c81745345f44251e44bc7a3b837687",
|
|
|
+// }; //自己
|
|
|
+const { WECHAT_APPID, WECHAT_SECRET } = {
|
|
|
+ WECHAT_APPID: "wxe9d7fff3c659445f",
|
|
|
+ WECHAT_SECRET: "8224f665f09fd5a79f5720676a142792",
|
|
|
+ };
|
|
|
+
|
|
|
+
|
|
|
+// const WECHAT_REDIRECT_URI = "https://liyuan.cocorobo.cn/#/login"; // 微信授权后的回调地址
|
|
|
+
|
|
|
+// 获取微信登录二维码的接口
|
|
|
+// router.route("/wechat-login-qrcode").all((req, res) => {
|
|
|
+// try {
|
|
|
+// // 这里应该是调用微信 API 来获取授权 URL,并转换为二维码
|
|
|
+// const randomState = Math.random().toString(36).substring(2); // 生成随机状态
|
|
|
+// const wechatUrl = `https://open.weixin.qq.com/connect/qrconnect?appid=${WECHAT_APPID}&redirect_uri=${encodeURIComponent(
|
|
|
+// WECHAT_REDIRECT_URI
|
|
|
+// )}&response_type=code&scope=snsapi_login&state=${randomState}#wechat_redirect`;
|
|
|
+// // const wechatUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${WECHAT_APPID}&redirect_uri=${encodeURIComponent(WECHAT_REDIRECT_URI)}&response_type=code&scope=snsapi_base&state=${randomState}#wechat_redirect`
|
|
|
+// // 这里简化处理,直接返回 URL
|
|
|
+// res.json({ url: wechatUrl });
|
|
|
+// } catch (error) {
|
|
|
+// res.status(500).send("服务器错误");
|
|
|
+// }
|
|
|
+// });
|
|
|
+
|
|
|
+// 微信回调接口,也就是用户扫码之后在手机上点击同意之后,需要进行重定向的目标URL
|
|
|
+router.route("/wechat-callback").all(async (req, res) => {
|
|
|
+ const code = req.query.code; // 获取微信回调返回的授权码
|
|
|
+ try {
|
|
|
+ // 使用授权码换取 access_token
|
|
|
+ const tokenResponse = await axios.get(
|
|
|
+ `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${WECHAT_APPID}&secret=${WECHAT_SECRET}&code=${code}&grant_type=authorization_code`
|
|
|
+ );
|
|
|
+ const accessToken = tokenResponse.data.access_token;
|
|
|
+ const openId = tokenResponse.data.openid;
|
|
|
+
|
|
|
+ // 这里可以根据 accessToken 和 openId 获取用户信息,并进行登录处理
|
|
|
+
|
|
|
+ // res.send('登录成功');
|
|
|
+ res.status(200).json({ openId: openId });
|
|
|
+ } catch (error) {
|
|
|
+ res.status(500).send("授权失败");
|
|
|
+ }
|
|
|
+});
|
|
|
+
|
|
|
+
|
|
|
+module.exports = router;
|