ClientTokenManage.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 ClientTokenManage extends Command
  8. {
  9. /**
  10. * @var string
  11. */
  12. protected $signature = 'tiktok:clientToken:refresh';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = '抖音client 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, 'client_token_expires_at');
  49. // token到期前10分钟开始更新
  50. if (strtotime($tokenExpiresAt) - time() > 600) {
  51. continue;
  52. }
  53. // 实例化并获取token
  54. $tokenData = $this->openService->getOpenInstance([
  55. 'app_id' => getProp($app, 'app_id'),
  56. 'secret' => getProp($app, 'app_secret'),
  57. ])->getClientToken(true);
  58. if ($tokenData) {
  59. // 更新数据库
  60. $seconds = (int)getProp($tokenData, 'expires_in');
  61. $this->accountDao->updateMiniApp(['id' => getProp($app, 'id')], [
  62. 'client_token' => getProp($tokenData, 'access_token'),
  63. 'client_token_expires_at' => date('Y-m-d H:i:s', strtotime("+ $seconds second")),
  64. ]);
  65. }
  66. }
  67. }
  68. }