在我們開發(fā)微信小程序中經(jīng)常會(huì)用到訂閱消息提醒趣钱,如商城系統(tǒng)中,用戶購買商品支付之后渔隶,可以發(fā)送提醒訂單支付成功羔挡;在我們的拼團(tuán)功能中,當(dāng)拼團(tuán)成功或失敗時(shí)间唉,可以推送訂閱消息提醒用戶绞灼;
一、訂閱消息分為長期訂閱和一次性訂閱呈野;
長期訂閱消息:就是在用戶授權(quán)之后低矮,可以推送多次消息給用戶;
一次性訂閱消息:就是用戶授權(quán)后只能推送一次消息給用戶被冒,如果還需要推送消息的話军掂,就必須讓用戶再授權(quán)一次了;
兩者比較起來的話肯定長期訂閱消息用起來比較舒服的昨悼;但是它不是所有開發(fā)者都可以申請(qǐng)蝗锥,一般是需要有一定的資質(zhì)才行,如媒體類率触;具體的話终议,大家可以看官方文檔的解釋更為詳細(xì);
二葱蝗、訂閱消息模板
2.1穴张、訂閱消息模板申請(qǐng)
我們平時(shí)在微信的通知服務(wù)中可以看到一些別的小程序的通知,它提示的字段都是需要先去小程序后臺(tái)中申請(qǐng)模板的两曼;
2.2皂甘、根據(jù)自己的需要挑選模板,并選擇所需字段
這里我選擇了支付成功后的訂閱消息模板
好了悼凑,挑選完模板后偿枕,我們開始進(jìn)行開發(fā);
三户辫、小程序代碼編寫
3.1益老、小程序中創(chuàng)建一個(gè)頁面,放入一個(gè)按鈕寸莫,并綁定一個(gè)點(diǎn)擊函數(shù)
xml:
<view class="intro">訂閱功能Demo</view>
<view>
<button type="info" bindtap="submit">提交訂單</button>
</view>
3.2捺萌、獲取訂閱權(quán)限,這里需要調(diào)用官方提供的API
wx.requestSubscribeMessage({
tmplIds: [''], //你的模板ID
success (res) { }
})
3.3、js代碼如下
const app = getApp()
Page({
data: {
},
onLoad: function () {
},
submit(){
wx.requestSubscribeMessage({
tmplIds: ['你的模板Id'],
success (res) {
//發(fā)送請(qǐng)求到后端桃纯,后端接收到請(qǐng)求后調(diào)用訂閱消息接口進(jìn)行推送
}
})
}
})
到這里我們可以測試效果了酷誓,點(diǎn)擊按鈕后會(huì)彈出授權(quán)框;要用真機(jī)調(diào)試才可以看到效果哦~
四态坦、編寫后端代碼
4.1盐数、實(shí)現(xiàn)邏輯
4.1.1.前期需要有推送用戶的openid
openId是用戶在小程序中的唯一標(biāo)識(shí),也就是我們要推送給誰
4.1.2.我們需要先獲取access_token伞梯;
access_token就類似一個(gè)臨時(shí)身份證玫氢;我們需要傳遞appId和appSecret去官方提供的接口進(jìn)行身份驗(yàn)證,如果你的appId和appSecret正確谜诫,就會(huì)傳遞一個(gè)access_token給你漾峡;這個(gè)token是有時(shí)效性的(7200s),也就是說7200s之后這個(gè)token就失效了喻旷,后面如果需要使用就需要重新獲取
4.1.3.封裝訂閱消息模板內(nèi)容
這里的封裝格式需要注意一下生逸;
例如,模板的內(nèi)容為
姓名: {{name01.DATA}}
金額: {{amount01.DATA}}
行程: {{thing01.DATA}}
日期: {{date01.DATA}}
則我們要封裝的數(shù)據(jù)格式應(yīng)為
{
"touser": "OPENID",
"template_id": "TEMPLATE_ID",
"page": "index",
"data": {
"name01": {
"value": "某某"
},
"amount01": {
"value": "¥100"
},
"thing01": {
"value": "廣州至北京"
} ,
"date01": {
"value": "2018-01-01"
}
}
}
4.1.4.調(diào)用接口推送訂閱消息
POST請(qǐng)求地址
https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
4.2且预、開發(fā)代碼
4.2.1.導(dǎo)入HTTP請(qǐng)求工具槽袄,這里使用Hutool非常好用的Java開發(fā)SDK
官方文檔地址:
在pom.xml文件中引入maven包
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.0</version>
</dependency>
4.2.2.獲取access_token
public String getAccessToken() {
String appId = "你的openId";
String appSecret = "你的小程序密鑰";
String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
JSONObject jsonObject = JSONUtil.parseObj(result);
return jsonObject.getStr("access_token");
}
4.2.3.發(fā)送訂閱消息
@RequestMapping("/send")
public String send(){
JSONObject body=new JSONObject();
body.set("touser","用戶的openId");
body.set("template_id","你的模板Id");
JSONObject json=new JSONObject();
json.set("thing6",new JSONObject().set("value","20200820757539"));
json.set("date4",new JSONObject().set("value", LocalDateTime.now()));
json.set("amount3",new JSONObject().set("value","多功能等一件商品"));
json.set("character_string2",new JSONObject().set("value", DateUtil.now()));
json.set("thing5",new JSONObject().set("value","拼團(tuán)"));
body.set("data",json);
//發(fā)送
String accessToken= getAccessToken();
String post = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
return "ok";
}
4.2.4.整合代碼
package com.maomao.demo.controller;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
@RestController
@RequestMapping("/msg")
public class MessageController {
public String getAccessToken() {
String appId = "你的openId";
String appSecret = "你的小程序密鑰";
String result = cn.hutool.http.HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret);
JSONObject jsonObject = JSONUtil.parseObj(result);
return jsonObject.getStr("access_token");
}
@RequestMapping("/send")
public String send(){
JSONObject body=new JSONObject();
body.set("touser","用戶的openId");
body.set("template_id","你的模板Id");
JSONObject json=new JSONObject();
json.set("thing6",new JSONObject().set("value","20200820757539"));
json.set("date4",new JSONObject().set("value", LocalDateTime.now()));
json.set("amount3",new JSONObject().set("value","多功能等一件商品"));
json.set("character_string2",new JSONObject().set("value", DateUtil.now()));
json.set("thing5",new JSONObject().set("value","拼團(tuán)"));
body.set("data",json);
//發(fā)送
String accessToken= getAccessToken();
String post = cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());
return "ok";
}
}
五、小程序端調(diào)用
5.1锋谐、調(diào)用后端API接口
const app = getApp()
Page({
data: {
},
onLoad: function () {
},
submit(){
wx.requestSubscribeMessage({
tmplIds: ['你的模板Id'],
success (res) {
//發(fā)送請(qǐng)求到后端遍尺,后端接收到請(qǐng)求后調(diào)用訂閱消息接口進(jìn)行推送
wx.request({
url: '你后端編寫的推送api地址',
method:"GET",
data:{},
success (res) {
console.log(res.data)
}
})
}
})
}
})