随身笔记
随身笔记

webhook消息推送服务器简单搭建

基于node.js搭建,后端用任意语言都行

服务器:

安装依赖:

npm init -y
npm install express body-parser dotenv

 

后端代码:

server.js

const express = require('express');
const bodyParser = require('body-parser');
const fs = require('fs').promises;
const path = require('path');
require('dotenv').config();

const app = express();
const port = process.env.PORT || 3000;

// 日志存储配置
const LOG_DIR = 'logs';
const LOG_FILE = path.join(LOG_DIR, 'webhook_logs.json');

// 初始化日志目录
async function initLogDir() {
  try {
    await fs.access(LOG_DIR);
  } catch {
    await fs.mkdir(LOG_DIR);
    await fs.writeFile(LOG_FILE, '[]');
  }
}

// 保存日志
async function saveLog(data) {
  try {
    const logs = await readLogs();
    logs.unshift({
      id: Date.now(),
      timestamp: new Date().toISOString(),
      ...data
    });
    await fs.writeFile(LOG_FILE, JSON.stringify(logs.slice(0, 100), null, 2));
  } catch (error) {
    console.error('保存日志失败:', error);
  }
}

// 读取日志
async function readLogs() {
  try {
    const data = await fs.readFile(LOG_FILE, 'utf8');
    return JSON.parse(data);
  } catch {
    return [];
  }
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

// 记录所有请求
app.use((req, res, next) => {
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
  next();
});

// Webhook接收端点
app.post('/webhook', async (req, res) => {
  try {
    const webhookData = {
      headers: req.headers,
      body: req.body,
      query: req.query,
      receivedAt: new Date().toISOString()
    };

    // 保存接收到的数据
    await saveLog(webhookData);

    console.log('收到Webhook请求:', {
      time: webhookData.receivedAt,
      body: webhookData.body
    });

    res.status(200).json({
      status: 'success',
      message: 'Webhook received successfully'
    });
  } catch (error) {
    console.error('处理Webhook失败:', error);
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
});

// 查看日志的API端点
app.get('/logs', async (req, res) => {
  try {
    const page = parseInt(req.query.page) || 1;
    const limit = parseInt(req.query.limit) || 10;
    const logs = await readLogs();
    
    const startIndex = (page - 1) * limit;
    const endIndex = page * limit;
    
    res.json({
      data: logs.slice(startIndex, endIndex),
      total: logs.length,
      page,
      limit
    });
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
});

// 查看单条日志详情
app.get('/logs/:id', async (req, res) => {
  try {
    const logs = await readLogs();
    const log = logs.find(l => l.id === parseInt(req.params.id));
    
    if (!log) {
      return res.status(404).json({
        status: 'error',
        message: 'Log not found'
      });
    }
    
    res.json(log);
  } catch (error) {
    res.status(500).json({
      status: 'error',
      message: error.message
    });
  }
});

// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({
    status: 'healthy',
    time: new Date().toISOString()
  });
});

// 启动服务器
async function startServer() {
  await initLogDir();
  app.listen(port, () => {
    console.log(`Webhook服务器已启动: http://localhost:${port}`);
  });
}

startServer();

 

使用curl发送测试请求:

curl -X POST http://localhost:3000/webhook \
  -H "Content-Type: application/json" \
  -d '{"message": "测试消息", "type": "test"}'

 

 

客户端:

查看发来的数据

curl "http://localhost:3000/logs?page=1&limit=10"

 

配合手机端app使用,可以把接收来的短信自动发送到地址上查看

短信转发到指定邮箱

随身笔记

webhook消息推送服务器简单搭建
基于node.js搭建,后端用任意语言都行 服务器: 安装依赖: npm init -y npm install express body-parser dotenv   后端代码: server.js const express = require…
扫描二维码继续阅读
2025-02-13