再申请完模板后,根据官方文档,我们知道需要将数据json化后post到下面这个地址
https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
那么我们就需要获取ACCESS_TOKEN,这个如何获取呢?获取的方式官方给出了好多种,找了一会就用这个最直接的吧,其中的appid和appsecret,请在公号基本配置中查找。
https请求方式: GET
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
正常情况下,请求GET请求这个地址微信会返回如下数据:
{"access_token":"ACCESS_TOKEN","expires_in":7200}
其中的access_token就是我们需要的,将数据对应申请的模板填写一下 执行发送就可以了,完整代码如下:
public function http_curl($url,$type,$res,$arr){
/*
$url 请求的url
$type 请求类型
$res 返回数据类型
$arr post请求参数
*/
$ch=curl_init();
/*$url='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET'; */
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
if($type=='post'){
curl_setopt($ch,CURLOPT_POST,1);
curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
}
$output = curl_exec($ch);
curl_close($ch);
if($res=='json'){
return json_decode($output,true);
}
}
function send(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=SECRET";
$urlgetcon = file_get_contents($url);
$usera = json_decode($urlgetcon, TRUE);
$token = $usera['access_token'];
$posturl = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$token;
$openid = '获取用户openid';
$dt = array(
"touser" => $openid,
'template_id' => '模板id',
'url' => "点击跳转URL",
'data' => array(
'first' =>array('value' => '您好,您寄卖的券出现纠纷!'),
'keyword1' =>array('value' =>$quann ),
'keyword2' =>array('value' => date('Y-m-d H:i:s')),
'keyword3' =>array('value' => 'XX权益'),
'remark' =>array('value' => '感谢您对我们平台的支持!'),
),
);
$postjson = json_encode($dt);
$resder = $this->http_curl($posturl,'post','json',$postjson);
}
效果:
有啥问题可以直接评论哦