2025-11-13 15:08:32 +08:00
|
|
|
|
const express = require('express');
|
|
|
|
|
|
const axios = require('axios');
|
|
|
|
|
|
const app = express();
|
|
|
|
|
|
app.use(express.json());
|
2025-09-15 10:04:47 +08:00
|
|
|
|
|
2025-11-13 15:08:32 +08:00
|
|
|
|
const APP_ID = 'wx364b8ebf17fe45fe';
|
|
|
|
|
|
const APP_SECRET = '9b7476020991a2c71f1416da7f011d31'; // ⚠️ 安全存储在后端
|
|
|
|
|
|
|
|
|
|
|
|
// 前端发送 code 到这里
|
|
|
|
|
|
app.post('/api/wechat-login', async (req, res) => {
|
|
|
|
|
|
const { code } = req.body;
|
|
|
|
|
|
if (!code) return res.status(400).json({ error: 'code is required' });
|
2025-09-15 10:04:47 +08:00
|
|
|
|
|
|
|
|
|
|
try {
|
2025-11-13 15:08:32 +08:00
|
|
|
|
// 1️⃣ 换取 access_token
|
|
|
|
|
|
const tokenResp = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', {
|
|
|
|
|
|
params: {
|
|
|
|
|
|
appid: APP_ID,
|
|
|
|
|
|
secret: APP_SECRET,
|
|
|
|
|
|
code,
|
|
|
|
|
|
grant_type: 'authorization_code'
|
|
|
|
|
|
}
|
2025-09-15 10:04:47 +08:00
|
|
|
|
});
|
|
|
|
|
|
|
2025-11-13 15:08:32 +08:00
|
|
|
|
const tokenData = tokenResp.data;
|
|
|
|
|
|
const accessToken = tokenData.access_token;
|
|
|
|
|
|
const openid = tokenData.openid;
|
|
|
|
|
|
|
|
|
|
|
|
if (!accessToken || !openid) {
|
|
|
|
|
|
return res.status(400).json({ error: 'Failed to get access_token or openid', data: tokenData });
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
// 2️⃣ 获取用户信息
|
|
|
|
|
|
const userResp = await axios.get('https://api.weixin.qq.com/sns/userinfo', {
|
|
|
|
|
|
params: { access_token: accessToken, openid }
|
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
|
|
const userInfo = userResp.data;
|
|
|
|
|
|
|
|
|
|
|
|
// 3️⃣ 可生成网站登录态(JWT 或 session),这里演示直接返回
|
|
|
|
|
|
res.json({ userInfo });
|
2025-09-15 10:04:47 +08:00
|
|
|
|
|
|
|
|
|
|
} catch (err) {
|
2025-11-13 15:08:32 +08:00
|
|
|
|
console.error(err);
|
|
|
|
|
|
res.status(500).json({ error: 'WeChat login failed' });
|
2025-09-15 10:04:47 +08:00
|
|
|
|
}
|
2025-11-13 15:08:32 +08:00
|
|
|
|
});
|
2025-09-15 10:04:47 +08:00
|
|
|
|
|
2025-11-13 15:08:32 +08:00
|
|
|
|
app.listen(3001, () => {
|
|
|
|
|
|
console.log('Server running on http://localhost:3001');
|
|
|
|
|
|
});
|