PHP微信公众平台开发高级篇--模板消息接口

实例

<?php
/**
 * 模板消息
 * 作用:1.用户公众号向用户发送重要的服务通知
 * 文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
 * 步骤:(测试账号),真实账号需要选择行业类型
 * 1.新增模板(标题,模板内容),变量定义格式{{变量名.DATA}},如{{name.DATA}}
 * 2.不建议用浏览器直接请求,会导致推送多次消息,可设置为事件推送
 */
header("Content-type: text/html; charset=utf-8");
$postArr = file_get_contents('php://input');
$postObj = simplexml_load_string($postArr,'SimpleXMLElement', LIBXML_NOCDATA);
$accessTokenInfo = file_get_contents("access_token.log");
$tokenArr = json_decode($accessTokenInfo,true);
if($accessTokenInfo && isset($tokenArr['expires_in']) && ($tokenArr['expires_in'] >time())){//保证不过期,做缓冲
    //1.获取全局access_token
    $access_token = $tokenArr['access_token'];
    //2.组装群发接口数据 array
    $array = [
        'touser' => 'oL-zT1Hkbx6Zza5Ny4ZZJr3Ze1-U',
        'template_id' => 'IjJoLC7ZO9Ux5CALOMA1NhEq2g3FnWEITxwJ1W1JuuE',
        'url' => 'www.baidu.com',
        'data' =>[
            'name' => ['value'=>'Jason','color'=>'#333'],//不能直接使用green,red这种方法
            'date' => ['value'=>'2018-07-17','color'=>'#157efb']
        ]
    ];
    //3.array===>json
    $postJson = json_encode($array);
    //调用curl
    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$access_token;
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_POST,1);
    curl_setopt($ch,CURLOPT_POSTFIELDS,$postJson);
    $output = curl_exec($ch);
    curl_close($ch);
    var_dump(json_decode($output,true));
}else{
    //重新请求access_token写入文件
    $ch = curl_init();
    $appId = "wxc7991ed87e25dc13";
    $appSecret = "3c1be9b400aae7042afb78dbd577f206";
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    $outPut = curl_exec($ch);
    curl_close($ch);
    $arr = json_decode($outPut,true);
    $tmp = [
        'access_token' =>$arr['access_token'],
        'expires_in' =>time() + ($arr['expires_in'] - 200)
    ];
    file_put_contents("access_token.log",json_encode($tmp));
}

猜你喜欢

转载自blog.csdn.net/qq_29627497/article/details/81099225