Placeholder canvas

How to Automate Online Payments in Minutes with PayPal Integration in PHP

As an online store owner, you can seamlessly PayPal integration into PHP applications within a matter of minutes. This PayPal integration allows you to accept payments through various methods such as plugins, addons, extensions, or manually through framework-based applications. By incorporating PayPal into your PHP application, you gain access to built-in PHP libraries and composer packages, significantly reducing your development time.

What is PayPal?

Paypal developer - PayPal Integration in PHP

PayPal is a globally recognized payment processing company that offers secure and user-friendly online payment solutions. You can easily link your credit/debit cards to a PayPal account, streamlining your online transactions. PayPal caters to a wide range of businesses, including freelancers, digital agencies, e-commerce store owners, and more.

Some notable features offered by PayPal include:

  • Acceptance of Credit Cards
  • Online Invoicing
  • Buyer and Seller Accounts
  • Shopping Cart Integration
  • Mobile Payments
  • International Money Transfers

How PayPal Works?

PayPal integrate

Using PayPal is a straightforward process involving three simple steps to successfully make an online payment:

  1. During checkout, choose PayPal as your form of payment.
  2. Log in to your PayPal account.
  3. Verify your payment information, then finish the purchase.

While this process seems uncomplicated, integrating PayPal into PHP applications for accepting recurring or one-time payments may require additional steps, including the setup of API keys, which necessitates some technical expertise.

Here are the steps to integrate PayPal into PHP applications:

Prerequisites

I will delve into the details of PayPal Integration in PHP’s payment gateway shortly. However, let’s begin with a quick checklist of the steps required to set up PayPal for your PHP 

applications:

  1. Start by acquiring a PayPal developer account and obtain sandbox credentials. This step is crucial for testing the integration.
  2. Create the appropriate directory structure for the integration.
  3. Initiate by creating the “Payment.php” file.
  4. Develop the “payment_form.php” file, which provides users with a form to input PayPal-related information.
  5. Integrate the system thoroughly to make sure everything works as it should.

PayPal Integration in PHP Websites

Let’s explore how to integrate PayPal into PHP websites in just a few straightforward steps:

Step 1: Create a PayPal Account and Obtain Sandbox Credentials

Begin by creating a PayPal account and obtain sandbox credentials from your developer account. These credentials are available for both business and personal accounts. Additionally, you’ll need a testing email address for processing payments in a testing environment.

Step 2: To add code, create PHP files.

Now, establish a directory folder to house your PHP files. The structure is depicted in the provided image.

Within this directory, install Omnipay using Composer. Access your SSH account, navigate to your application, and execute the following command:

composer requires omnipay/PayPal

Omnipay is a PHP payment processing library that streamlines payment gateway integration. It offers a clear API and supports various PayPal options, including:

  • PayPal Express
  • PayPal Express In-Context Checkout
  • PayPal Website Payments Pro
  • PayPal Rest API

I’ll be combining Omnipay with PayPal Express. You will find the composer.json file with the following code after the installation. 

{

    "name": "root/phpPayPal",

    "authors": [

        {

            "name": "Demo",

            "email": "[email protected]"

        }

    ],

    "require": {

        "league/omnipay": "^3.0",

        "omnipay/PayPal": "^3.0"

    }

}

Step 3: Create the Payment.php File

Create a “src” folder and add a file named “payment.php” within it. Insert the following code into the file, which includes explanatory comments:

<?php

namespace Payment;

use Omnipay\Omnipay;

class Payment

{

    /**

     * Create and configure the payment gateway.

     *

     * @return \Omnipay\Common\GatewayInterface

     */

    public function gateway()

    {

        $gateway = Omnipay::create('PayPal_Express');

        $gateway->setUsername("[email protected]");

        $gateway->setPassword("ARySNgUCvyU9tEBp-zsd0WbbNO_7Nxxxxoi3xxxxh2cTuDxRh7xxxxVu9W5ZkIBGYqjqfzHrjY3wta");

        $gateway->setSignature("EOEwezsNWMWQM63xxxxxknr8QLoAOoC6lD_-kFqjgKxxxxxwGWIvsJO6vP3syd10xspKbx7LgurYNt9");

        $gateway->setTestMode(true);

        return $gateway;

    }

    /**

     * Process a purchase transaction.

     *

     * @param array $parameters

     * @return \Omnipay\Common\Message\ResponseInterface

     */

    public function purchase(array $parameters)

    {

        $response = $this->gateway()

            ->purchase($parameters)

            ->send();

        return $response;

    }

    /**

     * Complete a purchase transaction.

     *

     * @param array $parameters

     * @return \Omnipay\Common\Message\ResponseInterface

     */

    public function complete(array $parameters)

    {

        $response = $this->gateway()

            ->completePurchase($parameters)

            ->send();

        return $response;

    }

    /**

     * Format an amount with two decimal places.

     *

     * @param float $amount

     * @return string

     */

    public function formatAmount($amount)

    {

        return number_format($amount, 2, '.', '');

    }

    /**

     * Get the cancel URL for a given order.

     *

     * @param string $order

     * @return string

     */

    public function getCancelUrl($order = "")

    {

        return $this->route('https://demo.example.com/cancel.php', $order);

    }

    /**

     * Get the return URL for a given order.

     *

     * @param string $order

     * @return string

     */

    public function getReturnUrl($order = "")

    {

        return $this->route('https://demo.example.com/return.php', $order);

    }

