明树Git Lab

Commit b3effd2e authored by zfp1's avatar zfp1

第一步先调通ds官方API

parents
Pipeline #91179 failed with stages
WECHAT_TOKEN=deepseektest
DEEPSEEK_API_KEY=sk-14f0cf16bad245169cd2563e0f9b678e
PORT=3001
\ No newline at end of file
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const { parseString, Builder } = require('xml2js');
const axios = require('axios');
const app = express();
const port = process.env.PORT || 3000;
console.log(process.env)
// 中间件配置
app.use(bodyParser.text({ type: 'text/xml' }));
app.use(express.json());
// 微信公众号签名验证
const validateWechatSignature = (req) => {
const { signature, timestamp, nonce } = req.query;
if (!signature || !timestamp || !nonce) return false;
const token = process.env.WECHAT_TOKEN;
const sortedStr = [token, timestamp, nonce].sort().join('');
const sha1 = crypto.createHash('sha1').update(sortedStr).digest('hex');
return sha1 === signature;
};
// 处理微信服务器验证
app.get('/wechat', (req, res) => {
if (!validateWechatSignature(req)) {
console.error('Signature validation failed');
return res.status(403).send('Invalid signature');
}
res.send(req.query.echostr);
});
// 处理微信消息
app.post('/wechat', async (req, res) => {
try {
// 1. 验证签名
if (!validateWechatSignature(req)) {
console.error('Invalid signature in POST');
return res.status(403).send('Forbidden');
}
// 2. 解析XML消息
const xmlData = await new Promise((resolve, reject) => {
parseString(req.body, (err, result) => {
err ? reject(err) : resolve(result.xml);
});
});
// 3. 提取消息内容
const message = {
toUser: xmlData.ToUserName[0],
fromUser: xmlData.FromUserName[0],
content: xmlData.Content?.[0] || '',
msgType: xmlData.MsgType[0]
};
console.log('Received message:', message);
// 4. 只处理文本消息
if (message.msgType !== 'text') {
return res.send(buildTextResponse(message, '暂不支持此类型消息'));
}
// 5. 调用DeepSeek API
const deepseekResponse = await callDeepSeekAPI(message.content);
// 6. 构建响应XML
const responseXml = buildTextResponse(message, deepseekResponse);
res.set('Content-Type', 'text/xml');
res.send(responseXml);
} catch (error) {
console.error('Error processing message:', error);
res.status(500).send('Server Error');
}
});
// 调用DeepSeek API
async function callDeepSeekAPI(prompt) {
try {
const response = await axios.post(
'https://api.deepseek.com/v1/chat/completions',
{
model: "deepseek-chat",
messages: [{ role: "user", content: prompt }],
temperature: 0.7
},
{
headers: {
'Authorization': `Bearer ${process.env.DEEPSEEK_API_KEY}`,
'Content-Type': 'application/json'
},
timeout: 5000 // 5秒超时
}
);
return response.data.choices[0].message.content.trim();
} catch (error) {
console.error('DeepSeek API Error:', error.response?.data || error.message);
return '服务暂时不可用,请稍后再试';
}
}
// 构建文本响应XML
function buildTextResponse(message, content) {
const builder = new Builder({
xmldec: { version: '1.0', encoding: 'UTF-8' },
cdata: true
});
return builder.buildObject({
xml: {
ToUserName: { _: message.fromUser },
FromUserName: { _: message.toUser },
CreateTime: Math.floor(Date.now() / 1000),
MsgType: 'text',
Content: content
}
});
}
// 启动服务
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/wechat`);
});
\ No newline at end of file
require('dotenv').config();
const express = require('express');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const { parseString, Builder } = require('xml2js');
const OpenAI = require('openai');
const app = express();
const port = process.env.PORT || 3000;
// 初始化 OpenAI 客户端(使用 DeepSeek API)
const openai = new OpenAI({
baseURL: 'https://api.deepseek.com', // DeepSeek API 地址
apiKey: process.env.DEEPSEEK_API_KEY, // 从环境变量中读取 API Key
});
// 中间件配置
app.use(bodyParser.text({ type: 'text/xml' }));
app.use(express.json());
// 微信公众号签名验证
const validateWechatSignature = (req) => {
const { signature, timestamp, nonce } = req.query;
if (!signature || !timestamp || !nonce) return false;
const token = process.env.WECHAT_TOKEN;
const sortedStr = [token, timestamp, nonce].sort().join('');
const sha1 = crypto.createHash('sha1').update(sortedStr).digest('hex');
return sha1 === signature;
};
// 处理微信服务器验证
app.get('/wechat', (req, res) => {
if (!validateWechatSignature(req)) {
console.error('Signature validation failed');
return res.status(403).send('Invalid signature');
}
res.send(req.query.echostr);
});
// 处理微信消息
app.post('/wechat', async (req, res) => {
try {
// 1. 验证签名
if (!validateWechatSignature(req)) {
console.error('Invalid signature in POST');
return res.status(403).send('Forbidden');
}
// 2. 解析XML消息
const xmlData = await new Promise((resolve, reject) => {
parseString(req.body, (err, result) => {
err ? reject(err) : resolve(result.xml);
});
});
// 3. 提取消息内容
const message = {
toUser: xmlData.ToUserName[0],
fromUser: xmlData.FromUserName[0],
content: xmlData.Content?.[0] || '',
msgType: xmlData.MsgType[0]
};
console.log('Received message:', message);
// 4. 只处理文本消息
if (message.msgType !== 'text') {
return res.send(buildTextResponse(message, '暂不支持此类型消息'));
}
// 5. 调用DeepSeek API生成回复
const deepseekResponse = await callDeepSeekAPI(message.content);
// 6. 构建响应XML
const responseXml = buildTextResponse(message, deepseekResponse);
res.set('Content-Type', 'text/xml');
res.send(responseXml);
} catch (error) {
console.error('Error processing message:', error);
res.status(500).send('Server Error');
}
});
// 调用DeepSeek API
async function callDeepSeekAPI(prompt) {
try {
const completion = await openai.chat.completions.create({
messages: [
{ role: "system", content: "你是一个智能助手。" }, // 系统角色设置
{ role: "user", content: prompt } // 用户输入
],
model: "deepseek-chat", // DeepSeek 模型
});
return completion.choices[0].message.content.trim();
} catch (error) {
console.error('DeepSeek API Error:', error);
return '服务暂时不可用,请稍后再试';
}
}
// 构建文本响应XML
function buildTextResponse(message, content) {
const builder = new Builder({
xmldec: { version: '1.0', encoding: 'UTF-8' },
cdata: true
});
return builder.buildObject({
xml: {
ToUserName: { _: message.fromUser },
FromUserName: { _: message.toUser },
CreateTime: Math.floor(Date.now() / 1000),
MsgType: 'text',
Content: content
}
});
}
// 启动服务
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}/wechat`);
});
\ No newline at end of file
{
"name": "wechat_ds",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"axios": "^1.7.9",
"body-parser": "^1.20.3",
"crypto": "^1.0.1",
"dotenv": "^16.4.7",
"express": "^4.21.2",
"xml2js": "^0.6.2"
}
}
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