网页端微信
This commit is contained in:
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');
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user