Overview
  • Namespace
  • Class

Namespaces

  • PayPal
    • Api
    • Auth
    • Cache
    • Common
    • Converter
    • Core
    • Exception
    • Handler
    • Log
    • Rest
    • Security
    • Transport
    • Validation

Classes

  • PayPal\Api\Address
  • PayPal\Api\Agreement
  • PayPal\Api\AgreementDetails
  • PayPal\Api\AgreementStateDescriptor
  • PayPal\Api\AgreementTransaction
  • PayPal\Api\AgreementTransactions
  • PayPal\Api\AlternatePayment
  • PayPal\Api\Amount
  • PayPal\Api\Authorization
  • PayPal\Api\BankAccount
  • PayPal\Api\BankAccountsList
  • PayPal\Api\BankToken
  • PayPal\Api\BaseAddress
  • PayPal\Api\Billing
  • PayPal\Api\BillingAgreementToken
  • PayPal\Api\BillingInfo
  • PayPal\Api\CancelNotification
  • PayPal\Api\Capture
  • PayPal\Api\CarrierAccount
  • PayPal\Api\CarrierAccountToken
  • PayPal\Api\CartBase
  • PayPal\Api\ChargeModel
  • PayPal\Api\Cost
  • PayPal\Api\CountryCode
  • PayPal\Api\CreateProfileResponse
  • PayPal\Api\Credit
  • PayPal\Api\CreditCard
  • PayPal\Api\CreditCardHistory
  • PayPal\Api\CreditCardList
  • PayPal\Api\CreditCardToken
  • PayPal\Api\CreditFinancingOffered
  • PayPal\Api\Currency
  • PayPal\Api\CurrencyConversion
  • PayPal\Api\CustomAmount
  • PayPal\Api\DetailedRefund
  • PayPal\Api\Details
  • PayPal\Api\Error
  • PayPal\Api\ErrorDetails
  • PayPal\Api\ExtendedBankAccount
  • PayPal\Api\ExternalFunding
  • PayPal\Api\FileAttachment
  • PayPal\Api\FlowConfig
  • PayPal\Api\FmfDetails
  • PayPal\Api\FundingDetail
  • PayPal\Api\FundingInstrument
  • PayPal\Api\FundingOption
  • PayPal\Api\FundingSource
  • PayPal\Api\FuturePayment
  • PayPal\Api\HyperSchema
  • PayPal\Api\Image
  • PayPal\Api\Incentive
  • PayPal\Api\InputFields
  • PayPal\Api\InstallmentInfo
  • PayPal\Api\InstallmentOption
  • PayPal\Api\Invoice
  • PayPal\Api\InvoiceAddress
  • PayPal\Api\InvoiceItem
  • PayPal\Api\InvoiceNumber
  • PayPal\Api\InvoiceSearchResponse
  • PayPal\Api\Item
  • PayPal\Api\ItemList
  • PayPal\Api\Links
  • PayPal\Api\Measurement
  • PayPal\Api\MerchantInfo
  • PayPal\Api\MerchantPreferences
  • PayPal\Api\Metadata
  • PayPal\Api\NameValuePair
  • PayPal\Api\Notification
  • PayPal\Api\OpenIdAddress
  • PayPal\Api\OpenIdError
  • PayPal\Api\OpenIdSession
  • PayPal\Api\OpenIdTokeninfo
  • PayPal\Api\OpenIdUserinfo
  • PayPal\Api\Order
  • PayPal\Api\OverrideChargeModel
  • PayPal\Api\Participant
  • PayPal\Api\Patch
  • PayPal\Api\PatchRequest
  • PayPal\Api\Payee
  • PayPal\Api\Payer
  • PayPal\Api\PayerInfo
  • PayPal\Api\Payment
  • PayPal\Api\PaymentCard
  • PayPal\Api\PaymentCardToken
  • PayPal\Api\PaymentDefinition
  • PayPal\Api\PaymentDetail
  • PayPal\Api\PaymentExecution
  • PayPal\Api\PaymentHistory
  • PayPal\Api\PaymentInstruction
  • PayPal\Api\PaymentOptions
  • PayPal\Api\PaymentSummary
  • PayPal\Api\PaymentTerm
  • PayPal\Api\Payout
  • PayPal\Api\PayoutBatch
  • PayPal\Api\PayoutBatchHeader
  • PayPal\Api\PayoutItem
  • PayPal\Api\PayoutItemDetails
  • PayPal\Api\PayoutSenderBatchHeader
  • PayPal\Api\Phone
  • PayPal\Api\Plan
  • PayPal\Api\PlanList
  • PayPal\Api\PotentialPayerInfo
  • PayPal\Api\Presentation
  • PayPal\Api\PrivateLabelCard
  • PayPal\Api\ProcessorResponse
  • PayPal\Api\RecipientBankingInstruction
  • PayPal\Api\RedirectUrls
  • PayPal\Api\Refund
  • PayPal\Api\RefundDetail
  • PayPal\Api\RefundRequest
  • PayPal\Api\RelatedResources
  • PayPal\Api\Sale
  • PayPal\Api\Search
  • PayPal\Api\ShippingAddress
  • PayPal\Api\ShippingCost
  • PayPal\Api\ShippingInfo
  • PayPal\Api\Tax
  • PayPal\Api\Template
  • PayPal\Api\TemplateData
  • PayPal\Api\Templates
  • PayPal\Api\TemplateSettings
  • PayPal\Api\TemplateSettingsMetadata
  • PayPal\Api\Terms
  • PayPal\Api\Transaction
  • PayPal\Api\TransactionBase
  • PayPal\Api\Transactions
  • PayPal\Api\VerifyWebhookSignature
  • PayPal\Api\VerifyWebhookSignatureResponse
  • PayPal\Api\Webhook
  • PayPal\Api\WebhookEvent
  • PayPal\Api\WebhookEventList
  • PayPal\Api\WebhookEventType
  • PayPal\Api\WebhookEventTypeList
  • PayPal\Api\WebhookList
  • PayPal\Api\WebProfile
  • PayPal\Auth\OAuthTokenCredential
  • PayPal\Cache\AuthorizationCache
  • PayPal\Common\ArrayUtil
  • PayPal\Common\PayPalModel
  • PayPal\Common\PayPalResourceModel
  • PayPal\Common\PayPalUserAgent
  • PayPal\Common\ReflectionUtil
  • PayPal\Converter\FormatConverter
  • PayPal\Core\PayPalConfigManager
  • PayPal\Core\PayPalConstants
  • PayPal\Core\PayPalCredentialManager
  • PayPal\Core\PayPalHttpConfig
  • PayPal\Core\PayPalHttpConnection
  • PayPal\Core\PayPalLoggingManager
  • PayPal\Handler\OauthHandler
  • PayPal\Handler\RestHandler
  • PayPal\Log\PayPalDefaultLogFactory
  • PayPal\Log\PayPalLogger
  • PayPal\Rest\ApiContext
  • PayPal\Security\Cipher
  • PayPal\Transport\PayPalRestCall
  • PayPal\Validation\ArgumentValidator
  • PayPal\Validation\JsonValidator
  • PayPal\Validation\NumericValidator
  • PayPal\Validation\UrlValidator

