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

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


Are you planning to start an online business? You will surely love to accept payments from international customers. All you need is a one-stop solution for every payment mode whether you are accepting payments via emails, credit cards or any other medium. Luckily, it’s quite easy these days, because many payment processors are available in the market. You must have the knowledge about PayPal, Stripe, Transfer wise, etc. They are facilitating the payment processes for online shops, digital agencies, freelancers and developers.
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. Moreover, you can also find built-in libraries and composer packages to cut short your development time.
  1. What is PayPal?
  2. How PayPal Works?
  3. PayPal Payment Gateway 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. Final Words
In this article, I will demonstrate how to integrate PayPal in PHP.

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 Payment Gateway 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.
  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.

Final Words

In this tutorial, I have demonstrated how one can integrate PayPal in PHP applications. 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.

Comments

  1. I wish to show thanks to you just for bailing me out of this particular trouble.As a result of checking through the net and meeting techniques that were not productive, I thought my life was done.


    https://ij-ijstartcanon.com/
    https://canon.comijsetups.com/
    https://step-cricut.com/
    https://uswebroot.com/
    https://garmiexpress.com/

    ReplyDelete
  2. Existing without the answers to the difficulties you've sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.

    canon.com/setup
    canon.con/setup
    canon. com/setup
    canon. com/setup
    www.canon.com/ijsetup
    Webroot.com/secure
    Webroot.com/safe

    ReplyDelete
  3. The first name that springs to mind when we discuss the safest forms of online money transactions is PayPal. PayPal is the simplest and safest way to send and receive money from anywhere on the planet.
    Bellen PayPal

    ReplyDelete
  4. I like your all post. You have done really good work. Thank you for the information you provide, it helped me a lot. I hope to have many more entries or so from you.
    Youtube nederland

    ReplyDelete
  5. This comment has been removed by the author.

    ReplyDelete

Post a Comment