使用laravel框架开发微信公众平台,获取Access token

管理员

参考文档:https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html

access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效
接口说明

代码如下:

$httpClient = new Client([
  'timeout' => 2.0,
  'base_uri' => 'https://api.weixin.qq.com/',
]);

$options = ['query' => [
  'grant_type' => 'client_credential',
  'appid' => config('wechat.official_account.default.app_id'),
  'secret' => config('wechat.official_account.default.secret'),
]];

$response = $httpClient->request('GET', 'cgi-bin/token', $options);

$result = json_decode($response->getBody()->getContents(), true);
dd($result);

返回结果:

array:2 [▼
  "access_token" => "45_GqtMYPbje4pQf8hrypX5V2ie-29fWr5WlPFpVvv06ikw55DK0a9W_3WJffT77Q2UknrkEJoqzgigohEu3lkfhLge-TcTymcZeVlE1ZE74wcHyvUAs-DUpMgo9B8IjLFxdEhtM590J3yZuh3FATGbAIAFYL"
  "expires_in" => 7200
]

由于access_token的有效期为2个小时,并且每天都有获取次数限制。
将access_token存入缓存

$cacheKey = 'test_access_token';
Cache::put($cacheKey, [
    'access_token' => $result['access_token'],
    'expires_in' => $result['expires_in'],
], 60);//缓存1分钟,方便测试

在获取access_token时候,增加验证是否存在缓存
获取access_token完整代码:

$cacheKey = 'test_access_token';

if (Cache::has($cacheKey) && $result = Cache::get($cacheKey)) {
   return $result;
}

$httpClient = new Client([
    'timeout' => 2.0,
    'base_uri' => 'https://api.weixin.qq.com/',
]);

$options = ['query' => [
   'grant_type' => 'client_credential',
   'appid' => config('wechat.official_account.default.app_id'),
   'secret' => config('wechat.official_account.default.secret'),
]];

$response = $httpClient->request('GET', 'cgi-bin/token', $options);

$result = json_decode($response->getBody()->getContents(), true);

Cache::put($cacheKey, [
   'access_token' => $result['access_token'],
   'expires_in' => $result['expires_in'],
], 60);//缓存1分钟,方便测试

if (!Cache::get($cacheKey)) {
   throw new \Exception('Failed to cache access token.');
}
        
        
return $result;
1人点赞
微信开发
管理员

全部评论 0