AccessTokenManage.php 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. <?php
  2. namespace App\Console\TikTok;
  3. use App\Dao\Account\AccountDao;
  4. use App\Services\OpenApi\OpenService;
  5. use App\Libs\TikTok\Kernel\Exceptions;
  6. use Illuminate\Console\Command;
  7. class AccessTokenManage extends Command
  8. {
  9. /**
  10. * @var string
  11. */
  12. protected $signature = 'tiktok:accessToken:refresh';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = '抖音access token刷新管理';
  19. private $accountDao;
  20. private $openService;
  21. public function __construct(
  22. AccountDao $accountDao,
  23. OpenService $openService
  24. )
  25. {
  26. parent::__construct();
  27. $this->accountDao = $accountDao;
  28. $this->openService = $openService;
  29. }
  30. /**
  31. * @return void
  32. * @throws Exceptions\HttpException
  33. * @throws Exceptions\InvalidArgumentException
  34. * @throws Exceptions\InvalidConfigException
  35. * @throws Exceptions\RuntimeException
  36. * @throws \GuzzleHttp\Exception\GuzzleException
  37. * @throws \Psr\SimpleCache\InvalidArgumentException
  38. */
  39. public function handle()
  40. {
  41. // 获取所有小程序
  42. $apps = $this->accountDao->getMiniApps();
  43. if (empty($apps)) {
  44. return;
  45. }
  46. foreach ($apps as $app) {
  47. // 数据库记录的token到期时间
  48. $tokenExpiresAt = getProp($app, 'access_token_expires_at');
  49. // token到期前10分钟开始更新
  50. if (strtotime($tokenExpiresAt) - time() > 600) {
  51. continue;
  52. }
  53. // 实例化并获取token
  54. $tokenData = $this->openService->getInstance([
  55. 'app_id' => getProp($app, 'app_id'),
  56. 'secret' => getProp($app, 'app_secret'),
  57. 'sandbox' => (bool)getProp($app, 'is_sandbox'),
  58. ])->getAccessToken(true);
  59. if ($tokenData) {
  60. // 更新数据库
  61. $seconds = (int)getProp($tokenData, 'expires_in');
  62. $this->accountDao->updateMiniApp(['id' => getProp($app, 'id')], [
  63. 'access_token' => getProp($tokenData, 'access_token'),
  64. 'access_token_expires_at' => date('Y-m-d H:i:s', strtotime("+ $seconds second")),
  65. ]);
  66. }
  67. }
  68. }
  69. }