Paypal Payment Gateway Integration In Laravel 5.5

By : PHPErrorCode November 21, 2017 775 Views laravel

Hello Friend, Today I share with you the PayPal Payment gateway integration in the laravel web application. Payment gateways are required to pay in any website's online transaction and this is the most important part of a web application. in this post we will be integration for PayPal Payment gateway in the laravel web application.

PayPal is a very good payment gateway when it comes to Payment gateway integration. Because that international payment process also works And this used in most all countries.

Here we are using a paypal/rest-api-sdk-free full package for paypal payment gateway, which allows you to pay a paypal payment gateway integrate in your laravel web application.

Now i create smole demo to create paypal paymnet gateway integration in laravel 5.5 web application step by step

Now i create smoal demo for use paypal paymnet gateway integration in laravel 5.5 web application, you are ready paypal payment gatway integration in your laravel web application so below step.

Step 1: Create laravel new application

Here, we are create new one laravel web application by using following below command

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

Step : 2 Create Database

  1. Open http://localhost/phpmyadmin/
  2. Create database as "Demo"

Step : 3 Database Setup

After create new laravel web application then open .env file and few change for below line


Step : 4 Install Paypal Packages

Now we are need to paypal/rest-api-sdk-php package. so open the composer.json file and add below 2 line.

"require": {
    "guzzlehttp/guzzle": "~5.2",
    "paypal/rest-api-sdk-php": "*",

now need to composer update after added above 2 line in composer.json file so add the following command in your CMD

composer update

After update composer Go to config derectory and create a new file paypal.php

return array(
	// set your paypal credential 

	'client_id' =>'set paypal client_ID',
	'secret' => 'set paypal secret_ID',

	// SDK Setup

	'settings' => array(
	// Set Paypal Mode 2 option 'Live' or 'sandbox'

	'mode' => 'sandbox',

	// Set maximum request time

	'http.ConnectionTimeOut' => 1000,
	// Set log Enabled or not

	'log.LogEnabled' => true,

	// Specify the file that want to write on

	'log.FileName' => storage_path() . '/logs/paypal.log',

	//Available option 'FINE', 'INFO', 'WARN' or 'ERROR'
	//Logging is most verbose in the 'FINE' level and decreases as you

	'log.LogLevel' => 'FINE'

Change the two things in the above code

  1. client_id
  2. secret

If you do not find the client_id and secret in paypal website, please see this link

Step : 5 Add route

Now we need three routs, which will send a HTTP recapture and there for check payment return status responce is true or false

// route for view/blade file

// route for post request
Route::post('paypal', 'PaymentController@postPaymentWithpaypal')->name('paypal');

// route for check status responce

Step : 6 Create PaymentController

Now Go to app/Http/Controllers directory and Create new file PaymentController.php, add the following code to it.

namespace App\Http\Controllers;

use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;
use Input;
use DB;

//All Paypal Details class
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 PaymentController extends Controller
    private $_api_context;
    public function __construct()
        //setup PayPal api context
        $paypal_conf = \Config::get('paypal');
        $this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));

    public function addPayment()
        return view('addPayment');

    public function postPaymentWithpaypal(Request $request)
        $payer = new Payer();

    	$item_1 = new Item();

        $item_1->setName('Item 1') //item name
            ->setPrice($request->get('amount')); //unit price

        $item_list = new ItemList();

        $amount = new Amount();

        $transaction = new Transaction();
            ->setDescription('Your transaction description');

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

        $payment = new Payment();

        catch (\PayPal\Exception\PPConnectionException $ex) 
            if (\Config::get('app.debug')) 
                \Session::put('error','Connection timeout');
                return Redirect::route('paywithpaypal');
                \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();

        // add payment ID to session
        Session::put('paypal_payment_id', $payment->getId());

            // redirect to paypal
            return Redirect::away($redirect_url);

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

    public function getPaymentStatus()
        // Get the payment ID before session clear
        $payment_id = Session::get('paypal_payment_id');

        // clear the session payment ID
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) 
            \Session::put('error','Payment failed');
            return Redirect::route('paywithpaypal');
        $payment = Payment::get($payment_id, $this->_api_context);

        $execution = new PaymentExecution();

        //---Execute the payment ---//
        $result = $payment->execute($execution, $this->_api_context);

        if ($result->getState() == 'approved') { 
            // Here Write your database logic like that insert record or value in database if you want 

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

		return Redirect::route('paywithpaypal');

Step : 7 Create view blade file

Now Go to resources/views/ directory and create new view file name addPayment.blade.php, add the following code to it.

<div class="container"> 
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @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 !!}
                <?php Session::forget('success');?>
                @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 !!}
                <?php Session::forget('error');?>
                <div class="panel-heading text-center"><h2>paypal payment gateway in laravel 5</h2></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>
                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-primary">
                                    Paywith Paypal

demo is redy now Let's start in laravel web application

open cmd and run below commnad

php artisan serve

open browser and show below url