WechatAccessToken.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. $accessTokenInfo = AccessTokenService::getAccessToken($miniprogram->appid, $miniprogram->appsecret);
  44. if(false === $accessTokenInfo || (0 != ($accessTokenInfo['errcode'] ?? 0))) {
  45. myLog('WechatAccessToken')->info('刷新小程序accessToken失败', [
  46. 'appid' => $miniprogram->appid,
  47. 'result' => $accessTokenInfo,
  48. ]);
  49. continue;
  50. }
  51. Redis::setex(AccessTokenService::getAccessTokenRedisKey($miniprogram->appid),
  52. $accessTokenInfo['expires_in'], $accessTokenInfo['access_token']);
  53. }
  54. }
  55. }