說明:該接口用于對小程序用戶發(fā)送服務(wù)通知,效果如下圖
image.png
image.png
流程說明:
0.先配置消息模板,在[微信公眾平臺(mp.weixin.qq.com)-功能-訂閱消息]中配置
1.小程序端對用戶喚起消息訂閱,用戶選擇接收消息的選項(模板);
2.后端在需要的時候往用戶接受過的模板進行發(fā)送服務(wù)通知掌眠;
小程序端代碼:
接口文檔:https://developers.weixin.qq.com/miniprogram/dev/api/open-api/subscribe-message/wx.requestSubscribeMessage.html
//小程序的html部分:index.wxml
<button bindtap="issue_subscribe_request" style=""> 喚起訂閱消息 </button>
//小程序的js部分:index.js
//發(fā)起訂閱請求
issue_subscribe_request(e){
wx.requestSubscribeMessage({
tmplIds: [
'qIpFKwcL_O12LLkmI6yps1o9ifW_4mv7AZUWdkzOlkk','mbdr6nqD0VRwDf69QEmYrlNsjgy4HIMuriEgYpUeHdk'],
success (res) {
console.log(res)
}
})
}
效果如下:
注:1.用戶沒有打勾的選項(模板),服務(wù)端無法向該用戶發(fā)送該選項的消息幕屹;
2.點擊下方的“總是保持以上選擇扇救,不再詢問”后,此用戶無法再喚起該彈窗香嗓,并且
①用戶全部都打勾選項并選總是迅腔,則服務(wù)端可以一直給該用戶發(fā)消息;
②用戶沒有打勾的選項并選總是靠娱,則再也無法給該用戶發(fā)送相關(guān)的服務(wù)通知沧烈;
image.png
PHP服務(wù)端代碼:
接口文檔:https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/subscribe-message/subscribeMessage.send.html
/**
* @desc 該方法向用戶發(fā)送評論通知
* @param $openid 接收消息用戶的openid
* @param $arr 消息內(nèi)容,根據(jù)模板需要進行配置
*/
public function send_subscribe_message($openid,$arr){
//小程序后臺配置的模板id
$template_id = "qIpFKwcL_O12LLkmI6yps1o9ifW_4mv7AZUWdkzOlkk";
//消息發(fā)送的格式
$template = "{
\"touser\": \"{$openid}\",
\"template_id\": \"{$template_id}\",
\"page\": \"index\",
\"miniprogram_state\":\"developer\",
\"lang\":\"zh_CN\",
\"data\": {
\"thing2\": {
\"value\": \"{$arr['content']}\"
},
\"time3\": {
\"value\": \"{$arr['create_time']}\"
},
\"thing5\": {
\"value\": \"{$arr['nickname']}\"
} ,
\"thing9\": {
\"value\": \"{$arr['remark']}\"
}
}
}";
//獲取access_token
$access_token = $this->get_access_token();
//使用curl進行請求
$url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token={$access_token}";
//$this->curl_post($url,$template)
$res = $this->curl_post($url,$template);
return $res;
//成功:"{"errcode":0,"errmsg":"ok","msgid":1822356413101195268}"
//失斚裨啤:"{"errcode":43101,"errmsg":"user refuse to accept the msg rid: 6073f992-2337e5cf-0dee24c3"}" //用戶沒有訂閱消息時的錯誤提示
}
//curl請求的方法
private function curl_post($url,$data=array()){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
// POST數(shù)據(jù)
curl_setopt($ch, CURLOPT_POST, 1);
// 把post的變量加上
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
/**
* @desc 獲取access_token
*/
private function get_access_token(){
$appid = '小程序的appid';
$secretkey = '小程序的key';
$url = "https://api.weixin.qq.com/cgi-bin/token?
grant_type=client_credential&appid=".$appid."&secret=".$secretkey ;
$res = json_decode(file_get_contents($url),true);//獲取微信返回的access_token
$access_token = $res['access_token'];
//獲取到access_token應(yīng)該保存起來锌雀,一般7000秒內(nèi)不會過期
}