小程序訂閱消息
前置條件:小程序端需要訂閱消息授權。
流程:
1.獲取token
2.發送訂閱消息
代碼如下:
<?php namespace app\api\controller; use think\Controller; #訂閱消息 class T extends Controller { #獲取token public function index(){ $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=XXXXX&secret=XXXXX"; $html = file_get_contents($url); $arr=explode('"',$html); $token=$arr[3]; $res=$this->send($token); // echo "<pre>"; // print_r($res); } #發送消息 public function send($token){ $url="https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=$token"; //發送訂閱消息接口 $time=date('Y-m-d H:i:s',time()); $data=[ "touser"=> "XXXX", //openid "template_id"=> "XXXXXX", //模板id // "page"=> "index", // "miniprogram_state"=>"developer", "lang"=>"zh_CN", "data"=> [ "character_string1"=> [ //訂單號 "value"=> "20190101124564" ], "name3"=> [ //師傅名稱 "value"=> "王大錘" ], "phone_number6"=> [ //手機號 "value"=> "13812345678" ], "time10"=> [ //接單時間 "value"=> $time ], "thing11"=> [ "value"=> "有師傅接單了" ] ] ]; $data_string = json_encode($data); $ch = curl_init($url); curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, 'POST'); curl_setopt ($ch, CURLOPT_POSTFIELDS,$data_string); curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE ); // 對認證證書來源的檢查 curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, FALSE ); // 從證書中檢查SSL加密算法是否存在 curl_setopt ( $ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)' ); // 模擬用戶使用的瀏覽器 curl_setopt ($ch, CURLOPT_RETURNTRANSFER,true); curl_setopt ($ch, CURLOPT_HTTPHEADER, array( 'Content-Type: application/json')); $result = curl_exec($ch); return $result; } }