微信公众平台之模板消息(php)
由于是第一次写博客,之前都是做好了就不管了,今天我就把我当初写的发出来给大家看看。请多多指教哦。
首先来看看模板消息的接口文档
1、模板消息调用时主要需要模板ID和模板中各参数的赋值内容;
2、模板中参数内容必须以”.DATA”结尾,否则视为保留字;
3、模板保留符号”{{ }}”。
接口调用请求说明
http请求方式: POST
https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=ACCESS_TOKEN
直接上代码吧:
public function index(){
$appid = '你的appid';
$appsecret = '你的appseceret';
$access_token=$this->access_token($appid,$appsecret);
$time="1484366836";
$this->template_message($access_token,$time,$openid);
}
//获取公众号的access_token
public function access_token($appid,$appsecret,$time){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
$data = curl_exec($ch);
curl_close($ch);
$data = json_decode($data,true);
return $data['access_token'];
}
//模板消息内容
public function template_message($access_token,$openid,$time){
$formwork = '{
"touser":"'.$openid.'",
"template_id":"fEQlkgna7XyjaGpKEGTGnY6WzZMAmUGUQbNxozATy5s",
"url":"http://baidu.com", //用户收到模板消息点击跳转url
"data":{
"first": {
"value":"Hi,你的会员卡即将到期,请尽快续费以免影响你的运动计划噢。\n",
"color":"#000000"
},
"name": {
"value":"会员",
"color":"#173177"
},
"expDate": {
"value":"'.date('Y-m-d H:i',$time).'",
"color":"#173177"
},
"remark":{
"value":"\n[重要提示]购卡续卡请点我噢~",
"color":"#173177"
}
}
}';
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$access_token}";
$this->http_curl($formwork,$url);
}
//curl
public function http_curl($formwork,$url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,0);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$formwork);
$data = curl_exec($ch);
curl_close($ch);
$judge = json_decode($data,true);
if($judge->errcode !=0){
$judge->errcode =$errror_code;
echo $error_code;
$this->error("发送失败!");
}else{
$this->success('成功');
}
}
最后要注意的就是:
获取access_token 每日限制2000次,超过了没有办法使用了。
不过还是可以解决的:
$token = json_decode(file_get_contents("access_token.json"),true);
if (time() > $token['expire_time'] || !$token['expire_time']){
$param['grant_type'] = 'client_credential';
$url = "{$this->apiURL}/token";
$res = self::http($url, $param);
$result = json_decode($res, true);
$access_token = $result["access_token"];
if ($access_token) {
$data->expire_time = time() + 7000;
$data->access_token = $access_token;
$fp = fopen("access_token.json", "w");
fwrite($fp, json_encode($data,true));
fclose($fp);
$token = json_decode($data, true);
}
}
$access_token = $token['access_token'];
有什么写得不好的地方,请指教哦。或者你有更简便的方法,我很乐意听的。