123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- <?php
- namespace App\Service;
- use App\Log;
- use App\RedisModel;
- use App\Support\DouYinApi;
- class AccessTokenService
- {
- const ACCESS_TOKEN_RDS = 'DouApp::AccessTokenBySecret_';
- const ACCESS_TOKEN_REQUEST_LOCK = 'DouApp::AccessTokenRequestLockRds_';
- /**
- * 获取代开发应用AccessToken
- * */
- public static function getAccessToken($appid, $from='')
- {
- $accessTokenStr = RedisModel::get(AccessTokenService::ACCESS_TOKEN_RDS. '_' .$appid);
- Log::logInfo('【'.$appid.'】Redis取出的结果为'.$accessTokenStr, [], 'GetAccessTokenTrace');
- if(!empty($accessTokenStr)) {
- Log::logInfo('【'.$appid.'】发现了结果,开始解析:'.$accessTokenStr, [], 'GetAccessTokenTrace');
- $accessTokenData = json_decode($accessTokenStr, true);
- $accessToken = $accessTokenData['access_token'] ?? '';
- $expire = $accessTokenData['expire'];
- $updateTime = isset($accessTokenData['update_time']) ? $accessTokenData['update_time'] : 0;
- if($expire <= time() || empty($accessToken) || $updateTime < time()) {
- self::refreshAccessToken($appid, $accessToken, $from);
- }
- } else {
- $accessToken = '';
- Log::logInfo('【'.$appid.'】没有找到AccessToken,开始生成', [], 'GetAccessTokenTrace');
- self::refreshAccessToken($appid, $accessToken, $from);
- }
- Log::logInfo('【'.$appid.'】本次返回的AccessToken为' . $accessToken, [], 'GetAccessTokenTrace');
- return $accessToken;
- }
- /**
- * 调用接口刷新AccessToken
- * @param string $appid
- * @param string $accessToken 当前缓存的access_token,更新成功后会返回新access_token
- * @param string $from 获取令牌的方法说明
- * @param int $retry 重试次数
- * */
- public static function refreshAccessToken($appid,&$accessToken, $from='',$retry=0)
- {
- $responseData = DouYinApi::getClientToken($appid);
- $accessToken = $responseData['access_token'] ?? '';
- $saveData = [
- 'access_token' => $accessToken,
- 'expire' => $responseData['expires_in'] + time(),
- 'update_time' => time() + 3600
- ];
- # 将accessToken存入Redis
- $redisKey = AccessTokenService::ACCESS_TOKEN_RDS. '_' .$appid;
- RedisModel::set($redisKey, json_encode($saveData));
- RedisModel::expire($redisKey, 7200);
- Log::logError('Redis KEY值为:', [
- 'key' => $redisKey,
- 'value' => $accessToken,
- 'apppid' => $appid
- ], 'refreshAccessTokenSave');
- return 0;
- }
- }
|