当前位置:网站首页 >  攻略

基于Webhook实现公域流量复购自动化系统搭建实战

时间:2026年06月06日 20:12:24 来源:易频IT社区

系统架构设计

公域流量复购的核心难点在于识别用户身份并在其产生购买行为时实时触发营销动作。本系统采用Webhook监听模式,架构分为三层:数据接收层、逻辑判断层、私域触达层。当用户在抖音、小红书等公域平台下单时,平台会推送订单数据至我们的服务器,服务器通过查询数据库判断该用户是否为老客,若是,则自动调用企业微信API发送复购优惠链接。

开发环境推荐使用Node.js,配合MySQL数据库进行数据持久化,使用Axios进行HTTP请求。整个系统不依赖昂贵的第三方SaaS,完全自建,成本极低且数据安全。

环境准备与依赖安装

首先在本地创建项目目录并初始化Node.js环境。请确保你的系统已安装Node.js v14及以上版本。打开终端,依次执行以下命令:

1. 初始化项目并安装依赖包

我们需要安装Express作为Web框架,mysql2用于数据库操作,axios用于发送请求,body-parser用于解析JSON数据,crypto用于签名验证。执行命令:

```bash mkdir repurchase-system && cd repurchase-system npm init -y npm install express mysql2 axios body-parser crypto --save ```

数据库表结构设计

我们需要两张核心表:customers表用于存储用户身份信息,order_history表用于记录每一笔订单以便后续数据分析。请在MySQL数据库中执行以下SQL语句完成建表。

1. 创建用户信息表

该表以公域平台的User ID作为唯一索引,同时存储关联的企业微信UserID。