Interfaces

  • PayPal\Handler\IPayPalHandler
  • PayPal\Log\PayPalLogFactory
  • PayPal\Rest\IResource

Exceptions

  • PayPal\Exception\PayPalConfigurationException
  • PayPal\Exception\PayPalConnectionException
  • PayPal\Exception\PayPalInvalidCredentialException
  • PayPal\Exception\PayPalMissingCredentialException
  1 <?php
  2 
  3 namespace PayPal\Core;
  4 
  5 use PayPal\Exception\PayPalConfigurationException;
  6 use PayPal\Exception\PayPalConnectionException;
  7 
  8 /**
  9  * A wrapper class based on the curl extension.
 10  * Requires the PHP curl module to be enabled.
 11  * See for full requirements the PHP manual: http://php.net/curl
 12  */
 13 class PayPalHttpConnection
 14 {
 15 
 16     /**
 17      * @var PayPalHttpConfig
 18      */
 19     private $httpConfig;
 20 
 21     /**
 22      * LoggingManager
 23      *
 24      * @var PayPalLoggingManager
 25      */
 26     private $logger;
 27 
 28     /**
 29      * @var array
 30      */
 31     private $responseHeaders = array();
 32 
 33     /**
 34      * @var bool
 35      */
 36     private $skippedHttpStatusLine = false;
 37 
 38     /**
 39      * Default Constructor
 40      *
 41      * @param PayPalHttpConfig $httpConfig
 42      * @param array            $config
 43      * @throws PayPalConfigurationException
 44      */
 45     public function __construct(PayPalHttpConfig $httpConfig, array $config)
 46     {
 47         if (!function_exists("curl_init")) {
 48             throw new PayPalConfigurationException("Curl module is not available on this system");
 49         }
 50         $this->httpConfig = $httpConfig;
 51         $this->logger = PayPalLoggingManager::getInstance(__CLASS__);
 52     }
 53 
 54     /**
 55      * Gets all Http Headers
 56      *
 57      * @return array
 58      */
 59     private function getHttpHeaders()
 60     {
 61         $ret = array();
 62         foreach ($this->httpConfig->getHeaders() as $k => $v) {
 63             $ret[] = "$k: $v";
 64         }
 65         return $ret;
 66     }
 67 
 68     /**
 69      * Parses the response headers for debugging.
 70      *
 71      * @param resource $ch
 72      * @param string $data
 73      * @return int
 74      */
 75     protected function parseResponseHeaders($ch, $data) {
 76         if (!$this->skippedHttpStatusLine) {
 77             $this->skippedHttpStatusLine = true;
 78             return strlen($data);
 79         }
 80 
 81         $trimmedData = trim($data);
 82         if (strlen($trimmedData) == 0) {
 83             return strlen($data);
 84         }
 85 
 86         list($key, $value) = explode(":", $trimmedData, 2);
 87 
 88         $key = trim($key);
 89         $value = trim($value);
 90 
 91         // This will skip over the HTTP Status Line and any other lines
 92         // that don't look like header lines with values
 93         if (strlen($key) > 0 && strlen($value) > 0) {
 94             // This is actually a very basic way of looking at response headers
 95             // and may miss a few repeated headers with different (appended)
 96             // values but this should work for debugging purposes.
 97             $this->responseHeaders[$key] = $value;
 98         }
 99 
100         return strlen($data);
101     }
102 
103 
104     /**
105      * Implodes a key/value array for printing.
106      *
107      * @param array $arr
108      * @return string
109      */
110     protected function implodeArray($arr) {
111         $retStr = '';
112         foreach($arr as $key => $value) {
113             $retStr .= $key . ': ' . $value . ', ';
114         }
115         rtrim($retStr, ', ');
116         return $retStr;
117     }
118 
119     /**
120      * Executes an HTTP request
121      *
122      * @param string $data query string OR POST content as a string
123      * @return mixed
124      * @throws PayPalConnectionException
125      */
126     public function execute($data)
127     {
128         //Initialize the logger
129         $this->logger->info($this->httpConfig->getMethod() . ' ' . $this->httpConfig->getUrl());
130 
131         //Initialize Curl Options
132         $ch = curl_init($this->httpConfig->getUrl());
133         $options = $this->httpConfig->getCurlOptions();
134         if (empty($options[CURLOPT_HTTPHEADER])) {
135             unset($options[CURLOPT_HTTPHEADER]);
136         }
137         curl_setopt_array($ch, $options);
138         curl_setopt($ch, CURLOPT_URL, $this->httpConfig->getUrl());
139         curl_setopt($ch, CURLOPT_HEADER, false);
140         curl_setopt($ch, CURLINFO_HEADER_OUT, true);
141         curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHttpHeaders());
142 
143         //Determine Curl Options based on Method
144         switch ($this->httpConfig->getMethod()) {
145             case 'POST':
146                 curl_setopt($ch, CURLOPT_POST, true);
147                 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
148                 break;
149             case 'PUT':
150             case 'PATCH':
151             case 'DELETE':
152                 curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
153                 break;
154         }
155 
156         //Default Option if Method not of given types in switch case
157         if ($this->httpConfig->getMethod() != null) {
158             curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->httpConfig->getMethod());
159         }
160 
161         $this->responseHeaders = array();
162         $this->skippedHttpStatusLine = false;
163         curl_setopt($ch, CURLOPT_HEADERFUNCTION, array($this, 'parseResponseHeaders'));
164 
165         //Execute Curl Request
166         $result = curl_exec($ch);
167         //Retrieve Response Status
168         $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
169 
170         //Retry if Certificate Exception
171         if (curl_errno($ch) == 60) {
172             $this->logger->info("Invalid or no certificate authority found - Retrying using bundled CA certs file");
173             curl_setopt($ch, CURLOPT_CAINFO, dirname(__FILE__) . '/cacert.pem');
174             $result = curl_exec($ch);
175             //Retrieve Response Status
176             $httpStatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
177         }
178 
179         //Throw Exception if Retries and Certificates doenst work
180         if (curl_errno($ch)) {
181             $ex = new PayPalConnectionException(
182                 $this->httpConfig->getUrl(),
183                 curl_error($ch),
184                 curl_errno($ch)
185             );
186             curl_close($ch);
187             throw $ex;
188         }
189 
190         // Get Request and Response Headers
191         $requestHeaders = curl_getinfo($ch, CURLINFO_HEADER_OUT);
192         $this->logger->debug("Request Headers \t: " . str_replace("\r\n", ", ", $requestHeaders));
193         $this->logger->debug(($data && $data != '' ? "Request Data\t\t: " . $data : "No Request Payload") . "\n" . str_repeat('-', 128) . "\n");
194         $this->logger->info("Response Status \t: " . $httpStatus);
195         $this->logger->debug("Response Headers\t: " . $this->implodeArray($this->responseHeaders));
196 
197         //Close the curl request
198         curl_close($ch);
199 
200         //More Exceptions based on HttpStatus Code
201         if ($httpStatus < 200 || $httpStatus >= 300) {
202             $ex = new PayPalConnectionException(
203                 $this->httpConfig->getUrl(),
204                 "Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}.",
205                 $httpStatus
206             );
207             $ex->setData($result);
208             $this->logger->error("Got Http response code $httpStatus when accessing {$this->httpConfig->getUrl()}. " . $result);
209             $this->logger->debug("\n\n" . str_repeat('=', 128) . "\n");
210             throw $ex;
211         }
212 
213         $this->logger->debug(($result && $result != '' ? "Response Data \t: " . $result : "No Response Body") . "\n\n" . str_repeat('=', 128) . "\n");
214 
215         //Return result object
216         return $result;
217     }
218 }
219 
API documentation generated by ApiGen