public function get_wx_access_token()
{
//将access_token存在session/cookie中
//如果access_token在session中并没有过期
if (isset($_SESSION['access_token']) && $_SESSION['expire_time'] > time()) {
return $_SESSION['access_token'];
}
//如果access_token不存在或者已经过期,重新获取access_token
else {
//$appid = 'wx5486430ceb12f84a';
// $appsecret = 'f52859525c6b799636d78bb49af14513';
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $this->appid . "&secret=" . $this->appsecret;
$arr = $this->http_curl($url);
//存到session中
$access_token = $arr['access_token'];
$_SESSION['access_token'] = $arr['access_token'];
$_SESSION['expire_time'] = time() + 7200;
return $access_token;
}
}
protected function http_curl($url, $arr = '', $type = 'get', $res = 'json')
{
$ch = curl_init();
//设置curl的参数
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
if ($type == 'post') {
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
}
//采集
$output = curl_exec($ch);
if ($res == 'json') {
if ($err = curl_errno($ch)) {
//要在关闭之前获得curl_errno
curl_close($ch);
//请求失败,返回错误信息
return $err;
} else {
//请求成功
return json_decode($output, true);
}
}
}