/**
* 通过 appid ,appsecret 获取 access_token
*/
function access_token($appid, $appsecret)
{
$token = Db::name('wx_user')->where(array('appid' => $appid, 'appsecret' => $appsecret))->find();
if (!$token) {
//不存在
$insert_data = [
'appid' => $appid,
'appsecret' => $appsecret
];
Db::name('wx_user')->insert($insert_data);
$token = Db::name('wx_user')->where(array('appid' => $appid, 'appsecret' => $appsecret))->find();
}
$appid = $token['appid'];
$appsecret = $token['appsecret'];
//判断是否过了缓存期
$expire_time = $token['web_expires'];
if ($expire_time > time()) {
return $token['web_access_token'];
}
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
$return = httpRequest($url, 'GET');
$return = json_decode($return, 1);
$web_expires = time() + 7140; // 提前60秒过期
if ($return['access_token']) {
Db::name('wx_user')->where(array('appid' => $appid, 'appsecret' => $appsecret))->update(array('web_access_token' => $return['access_token'], 'web_expires' => $web_expires));
}
return $return['access_token'];
}
调用的其他方法:
httpRequest()