第一步,我们先封装好curl:
//封装curl
function http_curl($url, $type = 'get', $res = 'json', $arr = '') {
//初始化curl
$ch = curl_init();
//设置curl参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
if ($type == 'post') {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
}
//采集
$output = curl_exec($ch);
//关闭
//curl_close($ch);
if ($res == 'json') {
if (curl_errno($ch)) {
//请求失败,返回错误信息
return curl_error($ch);
} else {
//请求成功
return json_decode($output, true);
}
}
}
第二步,获取到token:
function getwxaccess_token(){
$appid = "xxxxxxxxxxx";
$secret = "xxxxxxxxxxxx";
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = json_decode(curl_exec($ch), true);
curl_close($ch);
return $res['access_token'];
}
第三步,开始调用封装好的模板下发:
// $toUser用户openid $template_id模板下发id $durl跳转地址 $data模板内容
function sendWxTampaleMsgUrl($touser, $template_id, $durl, $data) {
//1.获取微信access_token
$access_token = getwxaccess_token();
$url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $access_token;
//2.创建消息数组
$tamp = array(
'touser' => "{$touser}",
'template_id' => $template_id,
'url' => $durl,
'topcolor' => "#FF0000",
'data' => $data,
);
//3.转成json
$tampJson = urldecode(json_encode($tamp));
//4.请求接口
$res = http_curl($url, 'post', 'json', $tampJson);
return $res;
}
注意事项:
1. 方法为封装,可拿去调取;
2. TP框架需要加public及$this;
3. return返回数组报错可用return json($res);