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));
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JasonHome

你的鼓励是我创作的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值