Integrate Checkout

Integrate PayPal Checkout for online payments

SDKCurrentStandardLast updated: September 30th 2021, @ 5:56:39 pm


Know before you code

  • This integration sets up online payment options using the PayPal JavaScript SDK, which presents relevant payment options to your buyers.
  • Complete the steps in Get started to get the following sandbox account information from the Developer Dashboard:

    • Email ID and password of a sandbox Personal account, to log in and test a checkout purchase.
    • Sandbox client ID of a REST app.

      Tip: Note the sandbox Business account the app corresponds to. You'll need the email ID and password for that account when you test the integration.

  • (UK merchants) Credit is a regulated activity in the UK. Before integrating a PayPal Credit button, you must be authorized to act as a credit broker and have a credit agreement with PayPal. For more information, contact business customer support through paypal.com or by calling 0800 358 7929.

Technical flow

PayPal Checkout integration technical flow

  1. You add the payment buttons to your web page.
  2. Your buyer clicks a button.
  3. The button calls the PayPal Orders API to set up a transaction.
  4. The button launches the PayPal Checkout experience.
  5. The buyer approves the payment.
  6. The button calls the PayPal Orders API to finalize the transaction.
  7. You show a confirmation message to your buyer.

1. Add payment buttons

To accept payments on your website, add the PayPal JavaScript SDK code to your checkout page.

Sample JavaScript SDK code

This sample code adds payment buttons to your website that capture the payment immediately. If you need to store the resulting transaction or other order details in a server, see the server-side instructions that follow this sample code.

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Ensures optimal rendering on mobile devices -->
    <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <!-- Optimal Internet Explorer compatibility -->
  </head>

  <body>
    <!-- Include the PayPal JavaScript SDK; replace "test" with your own sandbox Business account app client ID -->
    <script src="https://www.paypal.com/sdk/js?client-id=test&currency=USD"></script>

    <!-- Set up a container element for the button -->
    <div id="paypal-button-container"></div>

    <script>
      paypal.Buttons({

        // Sets up the transaction when a payment button is clicked
        createOrder: function(data, actions) {
          return actions.order.create({
            purchase_units: [{
              amount: {
                value: '77.44' // Can reference variables or functions. Example: `value: document.getElementById('...').value`
              }
            }]
          });
        },

        // Finalize the transaction after payer approval
        onApprove: function(data, actions) {
          return actions.order.capture().then(function(orderData) {
            // Successful capture! For dev/demo purposes:
                console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                var transaction = orderData.purchase_units[0].payments.captures[0];
                alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

            // When ready to go live, remove the alert and show a success message within this page. For example:
            // var element = document.getElementById('paypal-button-container');
            // element.innerHTML = '';
            // element.innerHTML = '<h3>Thank you for your payment!</h3>';
            // Or go to another URL:  actions.redirect('thank_you.html');
          });
        }
      }).render('#paypal-button-container');

    </script>
  </body>
</html>

Add and modify the code

  1. Copy the sample JavaScript SDK code and paste it into the code of your checkout page. This sample is already optimized for performance, but for more advanced considerations see JavaScript SDK performance optimization.
  2. In the SDK src URL, replace the default test value with your own sandbox client ID from one of your REST apps, so when testing, the payments will be sent there. Note which sandbox Business account corresponds to the REST app you are using.
  3. You can include additional query string parameters to override the default values the PayPal JavaScript SDK uses. Review the JavaScript SDK reference to learn more. Example: currency defaults to USD.
  4. The JavaScript SDK has createOrder and onApprove callbacks with actions that call the Orders REST API to set up and capture payments.
  5. (Optional) If you need to do any server-side operations at order creation time or after payment, such as storing the completed PayPal transaction ID or other order details in your database, a server-based API integration is the most robust solution.

    • Make two routes on your server: one for creating an order and one for capturing on approval. These routes should return JSON data only and no HTML or text. Before returning data, the capture call should store the resulting payment details in your database (particularly the purchase_units[0].payments.captures[0].id PayPal transaction ID) and validate the expected cart amount total.
    • Use these two server routes from the createOrder and onApprove callbacks. See the demo code sample which uses the browser Fetch API for the communication.
  6. You can include additional parameters during order creation. See the Orders v2 API reference for additional parameters. For example, extend purchase_units to include item descriptions and quantities that are part of this transaction:

        createOrder: function(data, actions) {
          return actions.order.create({
             "purchase_units": [{
                "amount": {
                  "currency_code": "USD",
                  "value": "100",
                  "breakdown": {
                    "item_total": {  /* Required when including the `items` array */
                      "currency_code": "USD",
                      "value": "100"
                    }
                  }
                },
                "items": [
                  {
                    "name": "First Product Name", /* Shows within upper-right dropdown during payment approval */
                    "description": "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */
                    "unit_amount": {
                      "currency_code": "USD",
                      "value": "50"
                    },
                    "quantity": "2"
                  },
                ]
              }]
          });
        },
    

    Other useful purchase unit parameters include:

    • A unique invoice_id that hasn't been used for a previously-completed transaction to identify the order for accounting purposes and to prevent duplicate payments.
    • A custom_id value of your choice for your system or own reference. This value is not indexed or visible to the buyer.
  7. (Optional) Customize the look and feel of your buttons.

Tips:

  • Feature the PayPal button on all pages that initiate checkout.
  • Show PayPal alongside all other acceptance marks (including cards, split tender, and buy online, pickup in-store) giving it equal prominence and function for your buyers.
  • When your buyer returns to your site from PayPal, they should be able to pay and complete their order in no more than two steps.

Step result

The payment buttons display on your website. You can now test purchases.

2. Test purchases

Test a PayPal purchase in the sandbox to see the checkout user experience and confirm money reaches the receiving Business account.

Test a purchase as a buyer

  1. On your checkout page, click the PayPal button.
  2. Log in using one of your sandbox Personal accounts.
  3. Within the PayPal checkout window, note the purchase amount.
  4. Click through and approve the purchase with the final Pay Now button. This should close the PayPal window and return to your page, where a message indicates the transaction completed.

Confirm the money entered the merchant account

  1. Log in to https://www.sandbox.paypal.com/ using the sandbox Business account that received the payment. Remember that the SDK src now uses a sandbox client ID from one of your own REST apps, and not the default test ID.
  2. In Recent Activity, confirm that the money, minus any fees, was received by this sandbox Business account.
  3. Log out of the account.

Next steps

See also

Integration options

Reference