<?php
/**
*公众号发送模板消息
*这里只做单纯的功能测试,没有涉及任何业务逻辑
1 获取code
2 通过code获取openid
3 获取access_token,这是调用发消息模板接口必要的参数,这里的access_token和网页授权access_token不是同一个东西,不知道微信在搞什么
4 获取模板id,组装消息数据,调用发消息接口发送
5 在模版消息发送任务完成后,微信服务器会将是否送达成功作为通知,发送到开发者中心中填写的服务器配置地址中。//这一步我没有测试
官方文档地址:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1433751277
*/
//获取code临时凭证,然后微信服务器直接跳转回调地址
function getCode(){
$appid='wx74428abd61a8ddd7';
$r_url=urlEncode("http://engweb.uuudoo.com/Apk/sendMsg.php");//回调地址,这个回调地址需要在(公众平台->接口权限->网页授权获取用户基本信息->修改)处配置
$url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$r_url&response_type=code&scope=snsapi_base&state=1#wechat_redirect";
header("Location: $url");
}
//这里是回调以后会执行到的方法,用临时凭证code获取网页授权access_token,同时会返回openid
function getAccessToken(){
$code=$_GET['code'];
$appid='wx74428abd61a8ddd7';
$secret='feffe4641e6bde01e510d51d67b9883a';
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$secret&code=$code&grant_type=authorization_code";
return file_get_contents($url);
}
//获取接口调用凭证access_token
function getAccessToken_s(){
$appid='wx74428abd61a8ddd7';
$secret='feffe4641e6bde01e510d51d67b9883a';
$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
$access_token = file_get_contents($url);
return json_decode($access_token)->access_token;
}
//发送模板消息
function sendMsg($data){//这个方法里面的代码来源于百度复制,能否用于生产有待考究
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".ACCESS_TOKEN);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$tmpInfo = curl_exec($ch);
if (curl_errno($ch)) {
return curl_error($ch);
}
curl_close($ch);
return $tmpInfo;
}
if(empty($_GET['code'])){//获取code
getCode();
}else{
//获取openid
$result=getAccessToken();
$openid=json_decode($result)->openid;
//获取ACCESS_TOKEN
define("ACCESS_TOKEN", getAccessToken_s());
//模板数据,微信要的是json数据,我这里先构建数组再转成json
$data=array(
'touser'=>''.$openid,//要发送给的用户
'template_id'=>'0OlJsB-vb5s50UiRdXS2tKGUm_3NDk3XdWjmaHb1fSk',//模板id,从模板库中获取,可通过接口获取或直接从公众号后台复制
'url'=>'https://baidu.com',//用户点击通知后的跳转的地址,这里可以使用miniprogram来跳转到小程序
'data'=>array(
'first'=>array(
'value'=>'恭喜你购买成功',
'color'=>'#173177',
),
'keyword1'=>array(
'value'=>'产品名称',
'color'=>'#173177',
),
'keyword2'=>array(
'value'=>'订单号',
'color'=>'#173177',
),
'keyword3'=>array(
'value'=>'订单价格',
'color'=>'#173177',
),
'keyword4'=>array(
'value'=>'订购时间',
'color'=>'#173177',
),
'remark'=>array(
'value'=>'欢迎再次购买!',
'color'=>'#173177',
)
)
);
//发送模板消息
sendMsg(json_encode($data));
echo "<script>alert('模板消息已发送');</script>";
}
?>