Laravel 8 Paypal Payment Gateway Integration

In this article, we will see laravel 8 PayPal payment gateway integration. Paypal is an international payment processing gateway working in the majority of countries that support online money transfers. Paypal is a safer, easier way to pay around the world.​ So, we will learn how to integrate the PayPal payment gateway in laravel 8.

PayPal is an american company operating a worldwide online payments system that supports online money transfers and serves as an electronic alternative to traditional paper methods like checks and money orders. For this example, we are using paypal/rest-api-sdk-php package. Using PayPal you can pay online, buy now, buy online, make an online payment, transfer money online, shop online and etc.

So, let's see PayPal payment gateway integration in laravel 8.

Step 1: Create a new laravel 8 application

Step 2: Setup database configuration

Step 3: Install paypal/rest-api-sdk-php package

Step 4: Configure the paypal.php file

Step 5: Add route in web.php file

Step 6: Create a controller

Step 7: Create a blade file

 

Step 1: Create a new laravel 8 application

In this step, We will create a new project set up for this PayPal integration. So, create a new project using the below command.

composer create-project --prefer-dist laravel/laravel paypal_integration_laravel_8

 

 

Step 2: Setup database configuration

 In this step, we will set up database configuration.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

 

Step 3: Install paypal/rest-api-sdk-php package

Now, we will run the following command and get the latest version of the PayPal API package using composer.

composer require paypal/rest-api-sdk-php

After installation of the PayPal package, we required a client id and secret key for Paypal integration. So, we need to login in paypal developer mode and create a new sandbox account for the same.

After login into Paypal, we need to create an application. So, check the below screenshot and create an application.

How to create papal application in laravel 8

 

 

After creating an application, we need to get the client id and secret key like the below screenshot.

How to get paypal client secret key and client id in laravel 8

 

Step 4: Configure the paypal.php file

Now, we need to configure the paypal.php file. So, we have manually created one file in config/paypal.php and added the below code.

<?php 
return [ 
    'client_id' => 'Enter Your Client ID',
	'secret' => 'Enter Your Secret Key',
    'settings' => array(
        'mode' => 'sandbox',
        'http.ConnectionTimeOut' => 1000,
        'log.LogEnabled' => true,
        'log.FileName' => storage_path() . '/logs/paypal.log',
        'log.LogLevel' => 'FINE'
    ),
];

 

Step 5: Add route in web.php file

 Now, we will add routes in the web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\PaypalController;

Route::get('paywithpaypal', array('as' => 'paywithpaypal','uses' => '[email protected]',));
Route::post('paypal', array('as' => 'paypal','uses' => '[email protected]',));
Route::get('paypal', array('as' => 'status','uses' => '[email protected]',));

 

 

Step 6: Create a controller

In this step, we will create PaypalController and add the below code to that controller.

<?php

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
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\ExecutePayment;
use PayPal\Api\PaymentExecution;
use PayPal\Api\Transaction;

class PaypalController extends Controller
{
    private $_api_context;
    
    public function __construct()
    {
            
        $paypal_configuration = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_configuration['client_id'], $paypal_configuration['secret']));
        $this->_api_context->setConfig($paypal_configuration['settings']);
    }

    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }

    public function postPaymentWithpaypal(Request $request)
    {
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');

    	$item_1 = new Item();

        $item_1->setName('Product 1')
            ->setCurrency('USD')
            ->setQuantity(1)
            ->setPrice($request->get('amount'));

        $item_list = new ItemList();
        $item_list->setItems(array($item_1));

        $amount = new Amount();
        $amount->setCurrency('USD')
            ->setTotal($request->get('amount'));

        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Enter Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('status'))
            ->setCancelUrl(URL::route('status'));

        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));            
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('paywithpaypal');                
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('paywithpaypal');                
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }
        
        Session::put('paypal_payment_id', $payment->getId());

        if(isset($redirect_url)) {            
            return Redirect::away($redirect_url);
        }

        \Session::put('error','Unknown error occurred');
    	return Redirect::route('paywithpaypal');
    }

    public function getPaymentStatus(Request $request)
    {        
        $payment_id = Session::get('paypal_payment_id');

        Session::forget('paypal_payment_id');
        if (empty($request->input('PayerID')) || empty($request->input('token'))) {
            \Session::put('error','Payment failed');
            return Redirect::route('paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);        
        $execution = new PaymentExecution();
        $execution->setPayerId($request->input('PayerID'));        
        $result = $payment->execute($execution, $this->_api_context);
        
        if ($result->getState() == 'approved') {         
            \Session::put('success','Payment success !!');
            return Redirect::route('paywithpaypal');
        }

        \Session::put('error','Payment failed !!');
		return Redirect::route('paywithpaypal');
    }
}

 

Step 7: Create a blade file

Now, we need to create a blade file for view. So, add the below code to your paywithpaypal.blade.php file.

<html>
<head>
	<meta charset="utf-8">
	<title>Laravel 8 Paypal Payment Gateway Integration - Techsolutionstuff</title>
	<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body>
	<div class="container">
    <div class="row">    	
        <div class="col-md-8 col-md-offset-2">        	
        	<h3 class="text-center" style="margin-top: 30px;">Laravel 8 Paypal Payment Gateway Integration - Techsolutionstuff</h3>
            <div class="panel panel-default" style="margin-top: 60px;">

                @if ($message = Session::get('success'))
                <div class="custom-alerts alert alert-success fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

                @if ($message = Session::get('error'))
                <div class="custom-alerts alert alert-danger fade in">
                    <button type="button" class="close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('error');?>
                @endif
                <div class="panel-heading"><b>Paywith Paypal</b></div>
                <div class="panel-body">
                    <form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('paypal') !!}" >
                        {{ csrf_field() }}

                        <div class="form-group{{ $errors->has('amount') ? ' has-error' : '' }}">
                            <label for="amount" class="col-md-4 control-label">Enter Amount</label>

                            <div class="col-md-6">
                                <input id="amount" type="text" class="form-control" name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span class="help-block">
                                        <strong>{{ $errors->first('amount') }}</strong>
                                    </span>
                                @endif
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

 

 

Now create a Paypal sandbox test account like the below screenshot.

how to create sandbox test account in paypal

 

once you will enter the amount you will get a form like this. if you don't have an account then you need to create an account first.

paypal payment gateway integration in laravel 8

 

 

After clicking on continue, you will get a success form like the below screenprint.

paypal integration in laravel 8

 

Once you will get this view then after it will show another successful message form of your transaction. click here to check your transaction.

paypal transaction receipt

 


You might also like:

RECOMMENDED POSTS

FEATURE POSTS