明树Git Lab

Commit 916525f9 authored by zfp1's avatar zfp1

3

parent 09a8c03a
const { OpenAI } = require('openai');
const express = require('express');
const crypto = require('crypto');
const xml2js = require('xml2js');
const app = express();
// 初始化DeepSeek客户端 [3]()
const deepseek = new OpenAI({
baseURL: 'https://api.deepseek.com/v1',
apiKey: DEEPSEEK_API_KEY,
});
// 微信消息处理器
app.use(express.text({ type: 'text/xml' }));
app.post('/wechat', async (req, res) => {
// 1. 验证签名
const { signature, timestamp, nonce } = req.query;
const sha1 = crypto.createHash('sha1');
const arr = [WECHAT_TOKEN, timestamp, nonce].sort();
const sign = sha1.update(arr.join('')).digest('hex');
if (signature !== sign) {
return res.status(403).send('Invalid signature');
}
// 2. 解析XML消息
const parser = new xml2js.Parser({ explicitArray: false });
const result = await parser.parseStringPromise(req.body);
const { ToUserName, FromUserName, Content } = result.xml;
// 3. 调用DeepSeek API
try {
const completion = await deepseek.chat.completions.create({
model: "deepseek-chat",
messages: [
{ role: "system", content: "你是一个微信客服助手, 回复内容不能超过2048字节" },
{ role: "user", content: Content }
],
stream: false,
});
// 4. 构建响应XML
const builder = new xml2js.Builder();
const response = builder.buildObject({
xml: {
ToUserName: FromUserName,
FromUserName: ToUserName,
CreateTime: Math.floor(Date.now() / 1000),
MsgType: 'text',
Content: completion.choices[0].message.content
}
});
res.type('application/xml').send(response);
} catch (error) {
console.error('API Error:', error);
res.type('text').send(' 系统繁忙,请稍后再试');
}
});
app.listen(process.env.PORT);
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment