小程序订阅消息(模板消息已被废弃)

小程序订阅消息
前置条件:小程序端需要订阅消息授权。
流程:
1.获取token
2.发送订阅消息
代码如下:
<?php
namespace appapicontroller;
use thinkController;
#订阅消息
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;
 
        
 
 
    }
    
    
}
 
原文地址:https://www.cnblogs.com/cyk2/p/13819322.html