微信模板推送其实是相对简单的。微信的相关的模板的建立在这里我就不说了,直接去查看文档就好了。模版消息只对认证的服务号开放。
后台数据的处理
模版消息调用时主要需要模版ID和模版中各参数的赋值内容。请注意: 1.模版中参数内容必须以".DATA"结尾,否则视为保留字; 2.模版保留符号"{{ }}"
<?php
class index{
var $appid="wx1XXXXXXXXXXX1bc";
var $sercet_app="03XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX7bb";
var $access_token;
function __construct()
{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->appid."&secret=".$this->sercet_app;
//get获取access_token的值
$data=$this->curl_get($url);
$res=json_decode($data);
$this->access_token=$res->access_token;
}
function root()
{
//模板消息
$json_template = $this->json_tempalte();
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$res=$this->postJson($url,urldecode($json_template));
}
function json_tempalte()
{
//模板消息
$template=array(
'touser'=>'o3XXXXXXXXXXXXXXXXXXXglQ', //用户openid
'template_id'=>"N0ur9yXXXXXXXXXXXXXXXXXXXXXY3ZrFv8", //在公众号下配置的模板id
'url'=>"www.XXXXXXXXXXX", //点击模板消息会跳转的链接
'topcolor'=>"#7B68EE",
'data'=>array(
'dept'=>array('value'=>urlencode("节操充值中心"),'color'=>"#FF0000"),
'event'=>array('value'=>urlencode('您的节操已透支'),'color'=>'#FF0000'), //keyword需要与配置的模板消息对应
'no'=>array('value'=>urlencode('请及时充值'),'color'=>'#FF0000'),
'status'=>array('value'=>urlencode('爱谁谁'),'color'=>'#FF0000'),
'startdate'=>array('value'=>urlencode('2019-01-01'),'color'=>'#FF0000'),
'enddate'=>array('value'=>urlencode('2019-02-28'),'color'=>'#FF0000'),
'remark' =>array('value'=>urlencode('备注:爱充不充'),'color'=>'#FF0000'), )
);
$json_template=json_encode($template);
return $json_template;
}
function curl_get($url)
{
$ch = curl_init();
// 必须的四个配置
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=utf-8;'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
// curl_setopt($ch, CURLOPT_POST, 1);
// curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$content = curl_exec($ch);
return $content;
}
function postJson($url, $json, $type = "array")
{
try {
$ch = curl_init();
// 必须的四个配置
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json;charset=utf-8;'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$content = curl_exec($ch);
} catch (HttpException $ex) {
return $ex . "<-Exception";
}
if ($type == 'array') {
return json_decode($content, true);
} else {
return $content;
}
}
}