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

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.

Integrating PayPal in PHP

  1. What is PayPal?
  2. How PayPal Works?
  3. PayPal Integration in PHP Websites
    1. Create a PayPal Account and Get Sandbox Credentials
    2. Create PHP files to add Code
    3. Create Payment.php file
    4. Create payment_form.php file
  4. Testing PayPal for Payment Submission
  5. Payment Cancelation (cancel.php)
  6. Setup PayPal Auto-Return and Payment Transfer
  7. Final Words

Host Your PHP Apps with Us for 10x Faster Performance

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

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

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

  1. {
  2. “name”: “root/phpPayPal”,
  3. “authors”: [
  4. {
  5. “name”: “Ahmed Khan”,
  6. “email”: “ahmedkhan_847@hotmail.com”
  7. }
  8. ],
  9. “require”: {
  10. “league/omnipay”: “^3.0”,
  11. “omnipay/PayPal”: “^3.0”
  12. }
  13. }

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.

  1. <?php
  2. namespace Payment;
  3. use Omnipay\Omnipay;
  4. class Payment
  5. {
  6. /**
  7. * @return mixed
  8. */
  9. public function gateway()
  10. {
  11. $gateway = Omnipay::create(‘PayPal_Express’);
  12. $gateway->setUsername(“sb-7j4hl606677@personal.example.com”);
  13. $gateway->setPassword(“ARySNgUCvyU9tEBp-zsd0WbbNO_7Nxxxxoi3xxxxh2cTuDxRh7xxxxVu9W5ZkIBGYqjqfzHrjY3wta”);
  14. $gateway->setSignature(“EOEwezsNWMWQM63xxxxxknr8QLoAOoC6lD_-kFqjgKxxxxxwGWIvsJO6vP3syd10xspKbx7LgurYNt9”);
  15. $gateway->setTestMode(true);
  16. return $gateway;
  17. }
  18. /**
  19. * @param array $parameters
  20. * @return mixed
  21. */
  22. public function purchase(array $parameters)
  23. {
  24. $response = $this->gateway()
  25. ->purchase($parameters)
  26. ->send();
  27. return $response;
  28. }
  29. /**
  30. * @param array $parameters
  31. */
  32. public function complete(array $parameters)
  33. {
  34. $response = $this->gateway()
  35. ->completePurchase($parameters)
  36. ->send();
  37. return $response;
  38. }
  39. /**
  40. * @param $amount
  41. */
  42. public function formatAmount($amount)
  43. {
  44. return number_format($amount, 2, ‘.’, ”);
  45. }
  46. /**
  47. * @param $order
  48. */
  49. public function getCancelUrl($order = “”)
  50. {
  51. return $this->route(‘http://phpstack-275615-1077014.cloudwaysapps.com/cancel.php’, $order);
  52. }
  53. /**
  54. * @param $order
  55. */
  56. public function getReturnUrl($order = “”)
  57. {
  58. return $this->route(‘http://phpstack-275615-1077014.cloudwaysapps.com/return.php’, $order);
  59. }
  60. public function route($name, $params)
  61. {
  62. return $name; // ya change hua hai
  63. }
  64. }

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.

  1. $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.

  1. <?php
  2. include “vendor/autoload.php”;
  3. include “src/Payment/payment.php”;
  4. use Payment\Payment;
  5. $payment = new Payment;
  6. // ?>
  7. <!DOCTYPE html>
  8. <html lang=”en”>
  9. <head>
  10. <meta charset=”UTF-8″>
  11. <meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
  12. <meta http-equiv=”X-UA-Compatible” content=”ie=edge”>
  13. <title>Pay with PayPal</title>
  14. <!– Latest compiled and minified CSS –>
  15. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css” integrity=”sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u” crossorigin=”anonymous”>
  16. <!– Optional theme –>
  17. <link rel=”stylesheet” href=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css” integrity=”sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp” crossorigin=”anonymous”>
  18. <!– Latest compiled and minified JavaScript –>
  19. <script src=”https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js” integrity=”sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa” crossorigin=”anonymous”></script>
  20. </head>
  21. <body>
  22. <div class=”container”>
  23. <div class=”row”>
  24. <div class=”col-md-6″>
  25. <form class=”form-horizontal” method=”POST” action=”https://www.sandbox.PayPal.com/cgi-bin/webscr “>
  26. <fieldset>
  27. <!– Form Name –>
  28. <legend>Pay with PayPal</legend>
  29. <!– Text input–>
  30. <div class=”form-group”>
  31. <label class=”col-md-4 control-label” for=”amount”>Payment Amount</label>
  32. <div class=”col-md-4″>
  33. <input id=”amount” name=”amount” type=”text” placeholder=”amount to pay” class=”form-control input-md” required=””>
  34. <span class=”help-block”>help</span>
  35. </div>
  36. </div>
  37. <input type=’hidden’ name=’business’ value=’sb-7j4hl606677@personal.example.com’>
  38. <input type=’hidden’ name=’item_name’ value=’Camera’>
  39. <input type=’hidden’ name=’item_number’ value=’CAM#N1′>
  40. <!–<input type=’hidden’ name=’amount’ value=’10’>–>
  41. <input type=’hidden’ name=’no_shipping’ value=’1′>
  42. <input type=’hidden’ name=’currency_code’ value=’USD’>
  43. <input type=’hidden’ name=’notify_url’ value=”<?php echo $payment->route(“notify”, “”) ?>’>
  44. <input type=’hidden’ name=’cancel_return’ value=”<?php echo $payment->route(“http://phpstack-275615-1077014.cloudwaysapps.com/cancel.php”, “”) ?>’>
  45. <input type=’hidden’ name=’return’ value=”<?php echo $payment->route(“return”, “http://phpstack-275615-1077014.cloudwaysapps.com/return.php”) ?>’>
  46. <input type=”hidden” name=”cmd” value=”_xclick”>
  47. <!– Button –>
  48. <div class=”form-group”>
  49. <label class=”col-md-4 control-label” for=”submit”></label>
  50. <div class=”col-md-4″>
  51. <button id=”submit” name=”pay_now” class=”btn btn-danger”>Pay With PayPal</button>
  52. </div>
  53. </div>
  54. </fieldset>
  55. </form>
  56. </div>
  57. </div>
  58. </div>
  59. </body>
  60. </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: sb-svrtq668012@personal.example.com

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.

  1. paypal.Buttons({
  2. onCancel: function (data) {
  3. // Show a cancel page, or return to the cart
  4. }
  5. }).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”

Give Your PHP Applications Optimum Web Performance

Host Your PHP Apps With Us & See The Blazing Web Performance Yourself!DEPLOY 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.

“>

nfinitiv

nfinitiv

Our team comprises many who’ve been on the front-line of start-ups. nfinitiv challenges the traditional norms of management consulting, providing quality advisory talent that delivers results by providing high-quality fact-based and analytically rigorous consultancy services to all start-ups at a value for money price point. When it comes to pitch decks analysis, we pride ourselves in our understanding of what VC’s expect and demand because all of our team are made up of advisers, angel investors and VC’s