微信小程序订阅通知的实现

背景:

为了让小程序有通知的功能,就要添加小程序的订阅功能

开发步骤:

1.在微信公众平台添加订阅功能配置

 选用模板可以选用里面的字段(无法自定义的文字。。),要注意一般用户只有一次性订阅的能力,长期性订阅类目消息仅向政务民生、医疗、交通、金融、教育等线下公共服务开放

选完模板后,会得到一个模板id,复制保存起来

2.代码开发

首先需要小程序前端用户确认同意发送消息

小程序前端代码

  auditSubscriptionsSetting() {
    let that = this;
    const tmplId = 'xxxxx'; //模板id
    wx.getSetting({
      withSubscriptions: true,
      success(res) {
        if (res.subscriptionsSetting && res.subscriptionsSetting.mainSwitch) {
          if (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings[tmplId]) {
            let item = res.subscriptionsSetting.itemSettings[tmplId];
            if (item == 'reject') {
              console.log('提示:用户拒绝订阅消息');
              that.followComfirm(tmplId);
            } else if (item == 'accept') {
              console.log('提示:您已经开启订阅消息');
            } else if (item == 'ban') {
              console.log('提示:您已经被后台封禁');
            }
          } else {
            console.log('提示:用户没有勾选订阅消息或者没有状态');
            that.followComfirm(tmplId);
          }
        } else {
          console.log('提示:订阅消息主开关没打开');
          that.followComfirm(tmplId);
        }
      }
    });
  },
  // 订阅信息
  followComfirm(tmplId) {
    wx.showModal({
      title: '订阅消息',
      content: '请同意我们给您推送信息,以便接受租户提交审核提醒。',
      success: (res) => {
        if (res.confirm) {
          wx.requestSubscribeMessage({
            tmplIds: [tmplId],
            success: (res) => {
              if (res[tmplId] === 'accept') {
                wx.showToast({
                  title: '订阅成功!',
                  icon: 'success'
                });
              } else if (res[tmplId] == 'reject') {
                //引导用户,手动引导用户点击按钮,去设置页开启,## Modals是自定义组件
                wx.showModal({
                  title: '订阅消息',
                  content: '您当前拒绝接受消息通知,是否去开启',
                  confirmText: '开启授权',
                  confirmColor: '#345391',
                  cancelText: '仍然拒绝',
                  cancelColor: '#999999',
                  success(res) {
                    if (res.confirm) {
                      console.log('用户点击确定');
                      wx.openSetting({
                        success(res) {
                          console.log(res.authSetting);
                        },
                        fail(err) {
                          //失败
                          console.log(err);
                        }
                      });
                    } else if (res.cancel) {
                      console.log('用户点击取消');
                    }
                  }
                });
              }
            },
            fail(err) {
              //失败
              console.log(err);
            }
          });
        }
      }
    });
  }

上面代码要执行auditSubscriptionsSetting方法,小程序页面就会弹出授权的,用户只要点了确认之后(这时候前端的操作已经完成)。用户想要收到订阅消息,需要后端调用微信订阅的接口去通知微信给用户发消息。

后端消息发送代码 


<?php 

send();
 
function send() {   
    //接口调用凭证 
    $token = get_token();		  
    //消息字段值
    $cont = array(
            "thing4"=>[ 
                "value"=> "消息参数内容", //备注 
            ],  
            "thing2"=>[ 
                "value"=> "消息参数值",   
            ],            
            "thing8"=>[            
                "value"=> "消息参数值",                         
            ], 
            "time7"=>[ 
                "value"=> "2023-04-30",   
            ], 
            
    ); 
    $data = array("touser"=>"xxxxxxxxxxxxxxx",
                "template_id"=>"QaLP3rJgiMCaM_fOX-d6NXVepwh8Zqfq2iXMuBwxgBA", 
                "page"=>"index",  //点击模板卡片后的跳转页面,仅限本小程序内的页面
                "miniprogram"=>"developer",  //跳转小程序类型: developer 为开发版; trial 为体验版; formal 为正式版;默认为正式版
                "lang"=>"zh_CN",	 
                "topcolor"=>"#FF0000",
                "data"=>$cont);	//模板内容     
    $result=curlPost("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$token",json_encode($data));     
    print_r($result);
}


/**  
 * 获取access_token 
 */
function get_token()
{ 
    $appid = "wxc09ab35dea5a26ab";
    $secret = "0b5fd52751e5b800d2a4daa9bb117491";
    $result = curlPost("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret",""); 
    $arr = json_decode($result, true);
    $result = $arr["access_token"];
    return $result;
}


//模拟post请求
function curlPost($url,$data)
{
    $ch = curl_init();
    $params[CURLOPT_URL] = $url;    //请求url地址
    $params[CURLOPT_HEADER] = FALSE; //是否返回响应头信息
    $params[CURLOPT_SSL_VERIFYPEER] = false;
    $params[CURLOPT_SSL_VERIFYHOST] = false;
    $params[CURLOPT_RETURNTRANSFER] = true; //是否将结果返回
    $params[CURLOPT_POST] = true;
    $params[CURLOPT_POSTFIELDS] = $data;
    curl_setopt_array($ch, $params); //传入curl参数
    $content = curl_exec($ch); //执行
    curl_close($ch); //关闭连接
    return $content;
}

3.常见的坑


问题1:用户收不到订阅消息

有几种可能,一个是发通知的时候,用户没去点授权,一次性的授权每次用户都要点一次授权,下次才能收到消息(巨坑。。。)

问题2:用户界面没有弹出授权的弹窗

是因为用户禁用的订阅授权,还有就是用户点了“总是保持以上选择,不再询问”,导致用户再也不发弹出授权框,就算微信卸载了也不行。(微信这种业务逻辑,真的是脑残+巨坑)。解决方式:开发人员可以在微信开发者工具里面,点击清除授权,就能弹了!!!,或者换一个模板id,这样一次性大家就恢复了弹窗授权 
 

猜你喜欢

转载自blog.csdn.net/qq_31432773/article/details/130450267