1 <?php
2 3 4
5
6 namespace PayPal\Handler;
7
8 use PayPal\Auth\OAuthTokenCredential;
9 use PayPal\Common\PayPalUserAgent;
10 use PayPal\Core\PayPalConstants;
11 use PayPal\Core\PayPalCredentialManager;
12 use PayPal\Core\PayPalHttpConfig;
13 use PayPal\Exception\PayPalConfigurationException;
14 use PayPal\Exception\PayPalInvalidCredentialException;
15 use PayPal\Exception\PayPalMissingCredentialException;
16
17 18 19
20 class RestHandler implements IPayPalHandler
21 {
22 23 24 25 26
27 private $apiContext;
28
29 30 31 32 33
34 public function __construct($apiContext)
35 {
36 $this->apiContext = $apiContext;
37 }
38
39 40 41 42 43 44 45 46 47
48 public function handle($httpConfig, $request, $options)
49 {
50 $credential = $this->apiContext->getCredential();
51 $config = $this->apiContext->getConfig();
52
53 if ($credential == null) {
54
55 $credMgr = PayPalCredentialManager::getInstance($config);
56 $credValues = $credMgr->getCredentialObject();
57
58 if (!is_array($credValues)) {
59 throw new PayPalMissingCredentialException("Empty or invalid credentials passed");
60 }
61
62 $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']);
63 }
64
65 if ($credential == null || !($credential instanceof OAuthTokenCredential)) {
66 throw new PayPalInvalidCredentialException("Invalid credentials passed");
67 }
68
69 $httpConfig->setUrl(
70 rtrim(trim($this->_getEndpoint($config)), '/') .
71 (isset($options['path']) ? $options['path'] : '')
72 );
73
74
75 $httpConfig->addHeader("Expect", null);
76
77 if (!array_key_exists("User-Agent", $httpConfig->getHeaders())) {
78 $httpConfig->addHeader("User-Agent", PayPalUserAgent::getValue(PayPalConstants::SDK_NAME, PayPalConstants::SDK_VERSION));
79 }
80
81 if (!is_null($credential) && $credential instanceof OAuthTokenCredential && is_null($httpConfig->getHeader('Authorization'))) {
82 $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config), false);
83 }
84
85 if (($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') && !is_null($this->apiContext->getRequestId())) {
86 $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId());
87 }
88
89 $headers = $this->apiContext->getRequestHeaders();
90 foreach ($headers as $key => $value) {
91 $httpConfig->addHeader($key, $value);
92 }
93 }
94
95 96 97 98 99 100 101 102
103 private function _getEndpoint($config)
104 {
105 if (isset($config['service.EndPoint'])) {
106 return $config['service.EndPoint'];
107 } elseif (isset($config['mode'])) {
108 switch (strtoupper($config['mode'])) {
109 case 'SANDBOX':
110 return PayPalConstants::REST_SANDBOX_ENDPOINT;
111 break;
112 case 'LIVE':
113 return PayPalConstants::REST_LIVE_ENDPOINT;
114 break;
115 default:
116 throw new PayPalConfigurationException('The mode config parameter must be set to either sandbox/live');
117 break;
118 }
119 } else {
120
121 return PayPalConstants::REST_SANDBOX_ENDPOINT;
122 }
123 }
124 }
125