PHP Laravel 6 PayPal Payment Gateway API integration step by step

Today, We want to share with you PHP Laravel 6 PayPal Payment Gateway API integration step by step.In this post we will show you Set up Paypal Payment Gateway Integration in Laravel 6 PHP Example, hear for PayPal Payment Gateway API integration in Laravel6 we will give you demo and example for implement.In this post, we will learn about How to integrate PayPal payment gateway in Laravel 6 with an example.

List of all Google Adsense, VueJS, AngularJS, PHP, Laravel Examples.

PHP Laravel 6 PayPal Payment Gateway API integration step by step

There are the Following The simple About Paypal payment gateway integration in Laravel 6.0 step by step Full Information With Example and source code.

As I will cover this Post with live Working example to develop Integrate Laravel Paypal Payment Gateway For Fast Online Payments, so the composer require paypal rest api sdk php is used for this example is following below.

Phase – 1 : Create new laravel application

create a new Fresh laravel 6 Web application

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

Phase – 2 : Database Configuration

configure chnage database setting in .env file

DB_HOST=localhost
DB_DATABASE=best_marketuts
DB_USERNAME=virat_im31
[email protected]

Phase – 3 : Install Required Packages

install paypal/rest-api-sdk-php

composer require paypal/rest-api-sdk-php

config/paypal.php

You can view paypal.php file like as bellow:

'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',

'settings' => array(
	'mode' => 'sandbox',
	'http.ConnectionTimeOut' => 1000,
	'log.LogEnabled' => true,
	'log.FileName' => storage_path() . '/logs/paypal.log',
	'log.LogLevel' => 'FINE'
	),
);

Phase – 4 : Define a Laravel 6 Route

routes/web.php

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

Phase – 5 : Make a Laravel 6 Controller

app/Http/Controllers/TransactionController.php

<?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 TransactionController extends Controller
{
    private $data_v1_api;

    public function __construct()
    {
        parent::__construct();
        
        $all_cridentials = \Config::get('paypal');
        $this->data_v1_api = new ApiContext(new OAuthTokenCredential($all_cridentials['client_id'], $all_cridentials['secret']));
        $this->data_v1_api->setConfig($all_cridentials['settings']);
    }


    public function planWithCharge()
    {
        return view('planwithcharge');
    }

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

    	$item_1 = new Item();

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

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

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

        $transaction = new Transaction();
        $transaction->setAmount($price)
            ->setItemList($item_list)
            ->setDescription('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->data_v1_api);
        } catch (\PayPal\Exception\PPConnectionException $ex) {
            if (\Config::get('app.debug')) {
                \Session::put('error','Sorry Your Connection timeout');
                return Redirect::route('planwithcharge');
            } else {
                \Session::put('error','Sorry, Some error occur, sorry for inconvenient');
                return Redirect::route('planwithcharge');
            }
        }

        foreach($payment->getLinks() as $link) {
            if($link->getRel() == 'approval_url') {
                $redirect_url = $link->getHref();
                break;
            }
        }

        Session::put('live_trans_ref_code', $payment->getId());

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

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

    public function getPaymentStatus()
    {

        $payment_id = Session::get('live_trans_ref_code');

        Session::forget('live_trans_ref_code');
        if (empty(Input::get('PayerID')) || empty(Input::get('token'))) {
            \Session::put('error','Sorry dear Your Payment failed');
            return Redirect::route('planwithcharge');
        }
        $payment = Payment::get($payment_id, $this->data_v1_api);

        $execution = new PaymentExecution();
        $execution->setPayerId(Input::get('PayerID'));

        $result = $payment->execute($execution, $this->data_v1_api);

        if ($result->getState() == 'approved') { 

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

		return Redirect::route('planwithcharge');
    }
}

Phase – 6 : Create Blade File

resources/total_likes/planwithcharge.blade.php

@extends('layouts.app')

@section('content')

<div class="dsp container">
<h1>Paypal payment gateway integration in Laravel 6 step by step</h1>
    <div class="dsp row">
        <div class="dsp col-md-8 col-md-offset-2">
            <div class="panel panel-default">
                @if ($message = Session::get('success'))
                <div class="dsp custom-alerts alert alert-success fade in">
                    <button type="button" class="dsp close" data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                </div>
                <?php Session::forget('success');?>
                @endif

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

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

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

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

Web Programming Tutorials Example with Demo

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about laravel payment gateway package.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   Paypal Recurring Payments PHP REST API Example
  2.   laravel paypal integration Tutorial from Scratch for Beginners
  3.   Ajax Image Upload without Refreshing Page using Jquery
  4.   Google Responsive Charts (Pie Bar Column) Examples
  5.   PHP Get Full URL PATH QUERY STRING
  6.   laravel Add cascade on delete (ON DELETE CASCADE)
  7.   PHP wordpress get timezone Example - MySQL
  8.   Laravel Calculate Age from Date of Birth in MySQL
  9.   javascript remove last comma from string
  10.   PHP Jquery Ajax CRUD Example Tutorial From Scratch