微信小程序#订阅消息#学习笔记

这可能是我看过的关于“微信小程序订阅消息”的文章里最简单的一篇

首先,微信小程序关于订阅消息的官方文档->
https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html
使用场景: 点击微信小程序里的某个按钮,会收到通知,例如预约会议成功后收到预约成功的提醒。等等。

步骤一:获取模板 ID

订阅消息需要我们提前准备消息的模板。
模板消息分两种,一种官方提供的公共模板,另一种是自定义的消息模板。按照自己的实际需要选择即可。这一步最重要的是获取模板ID。
在这里插入图片描述

步骤二:获取openId

  1. 小程序页面添加按钮,绑定事件 ,也可以在其他步骤里实现这一步,看了很多文档和文章,“这一步不需要授权”;
// 小程序前端页面wxml
<button type='primary' bindtap='getTmplID'>发送订阅消息</button>
  1. 获取openId ,必备参数 appid获取appsecret,与服务器通信,获取openId,然后设计数据库,存起来后面使用即可;
// 小程序前端页面js
getTmplID: function () {
    var that = this;
    wx.login({
      success: function (res) {
          if (res.code) {
              console.log("我是登录凭证:"+res.code);  
              wx.request({
                   url: 'https://xxxx/getopenid',  //后台获取openid的链接,该链接域名需要添加到小程序request 合法域名
                   header: { "Content-Type": "application/x-www-form-urlencoded" },
                   method: "POST",
                   data: {  code: res.code, appid: 'xxxx', appsecret:'xxxx' },  
                   success: function (res) {

                       app.globalData.openid = res.data.openid;
                       //console.log("openid:"+app.globalData.openid);
                   }
             })
          } else {
             console.log('获取用户登录态失败!' + res.errMsg)
          }
      }
  }),
  1. thinkphp后端实现 上面的逻辑接口;
 //获取openid
    public function getopenid(){
        $data = $_POST;
        //echo json_encode($data);
        $appid=$data['appid'];
        $appsecret=$data['appsecret'];
        $code=$data['code'];
        $get_url="https://api.weixin.qq.com/sns/jscode2session?appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=authorization_code";
        $get_return = file_get_contents($get_url);
        $get_return = (array)json_decode($get_return);
        //$openid=$get_return['openid'];
        echo json_encode($get_return);exit();
    }

步骤三,获取“获取订阅消息”下发权限

小程序端消息订阅接口

//小程序js页面里部署该函数即可
//tmplIds就是上面获得的消息模板ID
wx.requestSubscribeMessage({
      tmplIds: ['xxxx'],
      success(res) {
        console.log(res)
        if (res['xxxx'] === 'accept') {
          console.log('用户同意了')
          wx.showToast({
            title: '订阅OK!',
            duration: 1000,
          })
          console.log(app.globalData.openid);
          wx.request({
            
            method: 'POST',
            //url: '订阅消息接口api',
            url: 'https://xxxx/sendMessage',
            //不是josn格式
            header: {
              'content-type': 'application/json'
            },
            
            data: 
              JSON.stringify({
                touser: 'xxx', //当前用户的openid
                template_id: "xxx", //需要下发的模板ID,如模板不多可让后台直接配置写死,多的话就通过微信获取模板列表接口查询模板
                page: "pages/xxx/xxx", //点击小程序订阅消息跳转的页面,可携带参数
                data: {
                "thing1": { //这个key值就是上面提到的关键词,在后台对应的模板详情里可以看到,等后台-->点订阅消息-->我的模板(没有的话先去公共模板库选一个)-->点击详情-->右边详细内容里就是对应的key了
                 "value": 'xxx' //这个值是下发给用户的信息
                },
                "time2":{
                  "value":'2020-07-25 19:52'
                },
                "thing3": {
                "value": 'ok'
                }
                }
                }),
              
            //调用接口成功
            success: function (res) {
              console.log(res);
            },
          });
 
        }
      },
      fail(err) {
        //失败
        console.error(err);
        reject()
      }
    })

步骤四:服务器端调用接口下发订阅消息

thinkphp做服务端,调用消息发送接口

 //发送订阅消息
    public function sendMessage()
    {
        //获取access_token
        #$accessToken = new AccessToken();
        $access_token = $this-> getAccessToken();
        $openId='xxxx';
        $templateId='xxxxx';
        
        $data = array(
                "touser"=>$openId,
                "template_id"=>$templateId,
                "page"=>"/pages/xxx/xxx",
                "data"=>array(
                  "thing1"=>array(
                      "value"=>'xxxx',
                      "color"=>"#173177"
                   ),
                   "time2"=>array(
                       "value"=>'20xx年xx月xx日 12:30:00',
                       "color"=>"#173177"
                   ),
                   "thing3"=>array(
                       "value"=>'xxxx',
                       "color"=>"#173177"
                   ),
             ),
            );
            
        //将路径中占位符%s替换为$access_token值
        echo $access_token;
        $urls = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        $ret = $this-> postCurl($urls, $data,'json');
        echo $ret;
        return $ret;
        //return $ret;
    }

//获取accessToken    
    public function getAccessToken()
    {
        //当前时间戳
        $now_time = strtotime(date('Y-m-d H:i:s',time())) ;

        //失效时间
        $timeout = 7200 ;

        //判断access_token是否过期
        $before_time = $now_time - $timeout ;

        //未查找到就为过期
        
        //实例化数据表
        $Takeout_token = M('Takeout_access_token');
        
        $data=$Takeout_token->where('id',1)
            ->where('update_time' ,'>',$before_time)
            ->select();
            
        $access_token = $data['access_token'];

        //如果过期
        if( !$access_token ) {

            //获取新的access_token
            $appid  = 'xxxx'; //小程序id
            $secret = 'xxxx'; //小程序密钥
            $url    = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
            $res = json_decode(file_get_contents($url),true);

            $access_token = $res['access_token'] ;

            //更新数据库
            
            $update['access_token'] = $access_token ;
            $update['update_time']  = $now_time ;
            
            //实例化数据表
            $Takeout_token = M('Takeout_access_token');
            $Takeout_token->where('id',1)->save($update) ;
        }

        return $access_token ;
        //echo $access_token ;
    }
    
//发送post请求
     function postCurl($url,$data,$type){
         if($type == 'json'){
             $data = json_encode($data);//对数组进行json编码        
             $header= array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
             }    
        $curl = curl_init();    
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_SSL_VERIFYHOST,false);
        if(!empty($data)){
            curl_setopt($curl,CURLOPT_POSTFIELDS,$data);
            }
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        curl_setopt($curl,CURLOPT_HTTPHEADER,$header);
        $res = curl_exec($curl);
        if(curl_errno($curl)){
            echo 'Error+'.curl_error($curl);
            }
        curl_close($curl);
        return $res;
        
     }

至此,从前端按钮获取openid,到获取订阅消息权限,再到后端发送消息,整个流程全部完成,微信上可以按我们之前设计的模板进行消息发送。搭配我们设计好的流程即可完成丰富的应用场景。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值