You are here

protected function CheckoutSdkFactory::getClient in Commerce PayPal 8

Gets a preconfigured HTTP client instance for use by the SDK.

Parameters

array $config: The config for the client.

Return value

\GuzzleHttp\Client The API client.

1 call to CheckoutSdkFactory::getClient()
CheckoutSdkFactory::get in src/CheckoutSdkFactory.php
Retrieves the PayPal Checkout SDK for the given config.

File

src/CheckoutSdkFactory.php, line 125

Class

CheckoutSdkFactory
Defines a factory for our custom PayPal checkout SDK.

Namespace

Drupal\commerce_paypal

Code

protected function getClient(array $config) {
  switch ($config['mode']) {
    case 'live':
      $base_uri = 'https://api.paypal.com';
      break;
    case 'test':
    default:
      $base_uri = 'https://api.sandbox.paypal.com';
      break;
  }
  $attribution_id = isset($config['payment_solution']) && $config['payment_solution'] == 'custom_card_fields' ? 'Centarro_Commerce_PCP' : 'CommerceGuys_Cart_SPB';
  $options = [
    'base_uri' => $base_uri,
    'headers' => [
      'PayPal-Partner-Attribution-Id' => $attribution_id,
    ],
  ];
  $client = $this->clientFactory
    ->fromOptions($options);

  // Generates a key for storing the OAuth2 token retrieved from PayPal.
  // This is useful in case multiple PayPal checkout gateway instances are
  // configured.
  $token_key = 'commerce_paypal.oauth2_token.' . md5($config['client_id'] . $config['secret']);
  $config = [
    ClientCredentials::CONFIG_CLIENT_ID => $config['client_id'],
    ClientCredentials::CONFIG_CLIENT_SECRET => $config['secret'],
    ClientCredentials::CONFIG_TOKEN_URL => '/v1/oauth2/token',
    'token_key' => $token_key,
  ];
  $grant_type = new ClientCredentials($client, $config, $this->state);
  $middleware = new OAuthMiddleware($client, $grant_type);

  // Check if we've already requested an OAuth2 token, note that we do not
  // need to check for the expires timestamp here as the middleware is already
  // taking care of that.
  $token = $this->state
    ->get($token_key);
  if (!empty($token)) {
    $middleware
      ->setAccessToken($token['token'], 'client_credentials', $token['expires']);
  }
  $this->stack
    ->push($middleware
    ->onBefore());
  $this->stack
    ->push($middleware
    ->onFailure(2));
  $options['handler'] = $this->stack;
  $options['auth'] = 'oauth2';
  return $this->clientFactory
    ->fromOptions($options);
}