Files
AI/server1.js
2025-11-13 15:08:32 +08:00

52 lines
1.5 KiB
JavaScript
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

const express = require('express');
const axios = require('axios');
const app = express();
app.use(express.json());
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' });
try {
// 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'
}
});
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 });
} catch (err) {
console.error(err);
res.status(500).json({ error: 'WeChat login failed' });
}
});
app.listen(3001, () => {
console.log('Server running on http://localhost:3001');
});