X
    Categories: Laravel

Paypal integration in laravel 5.4

Paypal integration in laravel 5.4

Paypal integration in laravel 5.4. When we are going to build a e-commerce website we must have any one payment geteway to make a payment. Paypal is a global and common way to send a money by online. Lets see how to integrate paypal payment gateway in laravel 5.4

Step 1 : Install laravel 5.4

laravel new laravel54
Crafting application...
Loading composer repositories with package information
Installing dependencies (including require-dev) from lock file
Package operations: 59 installs, 0 updates, 0 removals
  - Installing doctrine/inflector (v1.1.0): Loading from cache
  - Installing erusev/parsedown (1.6.3): Loading from cache
  - Installing jakub-onderka/php-console-color (0.1): Loading from cache
  - Installing symfony/polyfill-mbstring (v1.4.0): Loading from cache
  - Installing symfony/var-dumper (v3.3.5): Loading from cache
  - Installing psr/log (1.0.2): Loading from cache
  - Installing symfony/debug (v3.3.5): Loading from cache
  - Installing symfony/console (v3.3.5): Loading from cache
  - Installing nikic/php-parser (v3.0.6): Loading from cache
  - Installing jakub-onderka/php-console-highlighter (v0.3.2): Loading from cache
  - Installing dnoegel/php-xdg-base-dir (0.1): Loading from cache
  - Installing psy/psysh (v0.8.9): Loading from cache
  - Installing vlucas/phpdotenv (v2.4.0): Loading from cache
  - Installing symfony/css-selector (v3.3.5): Loading from cache
  - Installing tijsverkoyen/css-to-inline-styles (2.2.0): Loading from cache
  .............

It will install the latest version of laravel to your application

Step 2 : Configure your database

In mycase :

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=laravel54
DB_USERNAME=root
DB_PASSWORD=root

Step 3 : Install guzzlehttp

composer require guzzlehttp/guzzle
Using version ^6.3 for guzzlehttp/guzzle
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 4 installs, 0 updates, 0 removals
  - Installing guzzlehttp/promises (v1.3.1): Loading from cache
  - Installing psr/http-message (1.0.1): Loading from cache
  - Installing guzzlehttp/psr7 (1.4.2): Loading from cache
  - Installing guzzlehttp/guzzle (6.3.0): Loading from cache
Writing lock file
Generating optimized autoload files

It will install latest version of guzzlehttp


Step 4 : Install Paypal PHP SDK

composer require paypal/rest-api-sdk-php:*
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals
  - Installing paypal/rest-api-sdk-php (1.12.0): Loading from cache
Writing lock file
Generating optimized autoload files

It will install latest php-paypal-rest-apk to your vendor folder

Step : 5 Run vendor publish command

php artisan vendor:publish

It will publish paypal.php file under config folder. If it does’t create a paypal.php dont panic just create it manually.

config/paypal.php

<?php
return array(
/** set your paypal credential **/
'client_id' =>'**********************************************',
'secret' => '=>'**********************************************',',
/**
* SDK configuration 
*/
'settings' => array(
/**
* Available option 'sandbox' or 'live'
*/
'mode' => 'sandbox',
/**
* Specify the max request time in seconds
*/
'http.ConnectionTimeOut' => 1000,
/**
* Whether want to log to a file
*/
'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
* proceed towards ERROR
*/
'log.LogLevel' => 'FINE'
),
);

Step 6 : Create a Route to add payment details and make payment

routes/web.php

Route::get('checkout', array('as' => 'paypal.paywithpaypal','uses' => 'PaypalController@payWithPaypal',)); 
Route::post('paypal', array('as' => 'paypal.paypal','uses' => 'PaypalController@postPaymentWithpaypal',));
Route::get('paypal', array('as' => 'payment.status','uses' => 'PaypalController@getPaymentStatus',));

Step 7 : Create Controller

app/Http/Controllers/PaypalController.php

Run below command to create a PaypalController file.

php artisan make:controller PaypalController

Replace PaypalController.php with below code

<?php

namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use Validator;
use URL;
use Session;
use Redirect;

/** 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;
use Illuminate\Support\Facades\Input;
class PaypalController extends HomeController
{
    private $_api_context;
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__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']);
    }
    /**
     * Show the application paywith paypalpage.
     *
     * @return \Illuminate\Http\Response
     */
    public function payWithPaypal()
    {
        return view('paywithpaypal');
    }
    /**
     * Store a details of payment with paypal.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postPaymentWithpaypal(Request $request)
    {
    	$this->validate($request, [
	    'name' => 'required',
	    'quantity' => 'required|numeric',
	    'amount' => 'required|numeric'
	]);
        $payer = new Payer();
        $payer->setPaymentMethod('paypal');
        $item_1 = new Item();
        $item_1->setName($request->get('name')) /** item name **/
            ->setCurrency('USD')
            ->setQuantity($request->get('quantity'))
            ->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') * $request->get('quantity') ));
        $transaction = new Transaction();
        $transaction->setAmount($amount)
            ->setItemList($item_list)
            ->setDescription('Your transaction description');
        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('payment.status')) /** Specify return URL **/
            ->setCancelUrl(URL::route('payment.status'));
        $payment = new Payment();
        $payment->setIntent('Sale')
            ->setPayer($payer)
            ->setRedirectUrls($redirect_urls)
            ->setTransactions(array($transaction));
            /** dd($payment->create($this->_api_context));exit; **/
        try {
            $payment->create($this->_api_context);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Connection timeout');
                return Redirect::route('paypal.paywithpaypal');
                /** echo "Exception: " . $ex->getMessage() . PHP_EOL; **/
                /** $err_data = json_decode($ex->getData(), true); **/
                /** exit; **/
            } else {
                \Session::put('error','Some error occur, sorry for inconvenient');
                return Redirect::route('paypal.paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/
            }
        }
        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('paypal.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('paypal.paywithpaypal');
        }
        $payment = Payment::get($payment_id, $this->_api_context);
        /** PaymentExecution object includes information necessary **/
        /** to execute a PayPal account payment. **/
        /** The payer_id is added to the request query parameters **/
        /** when the user is redirected from paypal back to your site **/
        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));
        /**Execute the payment **/
        $result = $payment->execute($execution, $this->_api_context);
        /** dd($result);exit; /** DEBUG RESULT, remove it later **/
        if ($result->getState() == 'approved') { 
            
            /** it's all right **/
            /** Here Write your database logic like that insert record or value in database if you want **/
            \Session::put('success','Payment success');
            return Redirect::route('paypal.paywithpaypal');
        }
        \Session::put('error','Payment failed');
        return Redirect::route('paypal.paywithpaypal');
    }
  }

Step 8 : Create blade file to enter item details

resources/paywithpaypal.blade.php

@extends('layouts.app')
@section('content')
<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">Paypal integration in Laravel</div>
<div class="panel-body">
<form class="form-horizontal" method="POST" id="payment-form" role="form" action="{!! URL::route('paypal.paypal') !!}" >
{{ csrf_field() }}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
<label >
Run your application in browser

Eg : http://localhost:8888/Paypal integration/laravel54/public/checkout

Note : You should login before try checkout. If you face paypal unsupported ssl protocol version error, Please check ssl is enabled in your curl version at phpinfo()

Paypal integration Demo Outputs

Thats it, Now you can simply make Paypal integration in laravel.

Marimuthu: