2 namespace PayPal\Rest;
\r
4 use PayPal\Auth\OAuthTokenCredential;
\r
5 use PayPal\Handler\IPPHandler;
\r
6 use PayPal\Core\PPCredentialManager;
\r
7 use PayPal\Core\PPConstants;
\r
8 use PayPal\Exception\PPMissingCredentialException;
\r
9 use PayPal\Exception\PPInvalidCredentialException;
\r
10 use PayPal\Exception\PPConfigurationException;
\r
11 use PayPal\Common\PPUserAgent;
\r
15 * API handler for all REST API calls
\r
17 class RestHandler implements IPPHandler {
\r
19 private $apiContext;
\r
21 public static $sdkName = "rest-sdk-php";
\r
22 public static $sdkVersion = "0.6.0";
\r
24 public function __construct($apiContext) {
\r
25 $this->apiContext = $apiContext;
\r
28 public function handle($httpConfig, $request, $options) {
\r
30 $credential = $this->apiContext->getCredential();
\r
31 $config = $this->apiContext->getConfig();
\r
33 if($credential == NULL) {
\r
34 // Try picking credentials from the config file
\r
35 $credMgr = PPCredentialManager::getInstance($config);
\r
36 $credValues = $credMgr->getCredentialObject();
\r
37 if(!is_array($credValues)) {
\r
38 throw new PPMissingCredentialException("Empty or invalid credentials passed");
\r
40 $credential = new OAuthTokenCredential($credValues['clientId'], $credValues['clientSecret']);
\r
42 if($credential == NULL || ! ($credential instanceof OAuthTokenCredential) ) {
\r
43 throw new PPInvalidCredentialException("Invalid credentials passed");
\r
47 $httpConfig->setUrl(
\r
48 rtrim( trim($this->_getEndpoint($config)), '/') .
\r
49 (isset($options['path']) ? $options['path'] : '')
\r
52 if(!array_key_exists("User-Agent", $httpConfig->getHeaders())) {
\r
53 $httpConfig->addHeader("User-Agent", PPUserAgent::getValue(self::$sdkName, self::$sdkVersion));
\r
55 if(!is_null($credential) && $credential instanceof OAuthTokenCredential) {
\r
56 $httpConfig->addHeader('Authorization', "Bearer " . $credential->getAccessToken($config));
\r
58 if($httpConfig->getMethod() == 'POST' || $httpConfig->getMethod() == 'PUT') {
\r
59 $httpConfig->addHeader('PayPal-Request-Id', $this->apiContext->getRequestId());
\r
64 private function _getEndpoint($config) {
\r
65 if (isset($config['service.EndPoint'])) {
\r
66 return $config['service.EndPoint'];
\r
67 } else if (isset($config['mode'])) {
\r
68 switch (strtoupper($config['mode'])) {
\r
70 return PPConstants::REST_SANDBOX_ENDPOINT;
\r
73 return PPConstants::REST_LIVE_ENDPOINT;
\r
76 throw new PPConfigurationException('The mode config parameter must be set to either sandbox/live');
\r
80 throw new PPConfigurationException('You must set one of service.endpoint or mode parameters in your configuration');
\r