抖音小程序

AccessTokenService.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. namespace App\Service;
  3. use App\Log;
  4. use App\RedisModel;
  5. use App\Support\DouYinApi;
  6. class AccessTokenService
  7. {
  8. const ACCESS_TOKEN_RDS = 'DouApp::AccessTokenBySecret_';
  9. const ACCESS_TOKEN_REQUEST_LOCK = 'DouApp::AccessTokenRequestLockRds_';
  10. /**
  11. * 获取代开发应用AccessToken
  12. * */
  13. public static function getAccessToken($appid, $from='')
  14. {
  15. $accessTokenStr = RedisModel::get(AccessTokenService::ACCESS_TOKEN_RDS. '_' .$appid);
  16. Log::logInfo('【'.$appid.'】Redis取出的结果为'.$accessTokenStr, [], 'GetAccessTokenTrace');
  17. if(!empty($accessTokenStr)) {
  18. Log::logInfo('【'.$appid.'】发现了结果,开始解析:'.$accessTokenStr, [], 'GetAccessTokenTrace');
  19. $accessTokenData = json_decode($accessTokenStr, true);
  20. $accessToken = $accessTokenData['access_token'] ?? '';
  21. $expire = $accessTokenData['expire'];
  22. $updateTime = isset($accessTokenData['update_time']) ? $accessTokenData['update_time'] : 0;
  23. if($expire <= time() || empty($accessToken) || $updateTime < time()) {
  24. self::refreshAccessToken($appid, $accessToken, $from);
  25. }
  26. } else {
  27. $accessToken = '';
  28. Log::logInfo('【'.$appid.'】没有找到AccessToken,开始生成', [], 'GetAccessTokenTrace');
  29. self::refreshAccessToken($appid, $accessToken, $from);
  30. }
  31. Log::logInfo('【'.$appid.'】本次返回的AccessToken为' . $accessToken, [], 'GetAccessTokenTrace');
  32. return $accessToken;
  33. }
  34. /**
  35. * 调用接口刷新AccessToken
  36. * @param string $appid
  37. * @param string $accessToken 当前缓存的access_token,更新成功后会返回新access_token
  38. * @param string $from 获取令牌的方法说明
  39. * @param int $retry 重试次数
  40. * */
  41. public static function refreshAccessToken($appid,&$accessToken, $from='',$retry=0)
  42. {
  43. $responseData = DouYinApi::getClientToken($appid);
  44. $accessToken = $responseData['access_token'] ?? '';
  45. $saveData = [
  46. 'access_token' => $accessToken,
  47. 'expire' => $responseData['expires_in'] + time(),
  48. 'update_time' => time() + 3600
  49. ];
  50. # 将accessToken存入Redis
  51. $redisKey = AccessTokenService::ACCESS_TOKEN_RDS. '_' .$appid;
  52. RedisModel::set($redisKey, json_encode($saveData));
  53. RedisModel::expire($redisKey, 7200);
  54. Log::logError('Redis KEY值为:', [
  55. 'key' => $redisKey,
  56. 'value' => $accessToken,
  57. 'apppid' => $appid
  58. ], 'refreshAccessTokenSave');
  59. return 0;
  60. }
  61. }