AppTokenManager.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Helpers\Utils;
  4. use App\Services\CallApiService;
  5. use Closure;
  6. use Illuminate\Http\Request;
  7. class AppTokenManager
  8. {
  9. /**
  10. * Handle an incoming request.
  11. *
  12. * @param \Illuminate\Http\Request $request
  13. * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
  14. * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
  15. */
  16. public function handle(Request $request, Closure $next)
  17. {
  18. if (request()->has('bpa')) {
  19. $bpa = Utils::bpaDecoding($request->get('bpa'));
  20. $mainAppId = $bpa['main_app_id'];
  21. $guestAppId = $bpa['guest_app_id'];
  22. view()->share('mainAppName', $this->appNameFor($mainAppId));
  23. view()->share('guestAppName', $this->appNameFor($guestAppId));
  24. $appGuestPage = $this->getAppGuestPage($mainAppId, $guestAppId);
  25. // dd($appGuestPage);
  26. foreach ($appGuestPage['Page'] ?? [] as $appGuest) {
  27. $appName = $appGuest['AppName'];
  28. if (session()->has("GateToken.$appName")) { continue; }
  29. if ($response = $this->getAppGateToken($appGuest['ApiUri'], $appGuest['AppBase64'])) {
  30. session()->put("GateToken.$appName", $response);
  31. }
  32. }
  33. }
  34. return $next($request);
  35. }
  36. public function appNameFor($appId)
  37. {
  38. if (empty($appId)) { return null; }
  39. return app(CallApiService::class)->callApi([
  40. 'url' => 'app-guest-page',
  41. 'data' => [
  42. 'PageVars' => [
  43. 'Query' => "(id = $appId) and is_on_use = 1",
  44. 'Limit' => 2,
  45. ]
  46. ]
  47. ])['Page'][0]['AppName'];
  48. }
  49. public function getAppGateToken($apiUri, $appBase64)
  50. {
  51. $response = \Unirest\Request::post(
  52. $apiUri . '/gate-token-get',
  53. [ 'Accept' => 'application/json' ],
  54. [ 'AppBase64' => $appBase64 ]
  55. );
  56. if ($response->code == 200) {
  57. $data = json_encode($response->body ?? []);
  58. return json_decode($data, true);
  59. } else {
  60. return false;
  61. }
  62. }
  63. public function getAppGuestPage($mainAppId, $guestAppId)
  64. {
  65. return app(CallApiService::class)->callApi([
  66. 'url' => 'app-guest-page',
  67. 'data' => [
  68. 'PageVars' => [
  69. 'Query' => "(id = $mainAppId or id = $guestAppId) and is_on_use = 1",
  70. 'Limit' => 2,
  71. ]
  72. ]
  73. ]);
  74. }
  75. }