Laravel 5 - Paypal Payment Gateway Integration Complete Detail

Paypal payment Gateway Integration in Laravel 5.2

PayPal has release an official SDK ( to simplify our work. Here we will learn how to integrate into Laravel 5.2.

We will be using laracast flash notification system

1. Install PayPal SDK and Laracast Flash notification via composer

Edit File composer.json and add
"require": {
"laracasts/flash": "^2.0",
"paypal/rest-api-sdk-php": "*"
Now, update the composer with below command :-
composer update
You can now use the PayPal package and laracast flash notification in the project.

Now, include the service provider within config/app.php
'providers' => [
And, for convenience, add a facade alias to this same file at the bottom:
'aliases' => [
'Flash' => Laracasts\Flash\Flash:class,
Now, add below code in your view file.

2. Create Paypal config file

create paypal config file in config directory with name paypal :-
return array(
// set your paypal credential
// Below credentials are different for sandbox mode and live mode.
'client_id' => 'Your Paypal Client ID will be here',
'secret' => 'Your Paypal secret key will be here',

* SDK configuration
'settings' => array(
* Available option 'sandbox' or 'live'
* Remember sandbox id and secret will be different than live
'mode' => 'sandbox',

* Specify the max request time in seconds
'http.ConnectionTimeOut' => 30,

* 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'
2. Create Controller file file

Now, Let's Create our controller in app/Http/Controller/EduclanpayController.php


namespace App\Http\Controllers;

use Laracasts\Flash\Flash;
use Session;
use Illuminate\Http\Request;
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 EduclanpayController extends Controller {

private $_api_context;

public function __construct() {
// setup PayPal api context
$paypal_conf = config('paypal');
$this->_api_context = new ApiContext(new OAuthTokenCredential($paypal_conf['client_id'], $paypal_conf['secret']));


public function postPayment() {

$payer = new Payer();

$item_1 = new Item();
$item_1->setName('Item 1') // item name
->setPrice('15'); // unit price

// add item to list
$item_list = new ItemList();

$amount = new Amount();

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

$redirect_urls = new RedirectUrls();

$payment = new Payment();

try {
} catch (\PayPal\Exception\PPConnectionException $ex) {
if (\config('app.debug')) {
echo "Exception: " . $ex->getMessage() . PHP_EOL;
$err_data = json_decode($ex->getData(), true);
} else {
Flash::error('Something went wrong, Sorry for inconvenience');
return redirect('/');

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());

if(isset($redirect_url)) {
// redirect to paypal
return redirect($redirect_url);
Flash::error('Unknown error occurred');
return redirect('/');

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

// clear the session payment ID

if (empty($request->input('PayerID')) || empty($request->input('token'))) {
Flash::error('Payment Failed');
return redirect('/');

$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();

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

* Get the ID with : $result->id
* Get the State with $result->state
* Get the Payer State with $result->payer->payment_method
* Get The Shipping Address and More Detail like below :- $result->payer->payer_info->shipping_address
* Get More detail about shipping address like city country name

echo '<pre>';print_r($result->payer->payer_info->shipping_address);echo '</pre>';exit; // DEBUG RESULT.

if ($result->getState() == 'approved') { // payment made
Flash::success('Payment Successful');
return redirect('home');
Flash::error('Payment Failed');
return redirect('/');


In Line no. 131 , i am printing the error and exiting, you can remove the code and do the processing as you want after wards.

Add Route

Now, add below route to our app/Http/route.php file

// You can use "get" or "post" method below for payment..
Route::get('payment', 'EduclanpayController@postPayment');
// This must be get method.
Route::get('payment/status', 'EduclanpayController@getPaymentStatus');

Now, you can need to add your own client id and secret key

For that follow below steps :-

1. Signup or Login to PayPal developer portal
2. Click on Dashboard link
3. Create your app by clicking "create app" and following process.
4. Under My apps, click on the app you created to use in your project
5. Scroll down after the Add webhook button, click on the Show link

You will get two key and id, One for "sandbox" mode and another for "live" mode. Use your choice one.

##### Understanding our Controller ####
Understanding postPayment function first

From Line no :- 38 to 55 in controller file inside postPayment It deals with item and price and total.

If you want to add more item, you can simply create them like below :-

$item_2 = new Item();
$item_2->setName('Item 1') // item name
->setPrice('15'); // unit price

And Do not forgot to add in Item List and change total, To do so, Check code from Line no. 45 to 50.
Once $item_2 has been created.

// add item to list in line no. 46
$item_list = new ItemList();
$item_list->setItems(array($item_1, $item_2));

and than increase Total amount

$amount = new Amount();
->setTotal(30); // Increase amount here as per the new item price.

And you are done , You can check more code inside function to understand more like description etc.,

Understanding getPaymentStatus function now

This deals with after payment has processed, it will give you complete paypal result, which you can use in your application to store.

I will discuss only line no : 130 which is below :-

echo '<pre>';print_r($result);echo '</pre>';exit;

Above $result data can be used to fetch user's result, I will pull down all data that you can use and store :-

To get Transaction ID


To get Whether payment is approved


To Check the Payer status of verified nature


To get Payer Information like :- Name, Email , Address, etc.,

// Email

// First and Last Name

// To get Payer ID

// To get Shipping Address details
// Recipient Name

//Address line 1:-

// City, State, Postal Code, Country Code

// Same way Billing Address can be fetch as above, Just replace shipping_address above with billing_address

//Address :-

// City, State, Postal Code, Country Code

Let's Get Transaction details in same nature :-


// Get The Item list

// Similarly if you have added more than 1 item, you can change items[1] , items[2] and so on and so forth

I hope, you have understood the flow, if not. Ask below.


Recent Posts