<?php
function curlhttp($url, $data){
$ch = curl_init();
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);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
//moban
function moban($plan,$user,$time,$desc,$openid) {
//使用前请 修改以下3个参数
$appid="wxce3b9bd********c"; //appid
$appsecret="2efaac3bb2********af177683866f69"; //appsecret
$template_id = "9qUKfOTQ********sQBlMxLqoV2xvIH7Kl1iRUySYfI";
$filetoka = "toka.txt";
$daysnows = date('Y-m-d H:i:s');
$daysides = date('YmdHis');
if(file_exists($filetoka)){
$ttimes = filemtime($filetoka);
$ftimes = date('Y-m-d H:i:s', $ttimes);
}else{
$ftimes = date("Y-m-d H:i:s",strtotime("-1 day"));
}
echo "<b>ktime</b>$ftimes";
$tiold=strtotime($ftimes);
$tinew=strtotime($daysnows);
$seyu=floor($tinew-$tiold);
if($seyu<600){ //60=1分钟
$ACCESS_TOKEN = file_get_contents($filetoka);
echo "cache token = '{$ACCESS_TOKEN}@{$ftimes}';\r\n";
}else{
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential";
$url .= "&appid=$appid&secret=$appsecret";
$json = file_get_contents($url);
$result=json_decode($json,true);
$ACCESS_TOKEN=$result['access_token'];
if($ACCESS_TOKEN){
echo "news token = '{$ACCESS_TOKEN}@{$ftimes}';\r\n";
file_put_contents($filetoka,$ACCESS_TOKEN);
}else{
echo "kong token = '{$json}@{$ftimes}';\r\n"; //没有token
file_put_contents($filetoka.".toka.kong.txt",$json);
}
}
//模板消息 可修改
$template=array(
'touser'=>$openid,
'template_id'=>$template_id, //模板的id
'url'=>"http://add.12391.net/?d=".$daysides,
'topcolor'=>"#FF0000",
'data'=>array(
'first'=>array('value'=>urlencode($plan),'color'=>"#00008B"),
'keyword1'=>array('value'=>urlencode($user),'color'=>"#00008B"),
'keyword2'=>array('value'=>urlencode($time),'color'=>'#00008B'),
'remark'=>array('value'=>urlencode($desc),'color'=>'#00008B')
)
);
$json_template=json_encode($template);
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$ACCESS_TOKEN;
$res=curlhttp($url,urldecode($json_template));
$sms=json_decode($res,true);
$isok=$sms['errmsg'];
echo "<h3>json_template</h3>".$json_template;
if($isok == "ok"){
echo "<h3>fa ok</h3>".$res; //OK的返回值
}else{
echo "<h3>fa er</h3>".$res; //ER的返回值
unlink($filetoka); //尝试删除缓存token并记录
file_put_contents($filetoka.".back.erer.txt",$res);
}
}
/*
模板库找到模板添加
编号 OPENTM411626253
标题 服务到期提醒
行业 IT科技 - IT软件与服务
最后修改时间 2017-08-01 15:38:22
或者
添加的模板信息详细内容:
{{first.DATA}}
机构名称:{{keyword1.DATA}}
服务期限:{{keyword2.DATA}}
{{remark.DATA}}
*/
//plan user time userid 将以下内容修改特别别是最后个参数userid为自己公众号下存在的用户ID
moban("开头备注test","我自己","2019年12月12日","后续备注","olwyOwk28TMY-exD3omLVB3L6awg");
?>
使用注意:
1.使用前请 修改以3个参数详见中文名字
2.最后一行代码 最后个参数务必修改自己公众号下的userid测试可用管理员自己的
3.认证公众号后台添加模板见代码内汉字说明
4.二次修改自网络源码,增加token缓存与自动更新机制,完善说明书