WechatAccessToken.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace App\Console\Commands\Miniprogram;
  3. use App\Service\Miniprogram\Wechat\AccessTokenService;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Redis;
  7. class WechatAccessToken extends Command
  8. {
  9. /**
  10. * The name and signature of the console command.
  11. *
  12. * @var string
  13. */
  14. protected $signature = 'Miniprogram:WechatAccessToken {--appid= : 小程序appid} {--secret= : 小程序secret}';
  15. /**
  16. * The console command description.
  17. *
  18. * @var string
  19. */
  20. protected $description = '微信小程序维护';
  21. /**
  22. * Execute the console command.
  23. */
  24. public function handle()
  25. {
  26. $appid = $this->option('appid');
  27. $secret = $this->option('secret');
  28. if($appid && $secret) {
  29. $miniprograms = [(object)[
  30. 'appid' => $appid, 'appsecret' => $secret
  31. ]];
  32. } else {
  33. $miniprograms = DB::table('miniprogram')
  34. ->where(['type' => 1, 'status' => 1])
  35. ->select('appid', 'appsecret')
  36. ->get();
  37. }
  38. foreach ($miniprograms as $miniprogram) {
  39. $ttl = Redis::ttl(AccessTokenService::getAccessTokenRedisKey($miniprogram->appid));
  40. if($ttl > 600) {
  41. continue;
  42. }
  43. try {
  44. $accessTokenInfo = AccessTokenService::getAccessToken($miniprogram->appid, $miniprogram->appsecret);
  45. } catch (\Exception $exception) {
  46. myLog('wechat-miniprogram')->info('刷新小程序accessToken失败', [
  47. 'appid' => $miniprogram->appid,
  48. 'exceptionMessage' => $exception->getMessage(),
  49. 'exceptionCode' => $exception->getCode()
  50. ]);
  51. continue;
  52. }
  53. Redis::setex(AccessTokenService::getAccessTokenRedisKey($miniprogram->appid),
  54. $accessTokenInfo['expires_in'], $accessTokenInfo['access_token']);
  55. }
  56. }
  57. }