php 小程序订阅消息

功能介绍

消息能力是小程序能力中的重要组成,我们为开发者提供了订阅消息能力,以便实现服务的闭环和更优的体验。

  • 订阅消息推送位置:服务通知
  • 订阅消息下发条件:用户自主订阅
  • 订阅消息卡片跳转能力:点击查看详情可跳转至该小程序的页面

使用说明

步骤一:获取模板 ID

在微信公众平台手动配置获取模板 ID:
登录 https://mp.weixin.qq.com 获取模板,如果没有合适的模板,可以申请添加新模板,审核通过后可使用。

步骤二:获取下发权限

前端的接口:我们可以预设多个模板ID一起申请,用户勾选的会返回accept,也是就通过,后端就可以记录了。

wx.requestSubscribeMessage({
  tmplIds: [''],
  success (res) { }
})

 

步骤三:调用接口下发订阅消息

POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN

/
* 发送订阅消息
 * @return [type] [description]
 */
public function sendSubMessage($openId = "openId",$tmpl = "TEMPLATE_ID",array $data,$page='',$miniprogram_state='formal'){

    $params['touser'] = $openId;
    $params['template_id'] = $tmpl;
    $params['page'] = $page;
    $params['miniprogram_state'] = $miniprogram_state;
    $params['data'] = $data;

    $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
    $re = $this->curl_url($url,$params);
    return $re;

}

private function curl_url($url, $json)
{
    $body = json_encode($json);
    $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    $result = curl_exec($ch);
    curl_close($ch);

    return $result;
}

data请求示例

{
  "touser": "OPENID",
  "template_id": "TEMPLATE_ID",
  "page": "index",
  "miniprogram_state":"developer",
  "lang":"zh_CN",
  "data": {
      "number01": {
          "value": "339208499"
      },
      "date01": {
          "value": "2015年01月05日"
      },
      "site01": {
          "value": "TIT创意园"
      } ,
      "site02": {
          "value": "广州市新港中路397号"
      }
  }
}

 官方文档:https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/subscribe-message.html

posted @ 2020-03-06 17:19  晴箜万里  阅读(2092)  评论(0编辑  收藏  举报