```sql CREATE TABLE `customers` ( `id` int(11) NOT NULL AUTO_INCREMENT, `platform_user_id` varchar(64) NOT NULL COMMENT '公域平台用户ID', `wecom_userid` varchar(64) DEFAULT NULL COMMENT '关联的企业微信UserID', `first_purchase_time` datetime DEFAULT CURRENT_TIMESTAMP, `total_orders` int(11) DEFAULT '1', `updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`), UNIQUE KEY `uk_platform_id` (`platform_user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ```

2. 创建订单历史表

```sql CREATE TABLE `order_history` ( `id` int(11) NOT NULL AUTO_INCREMENT, `platform_order_id` varchar(64) NOT NULL, `platform_user_id` varchar(64) NOT NULL, `amount` decimal(10,2) NOT NULL, `order_status` tinyint(1) DEFAULT '1', `created_at` datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `idx_user_id` (`platform_user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ```

核心业务代码实现

在项目根目录下创建server.js文件。我们将分步编写代码,实现Webhook接收、复购判断逻辑及私域消息推送。

1. 基础服务配置与数据库连接

首先引入依赖并创建数据库连接池。请将数据库配置信息替换为你自己的MySQL账号密码。

```javascript const express = require('express'); const bodyParser = require('body-parser'); const mysql = require('mysql2/promise'); const axios = require('axios'); const crypto = require('crypto'); const app = express(); app.use(bodyParser.json()); // 数据库连接池配置 const dbPool = mysql.createPool({ host: 'localhost', user: 'root', password: 'your_password', database: 'repurchase_db', waitForConnections: true, connectionLimit: 10, queueLimit: 0 }); // 企业微信配置(需替换为你自己的) const WECOM_CONFIG = { corpid: 'wwxxxxxxxxxxxxx', corpsecret: 'xxxxxxxxxxxxxxxxxxxxxxxx', agentid: 1000001 }; ```

2. 实现复购判断逻辑函数

这是系统的核心逻辑。当接收到订单数据时,先查询customers表。如果存在该platform_user_id,则判定为复购,更新订单总数并返回true;如果不存在,则插入新记录并返回false

```javascript async function checkAndHandleRepurchase(userId, orderId, amount) { const connection = await dbPool.getConnection(); try { await connection.beginTransaction(); // 查询用户是否存在 const [rows] = await connection.execute( 'SELECT FROM customers WHERE platform_user_id = ?', [userId] ); let isRepurchase = false; if (rows.length > 0) { // 用户存在,判定为复购 isRepurchase = true; await connection.execute( 'UPDATE customers SET total_orders = total_orders + 1 WHERE platform_user_id = ?', [userId] ); } else { // 新用户,插入数据 await connection.execute( 'INSERT INTO customers (platform_user_id, total_orders) VALUES (?, 1)', [userId] ); } // 记录订单历史 await connection.execute( 'INSERT INTO order_history (platform_order_id, platform_user_id, amount) VALUES (?, ?, ?)', [orderId, userId, amount] ); await connection.commit(); return { isRepurchase, customerInfo: rows[0] }; } catch (error) { await connection.rollback(); throw error; } finally { connection.release(); } } ```

基于Webhook实现公域流量复购自动化系统搭建实战

3. 实现企业微信消息推送函数

当判定为复购时,我们需要获取企业微信的Access Token,并向指定用户发送文本卡片消息。这里包含获取Token的API调用和发送消息的API调用。

```javascript async function getWecomAccessToken() { const cacheKey = 'wecom_token'; // 实际生产建议使用Redis缓存 const url = `https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=${WECOM_CONFIG.corpid}&corpsecret=${WECOM_CONFIG.corpsecret}`; const response = await axios.get(url); return response.data.access_token; } async function sendWecomMessage(userWecomId, content) { try { const token = await getWecomAccessToken(); const url = `https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=${token}`; const payload = { touser: userWecomId, msgtype: "textcard", agentid: WECOM_CONFIG.agentid, textcard: { title: "老客专属复购福利", description: content, url: "https://your-shop.com/promo", btntxt: "领取优惠券" } }; await axios.post(url, payload); console.log(`消息已发送给 ${userWecomId}`); } catch (error) { console.error('发送企业微信消息失败:', error.response ? error.response.data : error.message); } } ```

4. 搭建Webhook接收接口

创建POST接口/webhook/order。为了安全,建议在处理逻辑前进行签名验证,此处假设数据来源可信。接口接收JSON数据,提取user_idorder_id,调用上述逻辑。

```javascript app.post('/webhook/order', async (req, res) => { // 假设公域平台推送的数据结构如下,实际需根据抖音/小红书文档调整 const { user_id, order_id, total_amount, timestamp, sign } = req.body; // 1. 基础参数校验 if (!user_id || !order_id) { return res.status(400).json({ code: -1, message: '参数缺失' }); } // 2. 简单的签名验证示例(防止伪造请求) // const serverSign = crypto.createHash('md5').update(`${user_id}${order_id}${timestamp}YOUR_SALT`).digest('hex'); // if (serverSign !== sign) return res.status(403).json({ code: -1, message: '签名验证失败' }); try { // 3. 执行复购判断逻辑 const result = await checkAndHandleRepurchase(user_id, order_id, total_amount); if (result.isRepurchase) { console.log(`检测到老客复购: ${user_id}`); // 4. 如果用户已绑定企业微信,发送通知 if (result.customerInfo && result.customerInfo.wecom_userid) { await sendWecomMessage( result.customerInfo.wecom_userid, `感谢您的再次支持!这是您的第${result.customerInfo.total_orders + 1}次下单,点击领取专属95折券。` ); } } else { console.log(`新客首单: ${user_id}`); } // 必须返回200状态码,否则平台会重复推送 res.json({ code: 0, message: 'success' }); } catch (error) { console.error('处理订单失败:', error); res.status(500).json({ code: -1, message: '服务器内部错误' }); } }); const PORT = 3000; app.listen(PORT, () => { console.log(`复购系统服务已启动,监听端口: ${PORT}`); }); ```

公私域身份绑定方案

上述代码中,customers表里的wecom_userid需要预先绑定。通常的做法是:在私域社群或聊天窗口中生成一个带参二维码。用户扫码时,携带platform_user_id参数跳转页面,页面引导用户添加企业微信。

你需要编写一个额外的接口来处理这个绑定关系。当用户添加企业微信成功后(通过企微的“外部联系人免验证添加”事件回调),更新数据库:

```javascript // 这是一个模拟的绑定接口,实际场景通常在企微回调事件中处理 app.post('/api/bind/wecom', async (req, res) => { const { platform_user_id, wecom_userid } = req.body; try { await dbPool.execute( 'UPDATE customers SET wecom_userid = ? WHERE platform_user_id = ?', [wecom_userid, platform_user_id] ); res.json({ code: 0, message: '绑定成功' }); } catch (error) { res.status(500).json({ code: -1, message: '绑定失败' }); } }); ```

本地测试与部署上线

代码编写完成后,使用curl命令在本地模拟一次公域平台的订单推送,验证逻辑是否正确。

1. 本地模拟测试

启动服务:node server.js。然后打开新终端发送请求:

```bash curl -X POST http://localhost:3000/webhook/order \ -H "Content-Type: application/json" \ -d '{ "user_id": "test_user_001", "order_id": "order_123456", "total_amount": 99.00, "timestamp": 1678888888, "sign": "mock_sign" }' ```

观察终端日志,应显示“新客首单”。再次执行相同命令,日志应显示“检测到老客复购”并尝试发送企微消息。

2. 使用PM2守护进程

生产环境不能直接使用node命令,需使用PM2进行进程管理,确保服务崩溃后自动重启。

```bash npm install pm2 -g pm2 start server.js --name repurchase-api pm2 save pm2 startup ```

3. 内网穿透与公网配置

公域平台(如抖音)需要能访问到你的服务器。如果你没有云服务器,可以使用Ngrok进行内网穿透快速测试:

```bash 安装ngrok后执行 ngrok http 3000 ```

Ngrok会生成一个公网URL(例如https://abc.ngrok.io),将此URL配置到抖音开放平台的“订单接收地址”中即可。

相关推荐

最新

热门

推荐

精选

标签

易频IT社区是综合性互联网IT技术门户网站,专注分享网络技术、服务器运维、网络安全、编程开发、系统架构、云计算、大数据等行业干货,实时更新IT行业资讯、零基础教程、实战案例,为IT从业者、技术爱好者提供专业的学习交流平台。

Copyright © 2021-2026 易频IT社区. All Rights Reserved. 备案号:闽ICP备2023013482号 网站地图