网页端微信
This commit is contained in:
1
MP_verify_cfogfI7DfSkoUOht.txt
Normal file
1
MP_verify_cfogfI7DfSkoUOht.txt
Normal file
@@ -0,0 +1 @@
|
||||
cfogfI7DfSkoUOht
|
||||
77
server1.js
77
server1.js
@@ -1,44 +1,51 @@
|
||||
import fs from "fs";
|
||||
import OpenAI from "openai";
|
||||
const express = require('express');
|
||||
const axios = require('axios');
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
|
||||
// 1. 初始化客户端(记得设置环境变量 HUNYUAN_API_KEY)
|
||||
const client = new OpenAI({
|
||||
apiKey: "sk-LVfG90qgdhf9kKQUucqBSLioxamDu7gBeW9boXqKOxIDJt7H",
|
||||
baseURL: "https://api.hunyuan.cloud.tencent.com/v1",
|
||||
});
|
||||
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' });
|
||||
|
||||
async function run() {
|
||||
try {
|
||||
// 2. 读取本地图片,转成 base64
|
||||
const imagePath = "./test.png"; // 👈 换成你自己的图片路径
|
||||
const base64Image = fs.readFileSync(imagePath).toString("base64");
|
||||
|
||||
// 3. 调用 hunyuan-vision
|
||||
const completion = await client.chat.completions.create({
|
||||
model: "hunyuan-vision",
|
||||
stream: false, // 先关掉流式,调试更清晰
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [
|
||||
{ type: "text", text: "请描述这张图片的主要内容。" },
|
||||
{
|
||||
type: "image_url",
|
||||
image_url: {
|
||||
url: `data:image/png;base64,${base64Image}`, // 👈 必须加前缀
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
// 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'
|
||||
}
|
||||
});
|
||||
|
||||
// 4. 打印结果
|
||||
console.log(completion.choices[0].message.content);
|
||||
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.response?.data || err.message);
|
||||
console.error(err);
|
||||
res.status(500).json({ error: 'WeChat login failed' });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
run();
|
||||
app.listen(3001, () => {
|
||||
console.log('Server running on http://localhost:3001');
|
||||
});
|
||||
|
||||
44
wxtest.html
Normal file
44
wxtest.html
Normal file
@@ -0,0 +1,44 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>微信登录示例</title>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
<button id="loginBtn">微信登录</button>
|
||||
|
||||
<script>
|
||||
const APP_ID = 'wx364b8ebf17fe45fe';
|
||||
const REDIRECT_URI = encodeURIComponent(window.location.origin + '/callback.html');
|
||||
const STATE = Math.random().toString(36).substring(2, 12);
|
||||
const SCOPE = 'snsapi_userinfo';
|
||||
|
||||
document.getElementById('loginBtn').onclick = () => {
|
||||
const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${APP_ID}&redirect_uri=${REDIRECT_URI}&response_type=code&scope=${SCOPE}&state=${STATE}#wechat_redirect`;
|
||||
window.location.href = url;
|
||||
};
|
||||
|
||||
// 在 callback.html 中获取 code 并调用后端
|
||||
if (window.location.search.includes('code=')) {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const code = params.get('code');
|
||||
const state = params.get('state');
|
||||
|
||||
fetch('/api/wechat-login', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ code })
|
||||
})
|
||||
.then(res => res.json())
|
||||
.then(data => {
|
||||
console.log('登录结果:', data);
|
||||
// data.userInfo 就是微信用户信息
|
||||
})
|
||||
.catch(err => console.error(err));
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
Reference in New Issue
Block a user