PayPalHttpClient.php
54 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\PaymentGateways\PayPalCommerce\PayPalCheckoutSdk; |
| 4 | |
| 5 | use Give\PaymentGateways\PayPalCommerce\Models\MerchantDetail; |
| 6 | use PayPalCheckoutSdk\Core\FPTIInstrumentationInjector; |
| 7 | use PayPalCheckoutSdk\Core\GzipInjector; |
| 8 | use PayPalCheckoutSdk\Core\PayPalEnvironment; |
| 9 | |
| 10 | /** |
| 11 | * Class PayPalHttpClient. |
| 12 | * |
| 13 | * This class extends PayPalCheckoutSdk\Core\PayPalHttpClient class. |
| 14 | * PayPalHttpClient from php sdk force access token refresh on each http request. |
| 15 | * We register AuthorizationInjector class to inject access token in http request header. |
| 16 | * AuthorizationInjector clas refresh access token only if expired. |
| 17 | * |
| 18 | * @since 2.25.0 |
| 19 | */ |
| 20 | class PayPalHttpClient extends \PayPalCheckoutSdk\Core\PayPalHttpClient |
| 21 | { |
| 22 | /** |
| 23 | * Class constructor. |
| 24 | * |
| 25 | * @since 2.25.0 |
| 26 | */ |
| 27 | public function __construct(PayPalEnvironment $environment, $refreshToken = null) |
| 28 | { |
| 29 | parent::__construct($environment); |
| 30 | $this->authInjector = $this->getAuthorizationInjector($environment, $refreshToken); |
| 31 | $this->addInjector($this->authInjector); |
| 32 | $this->addInjector(new GzipInjector()); |
| 33 | $this->addInjector(new FPTIInstrumentationInjector()); |
| 34 | } |
| 35 | |
| 36 | /** |
| 37 | * Returns AuthorizationInjector. |
| 38 | * |
| 39 | * @since 2.25.0 |
| 40 | */ |
| 41 | private function getAuthorizationInjector($environment, $refreshToken): AuthorizationInjector |
| 42 | { |
| 43 | $merchant = give(MerchantDetail::class); |
| 44 | $authorizationInjector = new AuthorizationInjector($this, $environment, $refreshToken); |
| 45 | |
| 46 | // Set access token if exists. |
| 47 | if ($merchant->accessToken) { |
| 48 | $authorizationInjector->accessToken = $merchant->toArray()['token']; |
| 49 | } |
| 50 | |
| 51 | return $authorizationInjector; |
| 52 | } |
| 53 | } |
| 54 |