微信小程序之订阅消息

准备工作

演示

给按钮绑定一个事件触发订阅消息接口,示例如下:
wxml

<van-button round type="info" bindtap="pass" >通过</van-button>

js

  pass:function(){
    wx.requestSubscribeMessage({
      tmplIds: ['模板ID'],
      success:(res)=> {  
        //成功回调  
          wx.setStorageSync('tmplid', '模板ID')
        },

      fail(err) {

      }
  })
    wx.navigateTo({
      url: '/pages/test/pass'
    })
  }

点击按钮

选择允许,再点击发送订阅消息,会在服务通知收到一条订阅消息

后端代码(以原生PHP为例)

<?php
ini_set('display_errors', 'On');
$token_file = './mn_access_token';
$life_time = 7200;
//文件存在,并且最后修改时间与当前时间的差小于access_token的有效期,则有
if(file_exists($token_file) && time()-filemtime($token_file)<$life_time){
   //直接获取
  $access_token = file_get_contents($token_file);
}else{
  $appid = '你的appid';
  $secret ='你的appsecret';
  $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
  $curl = curl_init();
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($curl, CURLOPT_TIMEOUT, 500);
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
  curl_setopt($curl, CURLOPT_URL, $url);
  $res = curl_exec($curl);
  curl_close($curl);
  $tokenArr = json_decode($res,true);
  $access_token = $tokenArr['access_token'];
  file_put_contents($token_file, $access_token);
}
  $msgUrl = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=".$access_token;
  $data = [
  'touser' => $_POST['openid'],
  'template_id' => $_POST['tplid'],
  'page' => '/pages/doctor/borrowcheckpass',
  'data' =>
  [
    'number4' =>
    [
      'value' => date('Ymd').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8),
    ],
    'name6' =>
    [
      'value' => '测试患者',
    ],
    'thing8' =>
    [
      'value' => '测试实物玻片',
    ],
    'phone_number7' =>
    [
      'value' => '0551-'.mt_rand(1000000,9999999),
    ],
    'amount2' =>[
       'value' =>mt_rand(1,100),
    ]
  ],
];
  $ch = curl_init();

  curl_setopt($ch, CURLOPT_URL, $msgUrl);

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

  // POST数据

  curl_setopt($ch, CURLOPT_POST, 1);

  // 把post的变量加上

  curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));

  $output = curl_exec($ch);

  curl_close($ch);
  echo $output;

其中data参数格式可以模板详情

posted @ 2021-08-19 16:58  selfim  阅读(595)  评论(0编辑  收藏  举报