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