<?php
/**
* User: Eden
* Date: 2019/3/21
* 共有内容
*/
namespace CommonService;
use VendorFuncHttp;
class AccessTokenService extends CommonService
{
public function __construct()
{
parent::__construct();
}
/**
* 获取access_token
* 小程序的appid,secret
* 或者
* 公众号的appid,secret 公众号获取access_token需要配置ip白名单
*/
public function get_access_token($app_id, $app_secret)
{
// 查询缓存中是否存在
$key = "access_token_" . $app_id;
$ttl = $this->red->ttl($key);
if ($ttl == -2) { // 不存在
// step1 获取
$request_url = "https://api.weixin.qq.com/cgi-bin/token?";
$request_url .= "grant_type=client_credential&appid=" . $app_id . "&secret=" . $app_secret;
$data = json_decode(Http::doGet($request_url, 5), true);
// step2 存储
$this->red->setex($key, $data['expires_in'] - 1000, $data['access_token']);
return $data['access_token'];
} else {
return $this->red->get($key);
}
}
}