1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980 |
- <?php
- namespace App\Console\TikTok;
- use App\Dao\Account\AccountDao;
- use App\Services\OpenApi\OpenService;
- use App\Libs\TikTok\Kernel\Exceptions;
- use Illuminate\Console\Command;
- class AccessTokenManage extends Command
- {
- /**
- * @var string
- */
- protected $signature = 'tiktok:accessToken:refresh';
- /**
- * The console command description.
- *
- * @var string
- */
- protected $description = '抖音access token刷新管理';
- private $accountDao;
- private $openService;
- public function __construct(
- AccountDao $accountDao,
- OpenService $openService
- )
- {
- parent::__construct();
- $this->accountDao = $accountDao;
- $this->openService = $openService;
- }
- /**
- * @return void
- * @throws Exceptions\HttpException
- * @throws Exceptions\InvalidArgumentException
- * @throws Exceptions\InvalidConfigException
- * @throws Exceptions\RuntimeException
- * @throws \GuzzleHttp\Exception\GuzzleException
- * @throws \Psr\SimpleCache\InvalidArgumentException
- */
- public function handle()
- {
- // 获取所有小程序
- $apps = $this->accountDao->getMiniApps();
- if (empty($apps)) {
- return;
- }
- foreach ($apps as $app) {
- // 数据库记录的token到期时间
- $tokenExpiresAt = getProp($app, 'access_token_expires_at');
- // token到期前10分钟开始更新
- if (strtotime($tokenExpiresAt) - time() > 600) {
- continue;
- }
- // 实例化并获取token
- $tokenData = $this->openService->getInstance([
- 'app_id' => getProp($app, 'app_id'),
- 'secret' => getProp($app, 'app_secret'),
- 'sandbox' => (bool)getProp($app, 'is_sandbox'),
- ])->getAccessToken(true);
- if ($tokenData) {
- // 更新数据库
- $seconds = (int)getProp($tokenData, 'expires_in');
- $this->accountDao->updateMiniApp(['id' => getProp($app, 'id')], [
- 'access_token' => getProp($tokenData, 'access_token'),
- 'access_token_expires_at' => date('Y-m-d H:i:s', strtotime("+ $seconds second")),
- ]);
- }
- }
- }
- }
|