因业务需求需要用到微信小程序的推送功能,并且后台要用Java实现.边看官方文档,边琢磨,终于搞出来了.
先整理下流程:推送顾名思义,即是给程序中的用户发送微信推送.当前微信小程序推送有两种形式,1用户支付后可发起推送,2用户通过表单提交可以触发推送.当前我用的是触发表单提交的方式.
首先我们需要选用模板

一般来说微信小程序提供的模板库中已经有很多可用的模板供我们选择,如果不符合业务需求,则可已定义添加模板,不过需要审核.

微信小程序模板推送需要用到两个API 第一个
GET https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET

我们需要先获取模板的使用权限,注意次请求是Get请求.
第二个
POST https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=ACCESS_TOKEN


这些参数一会我们都要用到.
其中在页面中我们可以获取的是 form_id 和 touser也就是openid
form_id是我们表单提交后产生的一个id,而openid则是通过wx.login()获取的一个临时code,在发送请求获取的微信用户在当前小程序唯一的凭证.对于openid这里不多解释.


页面需要主页的是 report-submit设置为true则可以获取formid,button的form-type需要设为submit.
如此我们便可以获取一个formid
接下来是Java后台

附录get请求的方法


下面就是真正的推送了


附录post请求方法


这里的post请求需要注意的是一定要请求头中的请求参数为json否则会失败.
如上则可以顺利给用户发送模板

网友评论