Git Product home page Git Product logo

paypal-checkout-sdk's Introduction

PayPal Checkout SDK

Tests Latest Stable Version Maintainability Total Downloads License

This Package is a PHP SDK wrapper around version 2 of the PayPal rest API. It provides a simple, fluent API to create and capture orders with both sandbox and production environments supported.

To learn all about it, head over to the extensive documentation.

Installation

PayPal Checkout SDK Package requires PHP 7.4 or higher.

INFO: If you are using an older version of php this package may not function correctly.

The supported way of installing PayPal Checkout SDK package is via Composer.

composer require phpjuice/paypal-checkout-sdk

Setup

PayPal Checkout SDK is designed to simplify using the new PayPal checkout api in your app.

Setup 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.

Setup a Paypal Client

Inorder to communicate with PayPal platform we need to set up a client first :

Create a client with sandbox environment :

// import namespace
use PayPal\Http\Environment\SandboxEnvironment;
use PayPal\Http\PayPalClient;

// client id and client secret retrieved from PayPal
$clientId = "<<PAYPAL-CLIENT-ID>>";
$clientSecret = "<<PAYPAL-CLIENT-SECRET>>";

// create a new sandbox environment
$environment = new SandboxEnvironment($clientId, $clientSecret);

// create a new client
$client = new PayPalClient($environment);

Create a client with production environment :

// import namespace
use PayPal\Http\Environment\ProductionEnvironment;
use PayPal\Http\PayPalClient;

// client id and client secret retrieved from PayPal
$clientId = "<<PAYPAL-CLIENT-ID>>";
$clientSecret = "<<PAYPAL-CLIENT-SECRET>>";

// create a new sandbox environment
$environment = new ProductionEnvironment($clientId, $clientSecret);

// create a new client
$client = new PayPalClient($environment);

INFO: head over to the extensive documentation.

Usage

Create an Order

// Import namespace
use PayPal\Checkout\Requests\OrderCreateRequest;
use PayPal\Checkout\Orders\AmountBreakdown;
use PayPal\Checkout\Orders\Item;
use PayPal\Checkout\Orders\Order;
use PayPal\Checkout\Orders\PurchaseUnit;

// Create a purchase unit with the total amount
$purchase_unit = new PurchaseUnit(AmountBreakdown::of('100.00'));

// Create & add item to purchase unit
$purchase_unit->addItem(Item::create('Item 1', '100.00', 'USD', 1));

// Create a new order with intent to capture a payment
$order = new Order();

// Add a purchase unit to order
$order->addPurchaseUnit($purchase_unit);

// Create an order create http request
$request = new OrderCreateRequest($order);

// Send request to PayPal
$response = $client->send($request);

// Parse result
$result = json_decode((string) $response->getBody());
echo $result->id; // id of the created order
echo $result->intent; // CAPTURE
echo $result->status; // CREATED

INFO: head over to the extensive documentation.

Capture an Order

// Import namespace
use PayPal\Checkout\Requests\OrderCaptureRequest;

// Create an order capture http request
$request = new OrderCaptureRequest($order_id);

// Send request to PayPal
$response = $client->send($request);

// Parse result
$result = json_decode((string) $response->getBody());
echo $result->id; // id of the captured order
echo $result->status; // CAPTURED

INFO: head over to the extensive documentation.

Changelog

Please see the changelog for more information on what has changed recently.

Contributing

Please see CONTRIBUTING.md for details and a todo list.

Security

If you discover any security related issues, please email author instead of using the issue tracker.

Credits

License

license. Please see the Licence for more information.

Tests Latest Stable Version Maintainability Total Downloads License

paypal-checkout-sdk's People

Contributors

ankurk91 avatar joel-loycom avatar the-dijkstra avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

paypal-checkout-sdk's Issues

Recurring payments

First of, thank you for your work.
I would like to know if this repo supports recurring PayPal payment, such as subscriptions etc.

Add advanced usage docs

Tasks

  • add missing docs for api reference
  • add docs for usage with laravel
  • add docs for advanced usage

using floats for currency based applications is a bad idea

tldr; never use floats for money/currency applcations/libraries.

Floats introduce imprecision. For financial transactions you never want imprecision.
Reference: https://dzone.com/articles/never-use-float-and-double-for-monetary-calculatio#:~:text=Float%20and%20double%20are%20bad,use%20them%20for%20monetary%20calculations.&text=All%20floating%20point%20values%20that,it%20is%20in%20the%20memory.

How to fix, use Zero-Decimal currency format

Zero-decimal currencies

All API requests expect amounts to be provided in a currency’s smallest unit. For example, to charge 10 USD, provide an amount value of 1000 (i.e., 1000 cents).

For zero-decimal currencies, still provide amounts as an integer but without multiplying by 100. For example, to charge ¥500, provide an amount value of 500.

Reference: https://stripe.com/docs/currencies

