This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

📣 Join our live AMA on the Future of Page Builders with Brizy's CEO! Register Now →

PayPal Integration in PHP: How to Automate Online Payments Within Just a Few Minutes

Updated on December 13, 2021

7 Min Read
paypal integration in php

Being an online store owner, you can integrate PayPal in PHP applications within minutes. You can accept payments via plugins, addons, extensions, or manually via the framework-based applications. With PayPal Integrated in PHP application, you can also find built-in PHP libraries and composer packages to cut short your development time.

Payment Gateway Integration in PHP – A Quick Checklist

I will go into the details of PayPal Integration in PHP payment gateway, but here is a quick list of steps that you need to take to set up PayPal for your PHP applications

  1. Start by getting a PayPal developer account and get sandbox credentials. This is essential for testing out the integration.
  2. Create the proper directory structure for the integration.
  3. Start by creating the Payment.php file
  4. Create the payment_form.php for the form that the user could use to enter Paypal related information.
  5. Test the integration to see if everything is working as it should.

Host Your PHP Apps with Us for 10x Faster Performance

Don’t Let Your Customers Run Away With The Downtimes. Deploy With Us Today!

What is PayPal?

PayPal is an internationally acclaimed payment processing company that offers secured and easy to use online payment methods. You can easily register your credit/debit card(s) with a PayPal account and can make your online payments effortlessly. It can be used by a variety of businesses including freelancers, digital agencies ecommerce store owners and more.

Some of the best features that PayPal offers include: 

  • Accept Credit Cards
  • Online invoicing 
  • Buyer and Seller accounts
  • Shopping cart 
  • Mobile Payments
  • International Money transfer

How PayPal Works?

As mentioned earlier, using PayPal is quite easy. You just have to follow three steps to make an online payment successfully. 

1- Choose PayPal to checkout

2- Login to your account

3- Confirm your payment and pay.

It really looks like an easy process. However, if you are working with any software product and need to accept recurring or one-time payments, then you need to do a bit more for it. You will need certain API keys to securely integrate PayPal in PHP applications, which requires a bit of technical knowledge.

So, here are the steps that can help you to integrate PayPal in PHP applications.

PayPal Integration in PHP Websites

Let’s learn how to integrate PayPal in PHP websites within just a few steps:

Step – 1 Create a PayPal Account and Get Sandbox Credentials

Create a PayPal account and get your sandbox credentials from your developer account. You will get credentials for both business and personal accounts. 

Then, you will need a testing email to accept or send payments. Because being in a testing environment, you cannot use live emails to accept online payments.

Step – 2 Create PHP files to add Code

Now, create a directory folder to add PHP files. Check the structure in the image given below. 

As you can see, there are different files in the above image. I’ll define the code that you need to put in each of the files. Since I’ve deployed the application on Cloudways, you must have an account to upload files. Signup and launch the PHP server then connect to FileZilla via SFTP and upload files. 

Let’s come back to the code. After creating the directory, you must install Omnipay via composer. Login to the SSH account and navigate to your application. Run the following command.

Omnipay is a payment processing library for PHP. It has been outlined, based on ideas from Dynamic Merchant, also involving experience implementing dozens of gateways for CI Merchant. It includes a clear and steady API, and is completely unit tried, and indeed comes with a case application to induce you begun

composer require omnipay/PayPal

This will install the package and we can configure PayPal easily. Omnipay allows you to configure the following  PayPal options:

  • PayPal_Express (PayPal Express Checkout)
  • PayPal_ExpressInContext (PayPal Express In-Context Checkout)
  • PayPal_Pro (PayPal Website Payments Pro)
  • PayPal_Rest (PayPal Rest API)

I’ll be using PayPal Express with Omnipay. After the installation, you will see the composer.json file with the following code. 

{

    "name": "root/phpPayPal",

    "authors": [

        {

            "name": "Ahmed Khan",

            "email": "[email protected]"

        }

    ],

    "require": {

        "league/omnipay": "^3.0",

        "omnipay/PayPal": "^3.0"

    }

}

If you are working locally, you can also create this file and add the above-mentioned code manually then run `composer install` to add Omnipay in the project.

Step – 3 Create Payment.php file

Create a folder called src and add a file, payment.php in it. Add the following code in the file and save it. The code contains comments that are self explanatory.

<?php

namespace Payment;
use Omnipay\Omnipay;
class Payment

{

   /**

    * @return mixed

    */

   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;

   }

   /**

    * @param array $parameters

    * @return mixed

    */

   public function purchase(array $parameters)

   {

       $response = $this->gateway()
           ->purchase($parameters)
           ->send();

       return $response;

   }

   /**

    * @param array $parameters

    */

   public function complete(array $parameters)

   {

       $response = $this->gateway()
           ->completePurchase($parameters)
           ->send();

       return $response;
   }

   /**

    * @param $amount

    */

   public function formatAmount($amount)

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

   /**

    * @param $order

    */

   public function getCancelUrl($order = "")

   {
       return $this->route('http://phpstack-275615-1077014.cloudwaysapps.com/cancel.php', $order);
   }

   /**

    * @param $order

    */

   public function getReturnUrl($order = "")

   {

       return $this->route('http://phpstack-275615-1077014.cloudwaysapps.com/return.php', $order);
   }

   public function route($name, $params)

   {
       return $name; // ya change hua hai
   }
}

Now, you have to add Omnipay namespace to use the library functions. You can add it on top using Omnipay\Omnipay.

Now, declare the PayPal payment mode you will use to accept  payments. For this tutorial, I’m using PayPal Express. Sometimes you need to add API credentials like username, password, and signature. You can find these credentials in Tools -> All Tools -> Integrate PayPal tab -> API Credentials. Check the screenshot given below. 

