TrinityTuts

Paypal Gateway integration in PHP Application

Last updated on November 18th, 2022 at 10:03 am

In this tutorial I will explain to you how we can integrate Paypal Payment Gateway in our PHP Application. If you want to read about other payment gateway integration check out these posts. Integration Paypal payment gateway in web application takes a few minutes. Before we start I hope you have a Paypal account or you can create a PayPal developer account for free.

Live demo:- PayPal payment gateway

Prerequisites

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

PayPal Payment Gateway

Step 1. Before we start integration you can create a PayPal Account and Get Sandbox Credentials. Go to developer.paypal.com and login then after login click on Account menu from the left side of the screen under Sandbox as shown in the below image.

You can create a new account on click on the Create Account button. For sandbox mode, you can not use your actual email.

Step 2. You also need Client Id and Client Secret for payment you can get that from My App & Credentials menu under the dashboard click on the show button to get secret.

Step 3. Now we have to install Paypal PHP SDK you can install plugin using composer.

composer require "paypal/rest-api-sdk-php:*"

Step 4. Now once our plugin is installed after that you need to create a new PHP file and where we can load this plugin and make payment through Paypal. I create an index.php file in which I create a form that simply passes product name and price.

<?php

require_once('vendor/autoload.php');

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Sale;

    if(isset($_POST) && (count($_POST) > 0)){
        $product = $_POST['product'];
        $enter_amount = $_POST['amount'];

        $return = "https://demo.trinitytuts.com/paypal/callback.php";
        $cancel = "https://demo.trinitytuts.com/paypal/canceled.php";
        $currency = 'USD';
            
        $apiContext = new \PayPal\Rest\ApiContext(
            new \PayPal\Auth\OAuthTokenCredential(
                'ATQPCjSAopkGqgqea7ShUok5nlSYaqY5OAl9Td3l9bCBi5F6pC9QgKWkLzZXvkhyVde4Cp2eCxYtSZSo',     // ClientID
                'EBWXI5X8os7IprmNyy94oMeCZhruzJije55Yh5Pv7hUZ5hnCbTsHfr4hiDBz7f0XFvRakf0iuoE1XIkH'      // ClientSecret
            )
        );

        $apiContext->setConfig(
            array(
                'mode' => 'sandbox',
            )
        );
        $payer = new Payer();
        $payer->setPaymentMethod("paypal");

        $item1 = new Item();
        $item1->setName($product)
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setSku("1") // Similar to `item_number` in Classic API
            ->setPrice($enter_amount);
        $itemArr[] = $item1;

        $itemList = new ItemList();
        $itemList->setItems($itemArr);

        $details = new Details();
        $details->setShipping(0)
            ->setTax(0)
            ->setSubtotal($enter_amount);

        $amount = new Amount();
        $amount->setCurrency("USD")
            ->setTotal($enter_amount)
            ->setDetails($details);

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($itemList)
            ->setDescription("Payment description")
            ->setInvoiceNumber(uniqid());

        $redirectUrls = new RedirectUrls();
        $redirectUrls->setReturnUrl("$return?success=true")
            ->setCancelUrl("$cancel?success=false");

        $payment = new Payment();
        $payment->setIntent("sale")
            ->setPayer($payer)
            ->setRedirectUrls($redirectUrls)
            ->setTransactions(array($transaction));

        $request = clone $payment;

        try {
            $payment->create($apiContext);
        }catch (Exception $ex) {
            $error  = $ex;
            echo "<pre>";
            print_r($error);
        }

        $approvalUrl = $payment->getApprovalLink();
        parse_str($approvalUrl, $url);

        header("location:$approvalUrl");
        die;
    }
?>

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

    <title>Paypal PHP integration Example</title>
  </head>
  <body>
    
    <div class="container">
        <h1>Paypal PHP integration Example</h1>
        <form method="post">
            <div class="form-group">
                <label for="exampleInput1">Product</label>
                <input type="text" class="form-control" id="exampleInput1" name="product">
            </div>
            <div class="form-group">
                <label for="exampleInputPassword1">Amount</label>
                <input type="number" name="amount" class="form-control" id="exampleInputPassword1">
            </div>
            <button type="submit" class="btn btn-primary">Submit</button>
        </form>
    </div>

    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    https://code.jquery.com/jquery-3.4.1.slim.min.js
    https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js
    https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js
  </body>
</html>

Step 5. You also need to create a callback.php file which Handel response from Paypal gateway.

<?php

require_once('vendor/autoload.php');

use PayPal\Api\Amount;
use PayPal\Api\Details;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Payer;
use PayPal\Api\Payment;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Transaction;
use PayPal\Api\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Sale;

if(isset($_GET) && (count($_GET) > 0)){
    $currency = 'USD';
        
    $apiContext = new \PayPal\Rest\ApiContext(
        new \PayPal\Auth\OAuthTokenCredential(
            'ATQPCjSAopkGqgqea7ShUok5nlSYaqY5OAl9Td3l9bCBi5F6pC9QgKWkLzZXvkhyVde4Cp2eCxYtSZSo',     // ClientID
            'EBWXI5X8os7IprmNyy94oMeCZhruzJije55Yh5Pv7hUZ5hnCbTsHfr4hiDBz7f0XFvRakf0iuoE1XIkH'      // ClientSecret
        )
    );

    $apiContext->setConfig(
        array(
            'mode' => 'sandbox',
        )
    );

    $token = $_GET['token'];
    $paymentId = $_GET['paymentId'];
    $payerId = $_GET['PayerID'];
    $payment = Payment::get($paymentId, $apiContext);

    $execution = new PaymentExecution();
    $execution->setPayerId($payerId);
    
    $result = $payment->execute($execution, $apiContext);

    $payment = Payment::get($paymentId, $apiContext);
    $transactions = $payment->getTransactions();
    $transaction = $transactions[0];
    $relatedResources = $transaction->getRelatedResources();
    $relatedResource = $relatedResources[0];
    $sale = $relatedResources[0]->getSale();
    $saleId = $sale->getId();

    $sale = Sale::get($saleId, $apiContext);

    $data['reference_id'] = $token;
    $data['payment_request_id'] = $paymentId;
    $data['payment_id'] = $sale->getID();
    $data['response'] = '{"invoice_no": '.$sale->invoice_number.', "method": "paypal"}';
    $data['payment_status'] = $sale->getState();

    echo "<pre>";
    print_r($data);

}

That’s it now you can test this in your browser and if everything works fine you can update your API key with live details. I also create a demo for this example you can try from this link:- Paypal Payment live example.

If my post help you then please don’t forget to like our Facebook page and subscribe to our youtube channel.