Get more clarity on what to do after order create

After I create order, what next step should I do? Isn't it should generate approval_link? After order create step I get this:

{
  "create_time": "2023-02-28T07:46:30Z",
  "id": "18545950ND137401U",
  "intent": "CAPTURE",
  "links": [
    {
      "href": "https://api.sandbox.paypal.com/v2/checkout/orders/18545950ND137401U",
      "method": "GET",
      "rel": "self"
    },
    {
      "href": "https://www.sandbox.paypal.com/checkoutnow?token=18545950ND137401U",
      "method": "GET",
      "rel": "approve"
    },
    {
      "href": "https://api.sandbox.paypal.com/v2/checkout/orders/18545950ND137401U",
      "method": "PATCH",
      "rel": "update"
    },
    {
      "href": "https://api.sandbox.paypal.com/v2/checkout/orders/18545950ND137401U/capture",
      "method": "POST",
      "rel": "capture"
    }
  ],
  "purchase_units": [
    {
      "amount": {
        "breakdown": {
          "item_total": {
            "currency_code": "EUR",
            "value": "10.00"
          }
        },
        "currency_code": "EUR",
        "value": "10.00"
      },
      "items": [
        {
          "category": "DIGITAL_GOODS",
          "description": "",
          "name": "Invoice PRF-15",
          "quantity": "1",
          "unit_amount": {
            "currency_code": "EUR",
            "value": "10.00"
          }
        }
      ],
      "payee": {
        "email_address": "*****",
        "merchant_id": "AZUR3*******"
      },
      "reference_id": "default"
    }
  ],
  "status": "CREATED"
}

Where else to go? "Capture an Order" step possible only after customer approves payment. But where is the link for approval?

Allow to set additional parameters to PurchaseUnit

According to paypal docs, the order API allow us to set shipping on purchase_units, but the PurchaseUnit class does not have any method to set shipping, there must be some methods which would allow to set custom properties to the entity.

There are many other properties like - description, custom_id etc, which could be helpful to developers.

https://developer.paypal.com/docs/api/orders/v2/#definition-purchase_unit_request

This applies to other classes as well, all of there classes should allow to set additional body which would be merged with main array by toArray() method.

Thoughts?

sdk headers causing vcr tests to fail when change in php version

VCR is a PHP library used to mock requests to third-party APIs.

if you are using VCR for your project to mock request to PayPal using Http Paypal Client the request will include some extra headers :

    /**
     * Inject Paypal SDK headers into the request.
     *
     * @return \GuzzleHttp\Psr7\Request
     */
    public function injectSdkHeaders(Request $request)
    {
        return $request->withHeader('sdk_name', 'Checkout SDK')
                    ->withHeader('sdk_version', '1.0.0')
                    ->withHeader('sdk_tech_stack', 'PHP '.PHP_VERSION);
    }

as you see the sdk_tech_stack header is injecting the runtime PHP version. wich is causing VCR tests to fail when using different environments to run tests (ex: Local running on PHP 7.4.16, Github action running on PHP 7.4.18)

a quick fix for this would be to detect if the environment is a sandbox environment and not inject those headers.

Allow guzzlehttp/psr7 v2.0

Is your feature request related to a problem? Please describe.
Allow guzzle/psr7 v2.0, along with v1.6

Describe the solution you'd like
i dont see upgrade guide on their repo, it should be an easy upgrade

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Additional context
guzzlehttp/guzzle v7.3 already support both versions

Feature: Add Laravel service provider

It would be great to have Laravel support out of the box.
Here is an example of service provider

<?php

namespace App\Providers;

use Illuminate\Container\Container;
use Illuminate\Support\ServiceProvider;
use PayPal\Checkout\Http\PayPalClient;
use PayPal\Checkout\Environment\SandboxEnvironment;
use PayPal\Checkout\Environment\ProductionEnvironment;
use PayPal\Checkout\Environment\PayPalEnvironment;

class PayPalServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind(PayPalEnvironment::class, function (Container $app) {
            $clientId = config('paypal.client_id');
            $clientSecret = config('paypal.client_secret');

            if (config('paypal.sandbox')) {
                return new SandboxEnvironment($clientId, $clientSecret);
            }

            return new ProductionEnvironment($clientId, $clientSecret);
        });

        $this->app->singleton(PayPalClient::class, static function (Container $app) {
            return new PayPalClient($app->make(PayPalEnvironment::class));
        });
    }
}

The provider still need to publish the config file.

Here is the example of config file

<?php

// https://developer.paypal.com

return [
    'sandbox' => (bool) env('PAYPAL_SANDBOX', true),
    'client_id' => env('PAYPAL_CLIENT_ID'),
    'client_secret' => env('PAYPAL_CLIENT_SECRET'),
];

Now developers can type hint the PayPalClient class in their controller methods and Laravel container will resolve the correct class automatically.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.