定义一个class
class WeixinUtil{
private $appId = '你自己的appid';
private $appSecret = '你自己的appSecret';
//获取AccessToken
public function getAccessToken(){
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->$appId."&secret=".$this->$appSecret;
$ch = curl_init();//初始化curl
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); // 从证书中检查SSL加密算法是否存在
$data = json_decode(curl_exec($ch));
if(curl_errno($ch)){
echo "错误";
var_dump(curl_error($ch)); //若错误打印错误信息
}
$token = $data->access_token;
curl_close($ch);//关闭curl
return $token;
}
//将模板消息json格式化
function json_tempalte($Openid,$SysName,$PRid,$Status,$NestStatus,$SysUrl,$Phone){
//模板消息
$template=array(
'touser'=>"$Openid", //用户openid
'template_id'=>"lwWjYvPc-hVSL77VKARhdxB5cUGCVm_A-39nqXxU_RE", //模板id
'url'=>"$SysUrl", //点击模板消息会跳转的链接
'data'=>array(
//根据你模板里的参数来设置
'SysName'=>array('value'=>"$SysName",'color'=>"#FF0000"),
'PRid'=>array('value'=>"$PRid",'color'=>"#FF0000"),
'Status'=>array('value'=>"$Status",'color'=>'#FF0000'),
'NestStatus'=>array('value'=>"$NestStatus",'color'=>'#FF0000'),
'SysUrl'=>array('value'=>"$SysUrl",'color'=>"#FF0000"),
'Phone'=>array('value'=>"$Phone",'color'=>'#FF0000')
)
);
$json_template=json_encode($template);//转json格式
return $json_template;
}
/* 发送json格式的数据,到api接口 -xzz0704 */
function https_curl_json($url,$data){
$headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
$output = curl_exec($curl);
if (curl_errno($curl)) {
echo 'Errno'.curl_error($curl);//捕抓异常
}
curl_close($curl);
return $output;
}
}
实例化后调用方法
测试类如下:
<?php
$wx = new WeixinUtil();
//传入的参数
$Openid = "o9AQd1PtsBnKIYaqExcYQL-vTTfY";
$tpUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$wx->getAccessToken();
$SysName = "测试系统名称";
$PRid = "测试单号18000005";
//$Status ="提交";
$Status ="部门审批";
$NestStatus = " ";
//$NestStatus = "可以开始审批";
$SysUrl = "http://www.baidu.com/";
$Phone = "手机22222";
$json = $wx->json_tempalte($Openid,$SysName,$PRid,$Status,$NestStatus,$SysUrl,$Phone);
$out = $wx->https_curl_json($tpUrl,$json);//进行传输
//输出{"errcode":0,"errmsg":"ok","msgid":426091918049738752}表示成功 ps:msgid每个人不一样
echo $out;
?>
这里用到的只是静态数据,动态数据请根据自己的业务需求来
代码有点冗余,请各位自行优化