🍲dfcv🏰dd⋉(● ∸ ●)⋊@% PNG %k25u25%fgd5n! PNG %k25u25%fgd5n!paypalhttp/lib/PayPalHttp/Serializer/Multipart.php 0000644 00000010231 15242753701 0016334 0 ustar 00 body) || !$this->isAssociative($request->body))
{
throw new \Exception("HttpRequest body must be an associative array when Content-Type is: " . $request->headers["content-type"]);
}
$boundary = "---------------------" . md5(mt_rand() . microtime());
$contentTypeHeader = $request->headers["content-type"];
$request->headers["content-type"] = "{$contentTypeHeader}; boundary={$boundary}";
$value_params = [];
$file_params = [];
$disallow = ["\0", "\"", "\r", "\n"];
$body = [];
foreach ($request->body as $k => $v) {
$k = str_replace($disallow, "_", $k);
if (is_resource($v)) {
$file_params[] = $this->prepareFilePart($k, $v, $boundary);
} else if ($v instanceof FormPart) {
$value_params[] = $this->prepareFormPart($k, $v, $boundary);
} else {
$value_params[] = $this->prepareFormField($k, $v, $boundary);
}
}
$body = array_merge($value_params, $file_params);
// add boundary for each parameters
array_walk($body, function (&$part) use ($boundary) {
$part = "--{$boundary}" . self::LINEFEED . "{$part}";
});
// add final boundary
$body[] = "--{$boundary}--";
$body[] = "";
return implode(self::LINEFEED, $body);
}
public function decode($data)
{
throw new \Exception("Multipart does not support deserialization");
}
private function isAssociative(array $array)
{
return array_values($array) !== $array;
}
private function prepareFormField($partName, $value, $boundary)
{
return implode(self::LINEFEED, [
"Content-Disposition: form-data; name=\"{$partName}\"",
"",
filter_var($value),
]);
}
private function prepareFilePart($partName, $file, $boundary)
{
$fileInfo = new finfo(FILEINFO_MIME_TYPE);
$filePath = stream_get_meta_data($file)['uri'];
$data = file_get_contents($filePath);
$mimeType = $fileInfo->buffer($data);
$splitFilePath = explode(DIRECTORY_SEPARATOR, $filePath);
$filePath = end($splitFilePath);
$disallow = ["\0", "\"", "\r", "\n"];
$filePath = str_replace($disallow, "_", $filePath);
return implode(self::LINEFEED, [
"Content-Disposition: form-data; name=\"{$partName}\"; filename=\"{$filePath}\"",
"Content-Type: {$mimeType}",
"",
$data,
]);
}
private function prepareFormPart($partName, $formPart, $boundary)
{
$contentDisposition = "Content-Disposition: form-data; name=\"{$partName}\"";
$partHeaders = $formPart->getHeaders();
$formattedheaders = array_change_key_case($partHeaders);
if (array_key_exists("content-type", $formattedheaders)) {
if ($formattedheaders["content-type"] === "application/json") {
$contentDisposition .= "; filename=\"{$partName}.json\"";
}
$tempRequest = new HttpRequest('/', 'POST');
$tempRequest->headers = $formattedheaders;
$tempRequest->body = $formPart->getValue();
$encoder = new Encoder();
$partValue = $encoder->serializeRequest($tempRequest);
} else {
$partValue = $formPart->getValue();
}
$finalPartHeaders = [];
foreach ($partHeaders as $k => $v) {
$finalPartHeaders[] = "{$k}: {$v}";
}
$body = array_merge([$contentDisposition], $finalPartHeaders, [""], [$partValue]);
return implode(self::LINEFEED, $body);
}
}
paypalhttp/lib/PayPalHttp/Serializer/FormPart.php 0000644 00000000616 15242753701 0016113 0 ustar 00 value = $value;
$this->headers = array_merge([], $headers);
}
public function getValue()
{
return $this->value;
}
public function getHeaders()
{
return $this->headers;
}
}
paypalhttp/lib/PayPalHttp/Serializer/Form.php 0000644 00000002222 15242753701 0015257 0 ustar 00 body) || !$this->isAssociative($request->body))
{
throw new \Exception("HttpRequest body must be an associative array when Content-Type is: " . $request->headers["Content-Type"]);
}
return http_build_query($request->body);
}
/**
* @param $body
* @return mixed
* @throws \Exception as multipart does not support deserialization.
*/
public function decode($body)
{
throw new \Exception("CurlSupported does not support deserialization");
}
private function isAssociative(array $array)
{
return array_values($array) !== $array;
}
}
paypalhttp/lib/PayPalHttp/Serializer/Json.php 0000644 00000001307 15242753701 0015270 0 ustar 00 body;
if (is_string($body)) {
return $body;
}
if (is_array($body)) {
return json_encode($body);
}
throw new \Exception("Cannot serialize data. Unknown type");
}
public function decode($data)
{
return json_decode($data);
}
}
paypalhttp/lib/PayPalHttp/Serializer/Text.php 0000644 00000001220 15242753701 0015275 0 ustar 00 body;
if (is_string($body)) {
return $body;
}
if (is_array($body)) {
return json_encode($body);
}
return implode(" ", $body);
}
public function decode($data)
{
return $data;
}
}
paypalhttp/lib/PayPalHttp/Curl.php 0000644 00000001641 15242753701 0013154 0 ustar 00 curl = $curl;
}
public function setOpt($option, $value)
{
curl_setopt($this->curl, $option, $value);
return $this;
}
public function close()
{
curl_close($this->curl);
return $this;
}
public function exec()
{
return curl_exec($this->curl);
}
public function errNo()
{
return curl_errno($this->curl);
}
public function getInfo($option)
{
return curl_getinfo($this->curl, $option);
}
public function error()
{
return curl_error($this->curl);
}
}
paypalhttp/lib/PayPalHttp/Encoder.php 0000644 00000007033 15242753701 0013627 0 ustar 00 serializers[] = new Json();
$this->serializers[] = new Text();
$this->serializers[] = new Multipart();
$this->serializers[] = new Form();
}
public function serializeRequest(HttpRequest $request)
{
if (!array_key_exists('content-type', $request->headers)) {
$message = "HttpRequest does not have Content-Type header set";
echo $message;
throw new \Exception($message);
}
$contentType = $request->headers['content-type'];
/** @var Serializer $serializer */
$serializer = $this->serializer($contentType);
if (is_null($serializer)) {
$message = sprintf("Unable to serialize request with Content-Type: %s. Supported encodings are: %s", $contentType, implode(", ", $this->supportedEncodings()));
echo $message;
throw new \Exception($message);
}
if (!(is_string($request->body) || is_array($request->body))) {
$message = "Body must be either string or array";
echo $message;
throw new \Exception($message);
}
$serialized = $serializer->encode($request);
if (array_key_exists("content-encoding", $request->headers) && $request->headers["content-encoding"] === "gzip") {
$serialized = gzencode($serialized);
}
return $serialized;
}
public function deserializeResponse($responseBody, $headers)
{
if (!array_key_exists('content-type', $headers)) {
$message = "HTTP response does not have Content-Type header set";
echo $message;
throw new \Exception($message);
}
$contentType = $headers['content-type'];
$contentType = strtolower($contentType);
/** @var Serializer $serializer */
$serializer = $this->serializer($contentType);
if (is_null($serializer)) {
throw new \Exception(sprintf("Unable to deserialize response with Content-Type: %s. Supported encodings are: %s", $contentType, implode(", ", $this->supportedEncodings())));
}
if (array_key_exists("content-encoding", $headers) && $headers["content-encoding"] === "gzip") {
$responseBody = gzdecode($responseBody);
}
return $serializer->decode($responseBody);
}
private function serializer($contentType)
{
/** @var Serializer $serializer */
foreach ($this->serializers as $serializer) {
try {
if (preg_match($serializer->contentType(), $contentType) == 1) {
return $serializer;
}
} catch (\Exception $ex) {
$message = sprintf("Error while checking content type of %s: %s", get_class($serializer), $ex->getMessage());
echo $message;
throw new \Exception($message, $ex->getCode(), $ex);
}
}
return NULL;
}
private function supportedEncodings()
{
$values = [];
/** @var Serializer $serializer */
foreach ($this->serializers as $serializer) {
$values[] = $serializer->contentType();
}
return $values;
}
}
paypalhttp/lib/PayPalHttp/IOException.php 0000644 00000000362 15242753701 0014434 0 ustar 00 path = $path;
$this->verb = $verb;
$this->body = NULL;
$this->headers = [];
}
}
paypalhttp/lib/PayPalHttp/Serializer.php 0000644 00000001173 15242753701 0014360 0 ustar 00 statusCode = $statusCode;
$this->headers = $headers;
}
}
paypalhttp/lib/PayPalHttp/HttpResponse.php 0000644 00000001007 15242753701 0014701 0 ustar 00 statusCode = $statusCode;
$this->headers = $headers;
$this->result = $body;
}
}
paypalhttp/lib/PayPalHttp/Injector.php 0000644 00000000454 15242753701 0014025 0 ustar 00 environment = $environment;
$this->encoder = new Encoder();
$this->curlCls = Curl::class;
}
/**
* Injectors are blocks that can be used for executing arbitrary pre-flight logic, such as modifying a request or logging data.
* Executed in first-in first-out order.
*
* @param Injector $inj
*/
public function addInjector(Injector $inj)
{
$this->injectors[] = $inj;
}
/**
* The method that takes an HTTP request, serializes the request, makes a call to given environment, and deserialize response
*
* @param HttpRequest $httpRequest
* @return HttpResponse
*
* @throws HttpException
* @throws IOException
*/
public function execute(HttpRequest $httpRequest)
{
$requestCpy = clone $httpRequest;
$curl = new Curl();
foreach ($this->injectors as $inj) {
$inj->inject($requestCpy);
}
$url = $this->environment->baseUrl() . $requestCpy->path;
$formattedHeaders = $this->prepareHeaders($requestCpy->headers);
if (!array_key_exists("user-agent", $formattedHeaders)) {
$requestCpy->headers["user-agent"] = $this->userAgent();
}
$body = "";
if (!is_null($requestCpy->body)) {
$rawHeaders = $requestCpy->headers;
$requestCpy->headers = $formattedHeaders;
$body = $this->encoder->serializeRequest($requestCpy);
$requestCpy->headers = $this->mapHeaders($rawHeaders,$requestCpy->headers);
}
$curl->setOpt(CURLOPT_URL, $url);
$curl->setOpt(CURLOPT_CUSTOMREQUEST, $requestCpy->verb);
$curl->setOpt(CURLOPT_HTTPHEADER, $this->serializeHeaders($requestCpy->headers));
$curl->setOpt(CURLOPT_RETURNTRANSFER, 1);
$curl->setOpt(CURLOPT_HEADER, 0);
if (!is_null($requestCpy->body)) {
$curl->setOpt(CURLOPT_POSTFIELDS, $body);
}
if (strpos($this->environment->baseUrl(), "https://") === 0) {
$curl->setOpt(CURLOPT_SSL_VERIFYPEER, true);
$curl->setOpt(CURLOPT_SSL_VERIFYHOST, 2);
}
if ($caCertPath = $this->getCACertFilePath()) {
$curl->setOpt(CURLOPT_CAINFO, $caCertPath);
}
$response = $this->parseResponse($curl);
$curl->close();
return $response;
}
/**
* Returns an array representing headers with their keys
* to be lower case
* @param $headers
* @return array
*/
public function prepareHeaders($headers){
$preparedHeaders = array_change_key_case($headers);
if (array_key_exists("content-type", $preparedHeaders)) {
$preparedHeaders["content-type"] = strtolower($preparedHeaders["content-type"]);
}
return $preparedHeaders;
}
/**
* Returns an array representing headers with their key in
* original cases and updated values
* @param $rawHeaders
* @param $formattedHeaders
* @return array
*/
public function mapHeaders($rawHeaders, $formattedHeaders){
$rawHeadersKey = array_keys($rawHeaders);
foreach ($rawHeadersKey as $array_key) {
if(array_key_exists(strtolower($array_key), $formattedHeaders)){
$rawHeaders[$array_key] = $formattedHeaders[strtolower($array_key)];
}
}
return $rawHeaders;
}
/**
* Returns default user-agent
*
* @return string
*/
public function userAgent()
{
return "PayPalHttp-PHP HTTP/1.1";
}
/**
* Return the filepath to your custom CA Cert if needed.
* @return string
*/
protected function getCACertFilePath()
{
return null;
}
protected function setCurl(Curl $curl)
{
$this->curl = $curl;
}
protected function setEncoder(Encoder $encoder)
{
$this->encoder = $encoder;
}
private function serializeHeaders($headers)
{
$headerArray = [];
if ($headers) {
foreach ($headers as $key => $val) {
$headerArray[] = $key . ": " . $val;
}
}
return $headerArray;
}
private function parseResponse($curl)
{
$headers = [];
$curl->setOpt(CURLOPT_HEADERFUNCTION,
function($curl, $header) use (&$headers)
{
$len = strlen($header);
$k = "";
$v = "";
$this->deserializeHeader($header, $k, $v);
$headers[$k] = $v;
return $len;
});
$responseData = $curl->exec();
$statusCode = $curl->getInfo(CURLINFO_HTTP_CODE);
$errorCode = $curl->errNo();
$error = $curl->error();
if ($errorCode > 0) {
throw new IOException($error, $errorCode);
}
$body = $responseData;
if ($statusCode >= 200 && $statusCode < 300) {
$responseBody = NULL;
if (!empty($body)) {
$responseBody = $this->encoder->deserializeResponse($body, $this->prepareHeaders($headers));
}
return new HttpResponse(
$errorCode === 0 ? $statusCode : $errorCode,
$responseBody,
$headers
);
} else {
throw new HttpException($body, $statusCode, $headers);
}
}
private function deserializeHeader($header, &$key, &$value)
{
if (strlen($header) > 0) {
if (empty($header) || strpos($header, ':') === false) {
return NULL;
}
list($k, $v) = explode(":", $header);
$key = trim($k);
$value = trim($v);
}
}
}
paypalhttp/CHANGELOG.md 0000644 00000000146 15242753701 0010552 0 ustar 00 ## 1.0.1
* Fix Case Sensitivity of Content Type for deserialization process
## 1.0.0
- First release
paypalhttp/Rakefile 0000644 00000000151 15242753701 0010402 0 ustar 00 spec = Gem::Specification.find_by_name 'releasinator'
load "#{spec.gem_dir}/lib/tasks/releasinator.rake"
paypalhttp/.gitignore 0000644 00000001062 15242753701 0010727 0 ustar 00 .DS_Store
/vendor/
composer.phar
composer.lock
# User-specific stuff:
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/dictionaries
.idea/codeStyles/Project.xml
.idea/codeStyles/codeStyleConfig.xml
.idea/*
# Sensitive or high-churn files:
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.xml
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
## File-based project format:
*.iws
.idea/*.iml
.idea/vcs.xml
.idea/php.xml
.idea/php-test-framework.xml
.idea/modules.xml
__files/*
mappings/*
paypalhttp/README.md 0000644 00000005152 15242753701 0010222 0 ustar 00 ## PayPal HttpClient
PayPalHttp is a generic HTTP Client.
In it's simplest form, an [`HttpClient`](lib/PayPalHttp/HttpClient.php) exposes an `execute` method which takes an [HTTP request](lib/PayPalHttp/HttpRequest.php), executes it against the domain described in an [Environment](lib/PayPalHttp/Environment.php), and returns an [HTTP response](lib/PayPalHttp/HttpResponse.php).
### Environment
An [`Environment`](./lib/PayPalHttp/environment.rb) describes a domain that hosts a REST API, against which an `HttpClient` will make requests. `Environment` is a simple interface that wraps one method, `baseUrl`.
```php
$env = new Environment('https://example.com');
```
### Requests
HTTP requests contain all the information needed to make an HTTP request against the REST API. Specifically, one request describes a path, a verb, any path/query/form parameters, headers, attached files for upload, and body data.
### Responses
HTTP responses contain information returned by a server in response to a request as described above. They are simple objects which contain a status code, headers, and any data returned by the server.
```php
$request = new HttpRequest("/path", "GET");
$request->body[] = "some data";
$response = $client->execute($req);
$statusCode = $response->statusCode;
$headers = $response->headers;
$data = $response->result;
```
### Injectors
Injectors are blocks that can be used for executing arbitrary pre-flight logic, such as modifying a request or logging data. Injectors are attached to an `HttpClient` using the `addInjector` method.
The `HttpClient` executes its injectors in a first-in, first-out order, before each request.
```php
class LogInjector implements Injector
{
public function inject($httpRequest)
{
// Do some logging here
}
}
$logInjector = new LogInjector();
$client = new HttpClient($environment);
$client->addInjector($logInjector);
...
```
### Error Handling
`HttpClient#execute` may throw an `Exception` if something went wrong during the course of execution. If the server returned a non-200 response, [IOException](lib/PayPalHttp/IOException.php) will be thrown, that will contain a status code and headers you can use for debugging.
```php
try
{
$client->execute($req);
}
catch (HttpException $e)
{
$statusCode = $e->response->statusCode;
$headers = $e->response->headers;
$body = $e->response->result;
}
```
## License
PayPalHttp-PHP is open source and available under the MIT license. See the [LICENSE](./LICENSE) file for more information.
## Contributing
Pull requests and issues are welcome. Please see [CONTRIBUTING.md](./CONTRIBUTING.md) for more details.
paypalhttp/composer.json 0000644 00000000753 15242753701 0011467 0 ustar 00 {
"name": "paypal/paypalhttp",
"type": "library",
"license": "MIT",
"authors": [
{
"name": "PayPal",
"homepage": "https://github.com/paypal/paypalhttp_php/contributors"
}
],
"require": {
"ext-curl": "*"
},
"require-dev": {
"phpunit/phpunit": "^5.7",
"wiremock-php/wiremock-php": "1.43.2"
},
"autoload": {
"psr-4": {
"PayPalHttp\\": "lib/PayPalHttp"
}
}
}
paypalhttp/.gitattributes 0000644 00000000222 15242753701 0011627 0 ustar 00 tests/ export-ignore
.idea/ export-ignore
.github/ export-ignore
.releasinator.rb export-ignore
Gemfile export-ignore
Gemfile.lock export-ignore
paypalhttp/CONTRIBUTING.md 0000644 00000000403 15242753701 0011166 0 ustar 00 # Contribute to the PayPal PHP HttpClient
### *Pull requests are welcome!*
General Guidelines
------------------
* **Code style.** Please follow local code style. Ask if you're unsure.
* **No warnings.** All generated code must compile without warnings.
paypalhttp/phpunit.xml 0000644 00000000351 15242753701 0011150 0 ustar 00
./tests/unit
paypalhttp/LICENSE 0000644 00000002046 15242753701 0007747 0 ustar 00 Copyright (c) 2009-2021 PayPal, Inc.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
paypalhttp/.travis.yml 0000644 00000000320 15242753701 0011044 0 ustar 00 sudo: false
language: php
php:
- 5.6
- 7.0
- 7.1
- hhvm
matrix:
allow_failures:
- php: hhvm
fast_finish: true
before_script:
- composer self-update
- composer install --dev
script:
- vendor/bin/phpunit
paypal-checkout-sdk/tests/Orders/OrdersAuthorizeTest.php 0000644 00000001201 15242753701 0017516 0 ustar 00 markTestSkipped("Need an approved Order ID to execute this test.");
$request = new OrdersAuthorizeRequest('ORDER-ID');
$request->body = $this->buildRequestBody();
$client = TestHarness::client();
$response = $client->execute($request);
$this->assertEquals(201, $response->statusCode);
$this->assertNotNull($response->result);
}
}
paypal-checkout-sdk/tests/Orders/OrdersPatchTest.php 0000644 00000004722 15242753701 0016616 0 ustar 00 "add",
"path" => "/purchase_units/@reference_id=='test_ref_id1'/description",
"value" => "added_description"
],
[
"op" => "replace",
"path" => "/purchase_units/@reference_id=='test_ref_id1'/amount",
"value" => [
"currency_code" => "USD",
"value" => "200.00"
]
]
];
}
public function testOrdersPatchRequest()
{
$client = TestHarness::client();
$createdOrder = OrdersCreateTest::create($client);
$request = new OrdersPatchRequest($createdOrder->result->id);
$request->body = $this->buildRequestBody();
$response = $client->execute($request);
$this->assertEquals(204, $response->statusCode);
$request = new OrdersGetRequest($createdOrder->result->id);
$response = $client->execute($request);
$this->assertEquals(200, $response->statusCode);
$this->assertNotNull($response->result);
$createdOrder = $response->result;
$this->assertNotNull($createdOrder->id);
$this->assertNotNull($createdOrder->purchase_units);
$this->assertEquals(1, count($createdOrder->purchase_units));
$firstPurchaseUnit = $createdOrder->purchase_units[0];
$this->assertEquals("test_ref_id1", $firstPurchaseUnit->reference_id);
$this->assertEquals("USD", $firstPurchaseUnit->amount->currency_code);
$this->assertEquals("200.00", $firstPurchaseUnit->amount->value);
$this->assertEquals("added_description", $firstPurchaseUnit->description);
$this->assertNotNull($createdOrder->create_time);
$this->assertNotNull($createdOrder->links);
$foundApproveUrl = false;
foreach ($createdOrder->links as $link) {
if ("approve" === $link->rel) {
$foundApproveUrl = true;
$this->assertNotNull($link->href);
$this->assertEquals("GET", $link->method);
}
}
$this->assertTrue($foundApproveUrl);
$this->assertEquals("CREATED", $createdOrder->status);
}
}
paypal-checkout-sdk/tests/Orders/OrdersCreateTest.php 0000644 00000004304 15242753701 0016756 0 ustar 00 "CAPTURE",
"purchase_units" => [[
"reference_id" => "test_ref_id1",
"amount" => [
"value" => "100.00",
"currency_code" => "USD"
]
]],
"redirect_urls" => [
"cancel_url" => "https://example.com/cancel",
"return_url" => "https://example.com/return"
]
];
}
public static function create($client) {
$request = new OrdersCreateRequest();
$request->prefer("return=representation");
$request->body = self::buildRequestBody();
return $client->execute($request);
}
public function testOrdersCreateRequest()
{
$client = TestHarness::client();
$response = self::create($client);
$this->assertEquals(201, $response->statusCode);
$this->assertNotNull($response->result);
$createdOrder = $response->result;
$this->assertNotNull($createdOrder->id);
$this->assertNotNull($createdOrder->purchase_units);
$this->assertEquals(1, count($createdOrder->purchase_units));
$firstPurchaseUnit = $createdOrder->purchase_units[0];
$this->assertEquals("test_ref_id1", $firstPurchaseUnit->reference_id);
$this->assertEquals("USD", $firstPurchaseUnit->amount->currency_code);
$this->assertEquals("100.00", $firstPurchaseUnit->amount->value);
$this->assertNotNull($createdOrder->create_time);
$this->assertNotNull($createdOrder->links);
$foundApproveUrl = false;
foreach ($createdOrder->links as $link) {
if ("approve" === $link->rel) {
$foundApproveUrl = true;
$this->assertNotNull($link->href);
$this->assertEquals("GET", $link->method);
}
}
$this->assertTrue($foundApproveUrl);
$this->assertEquals("CREATED", $createdOrder->status);
}
}
paypal-checkout-sdk/tests/Orders/OrdersGetTest.php 0000644 00000003076 15242753701 0016277 0 ustar 00 result->id);
$response = $client->execute($request);
$this->assertEquals(200, $response->statusCode);
$this->assertNotNull($response->result);
$createdOrder = $response->result;
$this->assertNotNull($createdOrder->id);
$this->assertNotNull($createdOrder->purchase_units);
$this->assertEquals(1, count($createdOrder->purchase_units));
$firstPurchaseUnit = $createdOrder->purchase_units[0];
$this->assertEquals("test_ref_id1", $firstPurchaseUnit->reference_id);
$this->assertEquals("USD", $firstPurchaseUnit->amount->currency_code);
$this->assertEquals("100.00", $firstPurchaseUnit->amount->value);
$this->assertNotNull($createdOrder->create_time);
$this->assertNotNull($createdOrder->links);
$foundApproveUrl = false;
foreach ($createdOrder->links as $link) {
if ("approve" === $link->rel) {
$foundApproveUrl = true;
$this->assertNotNull($link->href);
$this->assertEquals("GET", $link->method);
}
}
$this->assertTrue($foundApproveUrl);
$this->assertEquals("CREATED", $createdOrder->status);
}
}
paypal-checkout-sdk/tests/Orders/OrdersCaptureTest.php 0000644 00000001106 15242753701 0017153 0 ustar 00 markTestSkipped("Need an approved Order ID to execute this test.");
$request = new OrdersCaptureRequest('ORDER-ID');
$client = TestHarness::client();
$response = $client->execute($request);
$this->assertEquals(201, $response->statusCode);
$this->assertNotNull($response->result);
}
}
paypal-checkout-sdk/tests/TestHarness.php 0000644 00000001207 15242753701 0014540 0 ustar 00 >";
$clientSecret = getenv("CLIENT_SECRET") ?: "<>";
return new SandboxEnvironment($clientId, $clientSecret);
}
}
paypal-checkout-sdk/samples/AuthorizeIntentExamples/CreateOrder.php 0000644 00000024277 15242753701 0021645 0 ustar 00 'AUTHORIZE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel',
'brand_name' => 'EXAMPLE INC',
'locale' => 'en-US',
'landing_page' => 'BILLING',
'shipping_preference' => 'SET_PROVIDED_ADDRESS',
'user_action' => 'PAY_NOW',
),
'purchase_units' =>
array(
0 =>
array(
'reference_id' => 'PUHF',
'description' => 'Sporting Goods',
'custom_id' => 'CUST-HighFashions',
'soft_descriptor' => 'HighFashions',
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00',
'breakdown' =>
array(
'item_total' =>
array(
'currency_code' => 'USD',
'value' => '180.00',
),
'shipping' =>
array(
'currency_code' => 'USD',
'value' => '20.00',
),
'handling' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
'tax_total' =>
array(
'currency_code' => 'USD',
'value' => '20.00',
),
'shipping_discount' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
),
),
'items' =>
array(
0 =>
array(
'name' => 'T-Shirt',
'description' => 'Green XL',
'sku' => 'sku01',
'unit_amount' =>
array(
'currency_code' => 'USD',
'value' => '90.00',
),
'tax' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
'quantity' => '1',
'category' => 'PHYSICAL_GOODS',
),
1 =>
array(
'name' => 'Shoes',
'description' => 'Running, Size 10.5',
'sku' => 'sku02',
'unit_amount' =>
array(
'currency_code' => 'USD',
'value' => '45.00',
),
'tax' =>
array(
'currency_code' => 'USD',
'value' => '5.00',
),
'quantity' => '2',
'category' => 'PHYSICAL_GOODS',
),
),
'shipping' =>
array(
'method' => 'United States Postal Service',
'name' =>
array(
'full_name' => 'John Doe',
),
'address' =>
array(
'address_line_1' => '123 Townsend St',
'address_line_2' => 'Floor 6',
'admin_area_2' => 'San Francisco',
'admin_area_1' => 'CA',
'postal_code' => '94107',
'country_code' => 'US',
),
),
),
),
);
}
/**
* Setting up the JSON request body for creating the Order with minimum request body. The Intent in the
* request body should be set as "AUTHORIZE" for authorize intent flow.
*
*/
private static function buildMinimumRequestBody()
{
return array(
'intent' => 'AUTHORIZE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel'
),
'purchase_units' =>
array(
0 =>
array(
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00'
)
)
)
);
}
/**
* This is the sample function which can be used to create an order. It uses the
* JSON body returned by buildRequestBody() to create an new Order.
*/
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = CreateOrder::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
/**
* This is the sample function which can be used to create an order. It uses the
* JSON body returned by buildMinimumRequestBody() to create an new Order.
*/
public static function createOrderWithMinimumBody($debug=false)
{
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = CreateOrder::buildMinimumRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Order With Minimum Body\n";
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
CreateOrder::createOrderWithMinimumBody(true);
} paypal-checkout-sdk/samples/AuthorizeIntentExamples/AuthorizeOrder.php 0000644 00000003734 15242753701 0022407 0 ustar 00 body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Authorization ID: {$response->result->purchase_units[0]->payments->authorizations[0]->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Authorization Links:\n";
foreach($response->result->purchase_units[0]->payments->authorizations[0]->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
/**
* This is an driver function which invokes authorize order.
*/
if (!count(debug_backtrace()))
{
AuthorizeOrder::authorizeOrder('1U242387CB956380X', true);
} paypal-checkout-sdk/samples/AuthorizeIntentExamples/CaptureOrder.php 0000644 00000003204 15242753701 0022030 0 ustar 00 body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Capture ID: {$response->result->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
/**
* Driver function for invoking the capture flow.
*/
if (!count(debug_backtrace()))
{
CaptureOrder::captureOrder('18A38324BV5456924', true);
} paypal-checkout-sdk/samples/AuthorizeIntentExamples/RunAll.php 0000644 00000004345 15242753701 0020635 0 ustar 00 statusCode == 201)
{
$orderId = $order->result->id;
print "Links:\n";
for ($i = 0; $i < count($order->result->links); ++$i)
{
$link = $order->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Created Successfully\n";
print "Copy approve link and paste it in browser. Login with buyer account and follow the instructions.\nOnce approved hit enter...\n";
}
else {
exit(1);
}
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fclose($handle);
print "Authorizing Order...\n";
$response = AuthorizeOrder::authorizeOrder($orderId);
$authId = "";
if ($response->statusCode == 201)
{
print "Authorized Successfully\n";
$authId = $response->result->purchase_units[0]->payments->authorizations[0]->id;
}
else {
exit(1);
}
print "\nCapturing Order...\n";
$response = CaptureOrder::captureOrder($authId);
if ($response->statusCode == 201)
{
print "Captured Successfully\n";
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
$captureId = $response->result->id;
print "Capture ID: {$captureId}\n";
print "Links:\n";
for ($i = 0; $i < count($response->result->links); ++$i){
$link = $response->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
}
else {
exit(1);
}
print "\nRefunding Order...\n";
$response = RefundOrder::refundOrder($captureId);
if ($response->statusCode == 201)
{
print "Refunded Successfully\n";
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Refund ID: {$response->result->id}\n";
print "Links:\n";
for ($i = 0; $i < count($response->result->links); ++$i){
$link = $response->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
}
else {
exit(1);
}
paypal-checkout-sdk/samples/CaptureIntentExamples/CreateOrder.php 0000644 00000017440 15242753701 0021270 0 ustar 00 'CAPTURE',
'application_context' =>
array(
'return_url' => 'https://example.com/return',
'cancel_url' => 'https://example.com/cancel',
'brand_name' => 'EXAMPLE INC',
'locale' => 'en-US',
'landing_page' => 'BILLING',
'shipping_preference' => 'SET_PROVIDED_ADDRESS',
'user_action' => 'PAY_NOW',
),
'purchase_units' =>
array(
0 =>
array(
'reference_id' => 'PUHF',
'description' => 'Sporting Goods',
'custom_id' => 'CUST-HighFashions',
'soft_descriptor' => 'HighFashions',
'amount' =>
array(
'currency_code' => 'USD',
'value' => '220.00',
'breakdown' =>
array(
'item_total' =>
array(
'currency_code' => 'USD',
'value' => '180.00',
),
'shipping' =>
array(
'currency_code' => 'USD',
'value' => '20.00',
),
'handling' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
'tax_total' =>
array(
'currency_code' => 'USD',
'value' => '20.00',
),
'shipping_discount' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
),
),
'items' =>
array(
0 =>
array(
'name' => 'T-Shirt',
'description' => 'Green XL',
'sku' => 'sku01',
'unit_amount' =>
array(
'currency_code' => 'USD',
'value' => '90.00',
),
'tax' =>
array(
'currency_code' => 'USD',
'value' => '10.00',
),
'quantity' => '1',
'category' => 'PHYSICAL_GOODS',
),
1 =>
array(
'name' => 'Shoes',
'description' => 'Running, Size 10.5',
'sku' => 'sku02',
'unit_amount' =>
array(
'currency_code' => 'USD',
'value' => '45.00',
),
'tax' =>
array(
'currency_code' => 'USD',
'value' => '5.00',
),
'quantity' => '2',
'category' => 'PHYSICAL_GOODS',
),
),
'shipping' =>
array(
'method' => 'United States Postal Service',
'name' =>
array(
'full_name' => 'John Doe',
),
'address' =>
array(
'address_line_1' => '123 Townsend St',
'address_line_2' => 'Floor 6',
'admin_area_2' => 'San Francisco',
'admin_area_1' => 'CA',
'postal_code' => '94107',
'country_code' => 'US',
),
),
),
),
);
}
/**
* This is the sample function which can be sued to create an order. It uses the
* JSON body returned by buildRequestBody() to create an new Order.
*/
public static function createOrder($debug=false)
{
$request = new OrdersCreateRequest();
$request->headers["prefer"] = "return=representation";
$request->body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
/**
* This is the driver function which invokes the createOrder function to create
* an sample order.
*/
if (!count(debug_backtrace()))
{
CreateOrder::createOrder(true);
}
paypal-checkout-sdk/samples/CaptureIntentExamples/CaptureOrder.php 0000644 00000003325 15242753701 0021465 0 ustar 00 execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Capture Ids:\n";
foreach($response->result->purchase_units as $purchase_unit)
{
foreach($purchase_unit->payments->captures as $capture)
{
print "\t{$capture->id}";
}
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
/**
* This is the driver function which invokes the captureOrder function with
* Approved Order Id to capture the order payment.
*/
if (!count(debug_backtrace()))
{
CaptureOrder::captureOrder('0F105083N67049335', true);
} paypal-checkout-sdk/samples/CaptureIntentExamples/RunAll.php 0000644 00000004074 15242753701 0020265 0 ustar 00 statusCode == 201)
{
$orderId = $order->result->id;
print "Links:\n";
for ($i = 0; $i < count($order->result->links); ++$i)
{
$link = $order->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Created Successfully\n";
print "Copy approve link and paste it in browser. Login with buyer account and follow the instructions.\nOnce approved hit enter...\n";
}
else {
exit(1);
}
$handle = fopen ("php://stdin","r");
$line = fgets($handle);
fclose($handle);
print "Capturing Order...\n";
$response = CaptureOrder::captureOrder($orderId);
if ($response->statusCode == 201)
{
print "Captured Successfully\n";
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Links:\n";
for ($i = 0; $i < count($response->result->links); ++$i){
$link = $response->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
foreach($response->result->purchase_units as $purchase_unit)
{
foreach($purchase_unit->payments->captures as $capture)
{
$captureId = $capture->id;
}
}
}
else {
exit(1);
}
print "\nRefunding Order...\n";
$response = RefundOrder::refundOrder($captureId);
if ($response->statusCode == 201)
{
print "Refunded Successfully\n";
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Refund ID: {$response->result->id}\n";
print "Links:\n";
for ($i = 0; $i < count($response->result->links); ++$i){
$link = $response->result->links[$i];
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
}
else {
exit(1);
}
paypal-checkout-sdk/samples/PatchOrder.php 0000644 00000005372 15242753701 0014641 0 ustar 00
array (
'op' => 'replace',
'path' => '/intent',
'value' => 'CAPTURE',
),
1 =>
array (
'op' => 'replace',
'path' => '/purchase_units/@reference_id==\'PUHF\'/amount',
'value' =>
array (
'currency_code' => 'USD',
'value' => '200.00',
'breakdown' =>
array (
'item_total' =>
array (
'currency_code' => 'USD',
'value' => '180.00',
),
'tax_total' =>
array (
'currency_code' => 'USD',
'value' => '20.00',
),
),
),
),
);
}
public static function patchOrder($orderId)
{
$client = PayPalClient::client();
$request = new OrdersPatchRequest($orderId);
$request->body = PatchOrder::buildRequestBody();
$client->execute($request);
$response = $client->execute(new OrdersGetRequest($orderId));
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
}
if (!count(debug_backtrace()))
{
print "Before PATCH:\n";
$createdOrder = CreateOrder::createOrder(true)->result;
print "\nAfter PATCH (Changed Intent and Amount):\n";
PatchOrder::patchOrder($createdOrder->id);
} paypal-checkout-sdk/samples/ErrorSample.php 0000644 00000005361 15242753701 0015037 0 ustar 00 $val)
{
$pretty .= $pre . ucfirst($key) .": ";
if (strcmp(gettype($val), "array") == 0){
$pretty .= "\n";
$sno = 1;
foreach ($val as $value)
{
$pretty .= $pre . "\t" . $sno++ . ":\n";
$pretty .= self::prettyPrint($value, $pre . "\t\t");
}
}
else {
$pretty .= $val . "\n";
}
}
return $pretty;
}
/**
* Body has no required parameters (intent, purchase_units)
*/
public static function createError1()
{
$request = new OrdersCreateRequest();
$request->body = "{}";
print "Request Body: {}\n\n";
print "Response:\n";
try{
$client = PayPalClient::client();
$response = $client->execute($request);
}
catch(HttpException $exception){
$message = json_decode($exception->getMessage(), true);
print "Status Code: {$exception->statusCode}\n";
print(self::prettyPrint($message));
}
}
/**
* Body has invalid parameter value for intent
*/
public static function createError2()
{
$request = new OrdersCreateRequest();
$request->body = array (
'intent' => 'INVALID',
'purchase_units' =>
array (
0 =>
array (
'amount' =>
array (
'currency_code' => 'USD',
'value' => '100.00',
),
),
),
);
print "Request Body:\n" . json_encode($request->body, JSON_PRETTY_PRINT) . "\n\n";
try{
$client = PayPalClient::client();
$response = $client->execute($request);
}
catch(HttpException $exception){
print "Response:\n";
$message = json_decode($exception->getMessage(), true);
print "Status Code: {$exception->statusCode}\n";
print(self::prettyPrint($message));
}
}
}
print "Calling createError1 (Body has no required parameters (intent, purchase_units))\n";
ErrorSample::createError1();
print "\n\nCalling createError2 (Body has invalid parameter value for intent)\n";
ErrorSample::createError2();
paypal-checkout-sdk/samples/RefundOrder.php 0000644 00000003266 15242753701 0015025 0 ustar 00
array(
'value' => '20.00',
'currency_code' => 'USD'
)
);
}
/**
* This function can be used to preform refund on the capture.
*/
public static function refundOrder($captureId, $debug=false)
{
$request = new CapturesRefundRequest($captureId);
$request->body = self::buildRequestBody();
$client = PayPalClient::client();
$response = $client->execute($request);
if ($debug)
{
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
return $response;
}
}
/**
* This is the driver function which invokes the refund capture function with
* Capture Id to perform refund on capture.
*/
if (!count(debug_backtrace()))
{
RefundOrder::refundOrder('8XL09935J2224701N', true);
}
paypal-checkout-sdk/samples/GetOrder.php 0000644 00000003257 15242753701 0014321 0 ustar 00 execute(new OrdersGetRequest($orderId));
/**
* Enable below line to print complete response as JSON.
*/
//print json_encode($response->result);
print "Status Code: {$response->statusCode}\n";
print "Status: {$response->result->status}\n";
print "Order ID: {$response->result->id}\n";
print "Intent: {$response->result->intent}\n";
print "Links:\n";
foreach($response->result->links as $link)
{
print "\t{$link->rel}: {$link->href}\tCall Type: {$link->method}\n";
}
print "Gross Amount: {$response->result->purchase_units[0]->amount->currency_code} {$response->result->purchase_units[0]->amount->value}\n";
// To toggle printing the whole response body comment/uncomment below line
echo json_encode($response->result, JSON_PRETTY_PRINT), "\n";
}
}
/**
* This is the driver function which invokes the getOrder function to retrieve
* an sample order.
*
* To get the correct Order id, we are using the createOrder to create new order
* and then we are using the newly created order id.
*/
if (!count(debug_backtrace()))
{
$createdOrder = CreateOrder::createOrder()->result;
GetOrder::getOrder($createdOrder ->id);
} paypal-checkout-sdk/samples/PayPalClient.php 0000644 00000002077 15242753701 0015132 0 ustar 00 >";
$clientSecret = getenv("CLIENT_SECRET") ?: "<>";
return new SandboxEnvironment($clientId, $clientSecret);
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/AccessTokenRequest.php 0000644 00000001311 15242753701 0021656 0 ustar 00 headers["Authorization"] = "Basic " . $environment->authorizationString();
$body = [
"grant_type" => "client_credentials"
];
if (!is_null($refreshToken))
{
$body["grant_type"] = "refresh_token";
$body["refresh_token"] = $refreshToken;
}
$this->body = $body;
$this->headers["Content-Type"] = "application/x-www-form-urlencoded";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/SandboxEnvironment.php 0000644 00000000472 15242753701 0021735 0 ustar 00 headers["Authorization"] = "Basic " . $environment->authorizationString();
$this->headers["Content-Type"] = "application/x-www-form-urlencoded";
$this->body = [
"grant_type" => "authorization_code",
"code" => $authorizationCode
];
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/AuthorizationInjector.php 0000644 00000003016 15242753701 0022445 0 ustar 00 client = $client;
$this->environment = $environment;
$this->refreshToken = $refreshToken;
}
public function inject($request)
{
if (!$this->hasAuthHeader($request) && !$this->isAuthRequest($request))
{
if (is_null($this->accessToken) || $this->accessToken->isExpired())
{
$this->accessToken = $this->fetchAccessToken();
}
$request->headers['Authorization'] = 'Bearer ' . $this->accessToken->token;
}
}
private function fetchAccessToken()
{
$accessTokenResponse = $this->client->execute(new AccessTokenRequest($this->environment, $this->refreshToken));
$accessToken = $accessTokenResponse->result;
return new AccessToken($accessToken->access_token, $accessToken->token_type, $accessToken->expires_in);
}
private function isAuthRequest($request)
{
return $request instanceof AccessTokenRequest || $request instanceof RefreshTokenRequest;
}
private function hasAuthHeader(HttpRequest $request)
{
return array_key_exists("Authorization", $request->headers);
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/UserAgent.php 0000644 00000002620 15242753701 0020004 0 ustar 00 headers["sdk_name"] = "Checkout SDK";
$request->headers["sdk_version"] = "1.0.2";
$request->headers["sdk_tech_stack"] = "PHP " . PHP_VERSION;
$request->headers["api_integration_type"] = "PAYPALSDK";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/PayPalHttpClient.php 0000644 00000001265 15242753701 0021300 0 ustar 00 refreshToken = $refreshToken;
$this->authInjector = new AuthorizationInjector($this, $environment, $refreshToken);
$this->addInjector($this->authInjector);
$this->addInjector(new GzipInjector());
$this->addInjector(new FPTIInstrumentationInjector());
}
public function userAgent()
{
return UserAgent::getValue();
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/AccessToken.php 0000644 00000000744 15242753701 0020316 0 ustar 00 token = $token;
$this->tokenType = $tokenType;
$this->expiresIn = $expiresIn;
$this->createDate = time();
}
public function isExpired()
{
return time() >= $this->createDate + $this->expiresIn;
}
} paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/ProductionEnvironment.php 0000644 00000000465 15242753701 0022467 0 ustar 00 headers["Accept-Encoding"] = "gzip";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Core/PayPalEnvironment.php 0000644 00000000721 15242753701 0021522 0 ustar 00 clientId = $clientId;
$this->clientSecret = $clientSecret;
}
public function authorizationString()
{
return base64_encode($this->clientId . ":" . $this->clientSecret);
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersValidateRequest.php 0000644 00000036247 15242753701 0022752 0 ustar 00 path = str_replace("{order_id}", urlencode($orderId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalClientMetadataId($payPalClientMetadataId)
{
$this->headers["PayPal-Client-Metadata-Id"] = $payPalClientMetadataId;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersCaptureRequest.php 0000644 00000037123 15242753701 0022616 0 ustar 00 path = str_replace("{order_id}", urlencode($orderId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalClientMetadataId($payPalClientMetadataId)
{
$this->headers["PayPal-Client-Metadata-Id"] = $payPalClientMetadataId;
}
public function payPalRequestId($payPalRequestId)
{
$this->headers["PayPal-Request-Id"] = $payPalRequestId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersCreateRequest.php 0000644 00000051220 15242753701 0022410 0 ustar 00 headers["Content-Type"] = "application/json";
}
public function payPalPartnerAttributionId($payPalPartnerAttributionId)
{
$this->headers["PayPal-Partner-Attribution-Id"] = $payPalPartnerAttributionId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersGetRequest.php 0000644 00000034466 15242753701 0021741 0 ustar 00 path = str_replace("{order_id}", urlencode($orderId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersPatchRequest.php 0000644 00000003154 15242753701 0022247 0 ustar 00 path = str_replace("{order_id}", urlencode($orderId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Orders/OrdersAuthorizeRequest.php 0000644 00000037161 15242753701 0023167 0 ustar 00 path = str_replace("{order_id}", urlencode($orderId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalClientMetadataId($payPalClientMetadataId)
{
$this->headers["PayPal-Client-Metadata-Id"] = $payPalClientMetadataId;
}
public function payPalRequestId($payPalRequestId)
{
$this->headers["PayPal-Request-Id"] = $payPalRequestId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/AuthorizationsVoidRequest.php 0000644 00000002207 15242753701 0024236 0 ustar 00 path = str_replace("{authorization_id}", urlencode($authorizationId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/AuthorizationsGetRequest.php 0000644 00000006553 15242753701 0024064 0 ustar 00 path = str_replace("{authorization_id}", urlencode($authorizationId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/CapturesRefundRequest.php 0000644 00000011741 15242753701 0023326 0 ustar 00 path = str_replace("{capture_id}", urlencode($captureId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalRequestId($payPalRequestId)
{
$this->headers["PayPal-Request-Id"] = $payPalRequestId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/RefundsGetRequest.php 0000644 00000010426 15242753701 0022441 0 ustar 00 path = str_replace("{refund_id}", urlencode($refundId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/CapturesGetRequest.php 0000644 00000011041 15242753701 0022613 0 ustar 00 path = str_replace("{capture_id}", urlencode($captureId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/AuthorizationsCaptureRequest.php 0000644 00000012736 15242753701 0024750 0 ustar 00 path = str_replace("{authorization_id}", urlencode($authorizationId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalRequestId($payPalRequestId)
{
$this->headers["PayPal-Request-Id"] = $payPalRequestId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/lib/PayPalCheckoutSdk/Payments/AuthorizationsReauthorizeRequest.php 0000644 00000010426 15242753701 0025640 0 ustar 00 path = str_replace("{authorization_id}", urlencode($authorizationId), $this->path);
$this->headers["Content-Type"] = "application/json";
}
public function payPalRequestId($payPalRequestId)
{
$this->headers["PayPal-Request-Id"] = $payPalRequestId;
}
public function prefer($prefer)
{
$this->headers["Prefer"] = $prefer;
}
}
paypal-checkout-sdk/init 0000644 00000000000 15242753701 0011276 0 ustar 00 paypal-checkout-sdk/.gitignore 0000644 00000000017 15242753701 0012410 0 ustar 00 .idea/
vendor/
paypal-checkout-sdk/README.md 0000644 00000015070 15242753701 0011704 0 ustar 00 # REST API SDK for PHP V2

### To consolidate support across various channels, we have currently turned off the feature of GitHub issues. Please visit https://www.paypal.com/support to submit your request or ask questions within our community forum.
__Welcome to PayPal PHP SDK__. This repository contains PayPal's PHP SDK and samples for [v2/checkout/orders](https://developer.paypal.com/docs/api/orders/v2/) and [v2/payments](https://developer.paypal.com/docs/api/payments/v2/) APIs.
This is a part of the next major PayPal SDK. It includes a simplified interface to only provide simple model objects and blueprints for HTTP calls. This repo currently contains functionality for PayPal Checkout APIs which includes [Orders V2](https://developer.paypal.com/docs/api/orders/v2/) and [Payments V2](https://developer.paypal.com/docs/api/payments/v2/).
Please refer to the [PayPal Checkout Integration Guide](https://developer.paypal.com/docs/checkout/) for more information. Also refer to [Setup your SDK](https://developer.paypal.com/docs/checkout/reference/server-integration/setup-sdk/) for additional information about setting up the SDK's.
## Latest Updates
Beginning January 2020, PayPal will require an update on the Personal Home Page (PHP) Checkout Software Developer Kit (SDK) to version 1.0.1. Merchants who have not updated their PHP Checkout SDK to version 1.0.1 will not be able to deserialize responses using outdated SDK integrations.
All PHP Checkout SDK integrations are expected to be updated by March 1, 2020. Merchants are encouraged to prepare for the update as soon as possible to avoid possible service disruption.
The Status Page has been updated with this information. The bulletin can be found [here](https://www.paypal-status.com/history/eventdetails/11015)
## Prerequisites
PHP 5.6 and above
An environment which supports TLS 1.2 (see the TLS-update site for more information)
## Usage
### Binaries
It is not mandatory to fork this repository for using the PayPal SDK. You can refer [PayPal Checkout Server SDK](https://developer.paypal.com/docs/checkout/reference/server-integration) for configuring and working with SDK without forking this code.
For contributing or referring the samples, You can fork/refer this repository.
### Setting up credentials
Get client ID and client secret by going to https://developer.paypal.com/developer/applications and generating a REST API app. Get Client ID and Secret from there.
```php
require __DIR__ . '/vendor/autoload.php';
use PayPalCheckoutSdk\Core\PayPalHttpClient;
use PayPalCheckoutSdk\Core\SandboxEnvironment;
// Creating an environment
$clientId = "<>";
$clientSecret = "<>";
$environment = new SandboxEnvironment($clientId, $clientSecret);
$client = new PayPalHttpClient($environment);
```
## Examples
### Creating an Order
#### Code:
```php
// Construct a request object and set desired parameters
// Here, OrdersCreateRequest() creates a POST request to /v2/checkout/orders
use PayPalCheckoutSdk\Orders\OrdersCreateRequest;
$request = new OrdersCreateRequest();
$request->prefer('return=representation');
$request->body = [
"intent" => "CAPTURE",
"purchase_units" => [[
"reference_id" => "test_ref_id1",
"amount" => [
"value" => "100.00",
"currency_code" => "USD"
]
]],
"application_context" => [
"cancel_url" => "https://example.com/cancel",
"return_url" => "https://example.com/return"
]
];
try {
// Call API with your client and get a response for your call
$response = $client->execute($request);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
print_r($response);
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
```
#### Example Output:
```
Status Code: 201
Id: 8GB67279RC051624C
Intent: CAPTURE
Gross_amount:
Currency_code: USD
Value: 100.00
Purchase_units:
1:
Amount:
Currency_code: USD
Value: 100.00
Create_time: 2018-08-06T23:34:31Z
Links:
1:
Href: https://api.sandbox.paypal.com/v2/checkout/orders/8GB67279RC051624C
Rel: self
Method: GET
2:
Href: https://www.sandbox.paypal.com/checkoutnow?token=8GB67279RC051624C
Rel: approve
Method: GET
3:
Href: https://api.sandbox.paypal.com/v2/checkout/orders/8GB67279RC051624C/capture
Rel: capture
Method: POST
Status: CREATED
```
## Capturing an Order
Before capture, Order should be approved by the buyer using the approval URL returned in the create order response.
### Code to Execute:
```php
use PayPalCheckoutSdk\Orders\OrdersCaptureRequest;
// Here, OrdersCaptureRequest() creates a POST request to /v2/checkout/orders
// $response->result->id gives the orderId of the order created above
$request = new OrdersCaptureRequest("APPROVED-ORDER-ID");
$request->prefer('return=representation');
try {
// Call API with your client and get a response for your call
$response = $client->execute($request);
// If call returns body in response, you can get the deserialized version from the result attribute of the response
print_r($response);
}catch (HttpException $ex) {
echo $ex->statusCode;
print_r($ex->getMessage());
}
```
#### Example Output:
```
Status Code: 201
Id: 8GB67279RC051624C
Create_time: 2018-08-06T23:39:11Z
Update_time: 2018-08-06T23:39:11Z
Payer:
Name:
Given_name: test
Surname: buyer
Email_address: test-buyer@paypal.com
Payer_id: KWADC7LXRRWCE
Phone:
Phone_number:
National_number: 408-411-2134
Address:
Country_code: US
Links:
1:
Href: https://api.sandbox.paypal.com/v2/checkout/orders/3L848818A2897925Y
Rel: self
Method: GET
Status: COMPLETED
```
## Running tests
To run integration tests using your client id and secret, clone this repository and run the following command:
```sh
$ composer install
$ CLIENT_ID=YOUR_SANDBOX_CLIENT_ID CLIENT_SECRET=OUR_SANDBOX_CLIENT_SECRET composer integration
```
## Samples
You can start off by trying out [creating and capturing an order](/samples/CaptureIntentExamples/RunAll.php)
To try out different samples for both create and authorize intent check [this link](/samples)
Note: Update the `PayPalClient.php` with your sandbox client credentials or pass your client credentials as environment variable while executing the samples.
## License
Code released under [SDK LICENSE](LICENSE)
paypal-checkout-sdk/composer.json 0000644 00000001652 15242753701 0013150 0 ustar 00 {
"name": "paypal/paypal-checkout-sdk",
"description": "PayPal's PHP SDK for Checkout REST APIs",
"keywords": ["paypal", "payments", "rest", "sdk", "orders", "checkout"],
"type": "library",
"license": "Apache-2.0",
"homepage": "http://github.com/paypal/Checkout-PHP-SDK/",
"require": {
"paypal/paypalhttp": "1.0.1"
},
"authors": [
{
"name": "PayPal",
"homepage": "https://github.com/paypal/Checkout-PHP-SDK/contributors"
}
],
"require-dev": {
"phpunit/phpunit": "^5.7"
},
"autoload": {
"psr-4": {
"PayPalCheckoutSdk\\": "lib/PayPalCheckoutSdk",
"Sample\\":"samples/"
}
},
"autoload-dev": {
"psr-4": {
"Test\\":"tests/"
}
},
"scripts": {
"unit": "phpunit --testsuite unit",
"integration": "phpunit --testsuite integration"
}
}
paypal-checkout-sdk/homepage.jpg 0000644 00000502725 15242753701 0012724 0 ustar 00 JFIF C
!*$( %2%(,-/0/#484.7*./. C
...................................................
r @@S&J42@@B
K,D4lȅhAA-f5PD)
P2 MEPTX"MT Zk@!Lcu
C%VJ#G(C@ H*EZZ^2565gRQN6zXM[;Yk4:Q9GVN5H}*]E9Mj̩*%B HRBh !
XXhD3V5PHhh$Z$Q6JfC@(lBEZ
E-!V-h
- %(!-dBPB2dFd2dZ4C@@Z H- `Zӳp-{Q&7uo7o/eagSrB8Ϯ2D0;Vz{'i{hȚH
Ii!{t (Z!D Ԗ4JHU$ZE !4 HȭFP VPHMР "UKmH*2hɢ
f( TB 2!P$ZL!APB2D,B$!
EHd>^|鳯