    /**

     * Generate a URL for a given route and parameters.

     *

     * @param string $name

     * @param mixed $params

     * @return string

     */

    public function route($name, $params)

    {

        return $name; // URL generation logic can be added here

    }

}

This code sets up the PayPal payment gateway with Omnipay and includes essential configuration parameters.

Step 4: Create the payment_form.php File

The next step involves creating a form for users to submit payments to PayPal. This form includes various fields for payment information. The “payment_form.php” file’s source code is shown below:

<?php

include "vendor/autoload.php";

use Payment\Payment;

$payment = new Payment();

?>

<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>PayPal JS SDK Demo</title>

</head>

<body>

  <div id="paypal-button-container"></div>

  <script

    data-sdk-integration-source="integrationbuilder_sc"

    src="https://www.paypal.com/sdk/js?client-id=<test>>&components=buttons&enable-funding=venmo,paylater"></script>

  <script>

    const FUNDING_SOURCES = [

      // EDIT FUNDING SOURCES

        paypal.FUNDING.PAYPAL,

        paypal.FUNDING.PAYLATER,

        paypal.FUNDING.VENMO,

        paypal.FUNDING.CARD

    ];

    FUNDING_SOURCES.forEach(fundingSource => {

      paypal.Buttons({

        fundingSource,

        style: {

          layout: 'vertical',

          shape: 'rect',

          color: (fundingSource == paypal.FUNDING.PAYLATER) ? 'gold' : '',

        },

        createOrder: async (data, actions) => {

          try {

            const response = await fetch("https://localhost:9597/orders", {

              method: "POST"

            });

            const details = await response.json();

            return details.id;

          } catch (error) {

            console.error(error);

            // Handle the error or display an appropriate error message to the user

          }

        },

        onApprove: async (data, actions) => {

          try {

            const response = await fetch(`https://localhost:9597/orders/${data.orderID}/capture`, {

              method: "POST"

            });

            const details = await response.json();

            // Three cases to handle:

            //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()

            //   (2) Other non-recoverable errors -> Show a failure message

            //   (3) Successful transaction -> Show confirmation or thank you message

            // This example reads a v2/checkout/orders capture response, propagated from the server

            // You could use a different API or structure for your 'orderData'

            const errorDetail = Array.isArray(details.details) && details.details[0];

            if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {

              return actions.restart();

              // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/

            }

            if (errorDetail) {

              let msg = 'Sorry, your transaction could not be processed.';

              msg += errorDetail.description ? ' ' + errorDetail.description : '';

              msg += details.debug_id ? ' (' + details.debug_id + ')' : '';

              alert(msg);

            }

            // Successful capture! For demo purposes:

            console.log('Capture result', details, JSON.stringify(details, null, 2));

            const transaction = details.purchase_units[0].payments.captures[0];

            alert('Transaction ' + transaction.status + ': ' + transaction.id + 'See console for all available details');

          } catch (error) {

            console.error(error);

            // Handle the error or display an appropriate error message to the user

          }

        },

      }).render("#paypal-button-container");

    })

  </script>

</body>

</html>

This form allows users to input the desired payment amount and redirects them to the PayPal sandbox site for payment processing. It also sets up various hidden input fields with relevant payment details.

Payment Cancellation (cancel.php)

In the event of a payment cancellation, buyers typically return to the parent page. Alternatively, you can implement the onCancel function to display a cancellation page or redirect users to the shopping cart.

paypal.Buttons({

  onCancel: function (data) {

    // Show a cancel page, or return to the cart

  }

}).render('#paypal-button-container');

Conclusion

We’ve explored how to automate online payments in minutes with PayPal integration in PHP. PayPal’s global recognition, security measures, and developer-friendly resources make it an ideal choice for handling online transactions. By following the steps outlined here, you can seamlessly integrate PayPal into your PHP applications and enhance the payment experience for your customers.

To recap, here are the key takeaways:

  • PayPal is a trusted and versatile payment platform suitable for various online businesses.
  • Setting up a PayPal Developer account and sandbox accounts is the first step toward integration.
  • Use the PayPal SDK for PHP and configure your API credentials securely.
  • Implement PayPal payments in your PHP application, and handle payment confirmation.

FAQs PayPal Integration in PHP

Why should I choose PayPal for online payment PayPal integration in my PHP application?

 PayPal offers several compelling reasons for choosing it as your preferred payment gateway for PHP applications. First and foremost, PayPal enjoys global recognition and trust among users, which can enhance the credibility of your online business. It provides robust security measures to protect both businesses and customers, reducing the risk of fraud. Additionally, PayPal is known for its user-friendly payment process, ensuring a smooth and hassle-free experience for your customers. 

How can I test PayPal integration without real transactions?

PayPal offers a sandbox environment for testing, allowing you to create simulated buyer and seller accounts. This enables you to thoroughly test your PHP PayPal integration without processing actual payments, ensuring a smooth experience before going live.

Can I customize the PayPal integration to match my website’s style?

Yes, PayPal allows customization to align the payment experience with your website’s branding. You can add your logo, adjust colors, and even use the REST API to control the entire payment process on your site while benefiting from PayPal’s secure payment processing in the background.

Want faster WordPress?

WordPress Speed Optimization

Try our AWS powered WordPress hosting for free and see the difference for yourself.

No Credit Card Required.

Whitelabel Web Hosting Portal Demo

Launching WordPress on AWS takes just one minute with Nestify.

Launching WooCommerce on AWS takes just one minute with Nestify.