微信客服消息或者事件推送或者公众号消息推送到服务器配置

  |  

nodejs + koa

// 使用此功能 需要配置 ip 白名单 和 开启开发者密码 才有效果

在这里插入图片描述
token 是自己随便定义的字符串,url 是服务器接口

先要写好接口,能够访问,不然 token 一直会报无效

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
async wechat(ctx, next) {
const { signature, timestamp, nonce, echostr } = ctx.query;
const message = ctx.request.body;

// 服务器的token
const token = 'f379eaf3c831b04de153469d1bec345e';

// 将token、timestamp、nonce三个参数进行字典序排序
const arrSort = [ token, timestamp, nonce ];
arrSort.sort();

// 将三个参数字符串拼接成一个字符串进行sha1加密,npm install --save sha1
const str = arrSort.join('');
const shaStr = crypto.createHash('sha1').update(str).digest('hex')
.toUpperCase();

// 获得加密后的字符串可与signature对比,验证标识该请求来源于微信服务器
if (shaStr === signature.toUpperCase()) {
// 确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效
// ctx.body = echostr;
// return
// const now = Date.parse(new Date()) / 1000;
// ctx.type = 'application/xml';
// const reply = `<xml>
// <ToUserName><![CDATA[${message.FromUserName}]]></ToUserName>
// <FromUserName><![CDATA[${message.ToUserName}]]></FromUserName>
// <CreateTime>${now}</CreateTime>
// <MsgType><![CDATA[text]]></MsgType>
// <Content><![CDATA[正在为你联系管理员,请稍后]]></Content>
// </xml>`;
// ctx.body = reply;

ctx.body = 'success';

// 由于微信消息要5秒内回复 所以使用异步 先返回后处理消息 自定义处理
// WXService.wxMessage(message);
} else {
// 否则接入失败。
ctx.body = 'no';
}
},

// 消息中增加打开小程序(必须是公众号关联的小程序)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// data-miniprogram-appid 是小程序appid
// data-miniprogram-path 是小程序页面路径
ctx.type = 'application/xml';
const reply = `<xml>
<ToUserName><![CDATA[${message.FromUserName}]]></ToUserName>
<FromUserName><![CDATA[${message.ToUserName}]]></FromUserName>
<CreateTime>${now}</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[hi,亲爱的老师,终于等到你~

欢迎加入bobo老师大家庭!在这里,您可以和众多有趣又靠谱的老师一起快乐成长!

作为专业的老师线上兼职创业平台,bobo老师将为您提供全方位的包装和优质的服务。赶紧加入吧,再晚连“知识付费的末班车”都赶不上喽!

点击下方菜单栏“我是老师”,马上进入小程序
<a data-miniprogram-appid="" data-miniprogram-path="pages/course/course" href="http://www.qq.com">“bobo老师服务中心”</a>,
注册成功后,就可以上传课程的视频啦。
]]></Content>
</xml>`;
ctx.body = reply;

第一次默认返回 echostr 使得消息推送提交成功

之后如果没有其他可用默认返回 success 字符串

  • 注意:
  1. 最好不用使用 http
文章目录