微信小程序订阅消息

370 阅读1分钟

前端弹窗获取订阅消息授权

let tmplIds="" ; //消息模板id
wx.getSetting({
      withSubscriptions: true,   //  这里设置为true,下面才会返回mainSwitch
      success: function(res){   
      
        // 调起授权界面弹窗
        if (res.subscriptionsSetting.mainSwitch) {  // 用户打开了订阅消息总开关
          if (res.subscriptionsSetting.itemSettings != null) {   // 用户同意总是保持是否推送消息的选择, 这里表示以后不会再拉起推送消息的授权
            let moIdState = res.subscriptionsSetting.itemSettings[tmplIds];  // 用户同意的消息模板id
            if(moIdState === 'accept'){   
              console.log('接受了消息推送');

            }else if(moIdState === 'reject'){
              console.log("拒绝消息推送");

            }else if(moIdState === 'ban'){
              console.log("已被后台封禁");

            }
          }else {
          	// 当用户没有点击 ’总是保持以上选择,不再询问‘  按钮。那每次执到这都会拉起授权弹窗
            wx.showModal({
              title: '提示',
              content:'请授权开通服务通知',
              showCancel: true,
              success: function (ress) {
                if (ress.confirm) {  
                  wx.requestSubscribeMessage({   // 调起消息订阅界面
                    tmplIds: [tmplIds],
                    success (res) { 
                      console.log('订阅消息 成功 ');
                     
                    },
                    fail (er){
                      console.log("订阅消息 失败 ");
                
                    }
                  })     
                        
                }
              }
            })
          }

        }else {
          console.log('订阅消息未开启')
        }      
      }, 
    }) 

后端发送消息

 /*
     *发送小程序订阅消息
     *$uid 被通知用户的id
     *$licenseplate 被通知用户的车牌号
     */
    public function send_subscribe_message($uid, $licenseplate)
    {
            $addonConfigList = get_addon_config('mycar');
         $appsecret = $addonConfigList['APP_SECRET'];
            $appid = $addonConfigList['APP_ID'];//小程序appid
             $code = $_REQUEST['js_code'];
        //根据uid获取用户微信openid
         $url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $appid . '&secret=' . $appsecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $content = file_get_contents($url);
        $content = json_decode($content, true);
        $unionid = isset($content['unionid']) ? $content['unionid'] : "";
        if (isset($content['session_key']) && isset($content['openid'])) {
            $openid =$content['openid'];
        // $openid = $this->get_user_wechat_openid($uid);
        // var_dump($openid);die;
        // if ($openid) {
            $MSG_TEMPLATE_ID = $addonConfigList['MSG_TEMPLATE_ID'];//模板消息id
            //获取公众号access_token
            $access_token = $this->gettokeninfo();
            $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
            $json_data = '{
               "touser":"' . $openid . '",
               "template_id":"' . $MSG_TEMPLATE_ID . '", 
               "page":  "pages/index/index" ,          
               "data":{
                    
                       "car_number1": {
                           "value":"' . $licenseplate . '",
                           "color":"#173177"
                       },
                       "thing2": {
                           "value":"当前",
                           "color":"#173177"
                       },
                       "date3": {
                           "value":"' . date("Y-m-d H:i:s") . '",
                           "color":"#173177"
                       },
                       "thing4":{
                           "value":"感谢您使用挪车小程序",
                           "color":"#173177"
                       }
               }
            }';
            $res = $this->curl_post2($json_data, $url);
            // var_dump($res);die;
            $call_sattus = json_decode($res, true);
            if ($call_sattus['errcode'] == 0) {
                //通知成功
                $resinfo['status'] = 1000;
                $resinfo['info'] = "通知成功,请耐心等待";
            } else {
                //通知失败
                $resinfo['status'] = $call_sattus['errcode'];
                $resinfo['info'] = "通知失败,请换种方式通知吧";
            }
        } else {
            //获取openid失败
            $resinfo['status'] = 1003;
            $resinfo['info'] = "通知失败,请换另外的方式通知用户";
        }
        return $resinfo;
    }
  public function curl_post2($post, $url = '', $Authorization = '')
    {
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type:application/json',
                'Authorization:' . $Authorization . ''
            )
        );
        $result = curl_exec($ch);
        return $result;
    }