You can now start using prebuilt PayPal methods for purchase, amount format, return URL, etc. Don’t forget to set this line to true for testing the gateway.

$gateway->setTestMode(true);

Step – 4 Create payment_form.php file

The next step is to create a form to submit payments to PayPal. This form includes the following fields.

<?php

include "vendor/autoload.php";
include "src/Payment/payment.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">
   <meta http-equiv="X-UA-Compatible" content="ie=edge">
   <title>Pay with PayPal</title>

   <!-- Latest compiled and minified CSS -->

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">


   <!-- Optional theme -->

   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

   <!-- Latest compiled and minified JavaScript -->

   <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

</head>

<body>

   <div class="container">
       <div class="row">
           <div class="col-md-6">

               <form class="form-horizontal" method="POST" action="https://www.sandbox.PayPal.com/cgi-bin/webscr ">
                   <fieldset>

                       <!-- Form Name -->
                       <legend>Pay with PayPal</legend>
                       <!-- Text input-->

                       <div class="form-group">
                           <label class="col-md-4 control-label" for="amount">Payment Amount</label>
                           <div class="col-md-4">
                               <input id="amount" name="amount" type="text" placeholder="amount to pay" class="form-control input-md" required="">
                               <span class="help-block">help</span>
                           </div>
                       </div>

                       <input type='hidden' name='business' value='[email protected]'>
                       <input type='hidden' name='item_name' value='Camera'>
                       <input type='hidden' name='item_number' value='CAM#N1'>
                       <!--<input type='hidden' name='amount' value='10'>-->
                       <input type='hidden' name='no_shipping' value='1'>
                       <input type='hidden' name='currency_code' value='USD'>
                       <input type='hidden' name='notify_url' value='<?php echo $payment->route("notify", "") ?>'>
                       <input type='hidden' name='cancel_return' value='<?php echo $payment->route("http://phpstack-275615-1077014.cloudwaysapps.com/cancel.php", "") ?>'>
                       <input type='hidden' name='return' value='<?php echo $payment->route("return", "http://phpstack-275615-1077014.cloudwaysapps.com/return.php") ?>'>
                       <input type="hidden" name="cmd" value="_xclick">

                       <!-- Button -->

                       <div class="form-group">
                           <label class="col-md-4 control-label" for="submit"></label>
                           <div class="col-md-4">
                               <button id="submit" name="pay_now" class="btn btn-danger">Pay With PayPal</button>
                           </div>
                       </div>
                   </fieldset>
               </form>
           </div>
       </div>
   </div>
</body>


</html>

The above form will show the basic input field which asks the desired amount to process. When you will submit the amount, you will be redirected to the PayPal sandbox site to login. You can log in with the test credentials which I’ve shown above in the first image of this tutorial.

Testing PayPal for Payment Submission.

At this stage, all the files should be uploaded to the Cloudways PHP web hosting server. Find the application URL in Application Access Details page. The URL will be like: 

http://phpstack-275615-1077014.cloudwaysapps.com/payment_form.php

You will see the basic form as the one shown below:

Enter the amount and log in to your testing account with test credentials, for instance: 

Email: [email protected]

Password: #qYxx$x4

This will take some time to process. Once the process is completed, you will see the Pay Now window. Click it and the amount will be paid from your testing account.

Check the demo below: 

I’ve also set the redirect URL. If you want to cancel the payment, just click the cancel link at the bottom, and you will be redirected to the cancel page. Similarly, you can create different pages like success, notify, etc. using the same practice.

Payment Cancelation (cancel.php)

When a buyer cancels a payment, they typically return to the parent page. on the other hand, You can instead use the onCancel function to show the cancellation page or get redirected to the shopping cart.

paypal.Buttons({
  onCancel: function (data) {
    // Show a cancel page, or return to the cart
  }
}).render('#paypal-button-container');

Setup PayPal Auto-Return and Payment Transfer

Follow the steps

  1. Log into your PayPal account (Business)
  2. On “My Account” TAB, click on the “Profile”
  3. Click Website Payments under “Product & Services” on the left of the page.
  4. Click “Update” next to “Website preferences.”
  5. Click On under “Auto Return”.
  6. Now under the Hosted Payment Services, click “Website Payments Preferences”
  7. Select the radio button “Auto Return,” and enter redirect URL in the URL field
    Also, select the radio button “Payment data transfer.”
  8. Click “Save”

Host PHP Websites with Ease [Starts at $10 Credit]

  • Free Staging
  • Free backup
  • PHP 8.0
  • Unlimited Websites

TRY NOW

Final Words

In this tutorial, I have demonstrated the process how you can integrate PayPal in PHP application. You can extend it to more complex usage like online shops etc. You can also save product payments in the database with status. PayPal carries out a strong checkup on accounts for any fraud activities so I would suggest you not to use it for any bogus payments otherwise, your account will be banned.

If you still have some more questions regarding this article, please feel free to write them down below in the comments section.

Share your opinion in the comment section. COMMENT NOW

Share This Article

Shahroze Nawaz

Shahroze is a PHP Community Manager at Cloudways - A Managed PHP Hosting Platform. Besides his work life, he loves movies and travelling.

×

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Thankyou for Subscribing Us!

×

Webinar: How to Get 100% Scores on Core Web Vitals

Join Joe Williams & Aleksandar Savkovic on 29th of March, 2021.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

Want to Experience the Cloudways Platform in Its Full Glory?

Take a FREE guided tour of Cloudways and see for yourself how easily you can manage your server & apps on the leading cloud-hosting platform.

Start my tour

CYBER WEEK SAVINGS

  • 0

    Days

  • 0

    Hours

  • 0

    Mints

  • 0

    Sec

GET OFFER

For 4 Months &
40 Free Migrations

For 4 Months &
40 Free Migrations

Upgrade Now