|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Diimolabs\Oauth2Client; |
| 4 | + |
| 5 | +use Illuminate\Support\Facades\Http; |
| 6 | +use Illuminate\Support\Facades\Storage; |
| 7 | + |
| 8 | +class OAuthHttpClient |
| 9 | +{ |
| 10 | + private static $path; |
| 11 | + |
| 12 | + private static $host; |
| 13 | + |
| 14 | + private static $clientId; |
| 15 | + |
| 16 | + private static $clientSecret; |
| 17 | + |
| 18 | + private static function getCredentialsInfo() { |
| 19 | + return collect(json_decode( |
| 20 | + file_get_contents(self::$path) |
| 21 | + )); |
| 22 | + } |
| 23 | + |
| 24 | + private static function requestToken() { |
| 25 | + $response = Http::acceptJson() |
| 26 | + ->post(self::$host . '/oauth/token', [ |
| 27 | + 'grant_type' => 'client_credentials', |
| 28 | + 'client_id' => self::$clientId, |
| 29 | + 'client_secret' => self::$clientSecret, |
| 30 | + ]); |
| 31 | + |
| 32 | + if($response->failed()){ |
| 33 | + abort(403); |
| 34 | + } |
| 35 | + |
| 36 | + Storage::put('oauth-credentials.json.key', $response->body()); |
| 37 | + } |
| 38 | + |
| 39 | + private static function validateToken() { |
| 40 | + // check if exist file with token |
| 41 | + if(!file_exists(self::$path)){ |
| 42 | + self::requestToken(); |
| 43 | + } |
| 44 | + |
| 45 | + $data = self::getCredentialsInfo(); |
| 46 | + |
| 47 | + $expiredDate = now()->parse(date("Y-m-d H:i:s", $data['expires_in'])); |
| 48 | + |
| 49 | + if(now()->lt($expiredDate)){ |
| 50 | + self::requestToken(); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + private static function getAuthorizationToken() { |
| 55 | + self::validateToken(); |
| 56 | + |
| 57 | + return self::getCredentialsInfo()['access_token']; |
| 58 | + } |
| 59 | + |
| 60 | + private static function getOauthAuthorization(){ |
| 61 | + return [ |
| 62 | + 'Authorization' => 'Bearer ' . self::getAuthorizationToken() |
| 63 | + ]; |
| 64 | + } |
| 65 | + |
| 66 | + public static function oauthRequest() { |
| 67 | + self::$path = storage_path('app/oauth-credentials.json.key'); |
| 68 | + self::$host = config('oauth-client.host'); |
| 69 | + self::$clientId = config('oauth-client.client_id'); |
| 70 | + self::$clientSecret = config('oauth-client.client_secret'); |
| 71 | + |
| 72 | + info(self::$path); |
| 73 | + return Http::withHeaders( |
| 74 | + self::getOauthAuthorization() |
| 75 | + ); |
| 76 | + } |
| 77 | +} |
0 commit comments