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

DB_HOST=localhost
DB_DATABASE=Your_Database_Name
DB_USERNAME=Your_Database_User_Name
DB_PASSWORD=Your_Database_Password_Name

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

<?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::get('addPayment','PaymentController@addPayment')->name('addPayment');

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

//---------------------------------
// route for check status responce
//---------------------------------
Route::get('paypal','PaymentController@getPaymentStatus')->name('status');

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']));
        $this->_api_context->setConfig($paypal_conf['settings']);
    }

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

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

    	$item_1 = new Item();

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

        $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('Your transaction description');

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('status')) //Specify return URL
            ->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;
            }
        }

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

        if(isset($redirect_url)) 
        {
            //-------------------
            // 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
        //-----------------------------
        Session::forget('paypal_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();
        $execution->setPayerId(Input::get('PayerID'));

        //---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 !!}
                </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 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>
                                    </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>

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

http://localhost:8000/addPayment