微信小程序之訂閱消息


准備工作

演示

給按鈕綁定一個事件觸發訂閱消息接口,示例如下:
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參數格式可以模板詳情


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM