1 <?php
2 3 4
5
6 namespace PayPal\Handler;
7
8 use PayPal\Common\PayPalUserAgent;
9 use PayPal\Core\PayPalConstants;
10 use PayPal\Core\PayPalHttpConfig;
11 use PayPal\Exception\PayPalConfigurationException;
12 use PayPal\Exception\PayPalInvalidCredentialException;
13 use PayPal\Exception\PayPalMissingCredentialException;
14
15 16 17
18 class OauthHandler implements IPayPalHandler
19 {
20 21 22 23 24
25 private $apiContext;
26
27 28 29 30 31
32 public function __construct($apiContext)
33 {
34 $this->apiContext = $apiContext;
35 }
36
37 38 39 40 41 42 43 44 45
46 public function handle($httpConfig, $request, $options)
47 {
48 $config = $this->apiContext->getConfig();
49
50 $httpConfig->setUrl(
51 rtrim(trim($this->_getEndpoint($config)), '/') .
52 (isset($options['path']) ? $options['path'] : '')
53 );
54
55 $headers = array(
56 "User-Agent" => PayPalUserAgent::getValue(PayPalConstants::SDK_NAME, PayPalConstants::SDK_VERSION),
57 "Authorization" => "Basic " . base64_encode($options['clientId'] . ":" . $options['clientSecret']),
58 "Accept" => "*/*"
59 );
60 $httpConfig->setHeaders($headers);
61
62
63 $headers = $this->apiContext->getRequestHeaders();
64 foreach ($headers as $key => $value) {
65 $httpConfig->addHeader($key, $value);
66 }
67 }
68
69 70 71 72 73 74 75 76
77 private static function _getEndpoint($config)
78 {
79 if (isset($config['oauth.EndPoint'])) {
80 $baseEndpoint = $config['oauth.EndPoint'];
81 } elseif (isset($config['service.EndPoint'])) {
82 $baseEndpoint = $config['service.EndPoint'];
83 } elseif (isset($config['mode'])) {
84 switch (strtoupper($config['mode'])) {
85 case 'SANDBOX':
86 $baseEndpoint = PayPalConstants::REST_SANDBOX_ENDPOINT;
87 break;
88 case 'LIVE':
89 $baseEndpoint = PayPalConstants::REST_LIVE_ENDPOINT;
90 break;
91 default:
92 throw new PayPalConfigurationException('The mode config parameter must be set to either sandbox/live');
93 }
94 } else {
95
96 $baseEndpoint = PayPalConstants::REST_SANDBOX_ENDPOINT;
97 }
98
99 $baseEndpoint = rtrim(trim($baseEndpoint), '/') . "/v1/oauth2/token";
100
101 return $baseEndpoint;
102 }
103 }
104