How to integrate PayPal into Laravel?

Parth Patel
In Laravel
Published in
3 min readMay 30, 2020

PayPal Payment Gateway Integration

Photo by Canva Team

Laravel Tutorials

Just copy and paste, and you are done. I made it that simple for everyone. Assuming that you already have laravel setup on your local machine. Follow the below steps one by one to easily integrate Paypal into your laravel project:

Sign up for a free PayPal Business Account

Sign in to PayPal Developers Dashboard

There are two types of API modes in PayPal:

  1. Sandbox ( For testing payments in development )
  2. Live ( For actual payments in production )

Create an App in both of the modes one by one.

Hurray! We are halfway there.

PayPal SDK for PHP

Add the paypal/rest-api-sdk-php to your laravel project by the following command:

composer install paypal/rest-api-sdk-php

Create a paypal.php in your config folder and add the following code:

<?php 
return [
'client_id' => env('PAYPAL_CLIENT_ID',''),
'secret' => env('PAYPAL_SECRET',''),
'settings' => array(
'mode' => env('PAYPAL_MODE','sandbox'),
'http.ConnectionTimeOut' => 30,
'log.LogEnabled' => true,
'log.FileName' => storage_path() . '/logs/paypal.log',
'log.LogLevel' => 'ERROR'
),
];

Now, go to your PayPal app dashboard and open the app which you have created in the beginning. PAYPAL_CLIENT_ID and PAYPAL_SECRET will be mentioned there like below.

Also, add and paste the values of the following environment variables to your .env file:

PAYPAL_MODE=sandbox
PAYPAL_CLIENT_ID=XXXXXXXXXXXXXXX
PAYPAL_SECRET=XXXXXXXXXXXXXXX

Create a controller and name it PaymentController. Use the following command to create a controller:

php artisan make:controller PaymentController

Add the following code to your routes/web.php:

//PaymentRoute::post('/payment', ['as' => 'payment', 'uses' => 'PaymentController@payWithpaypal']);Route::get('/payment/status',['as' => 'status', 'uses' => 'PaymentController@getPaymentStatus']);

Add the following code to your controller:

<?phpnamespace App\Http\Controllers;use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use PayPal\Rest\ApiContext;
use PayPal\Auth\OAuthTokenCredential;
use PayPal\Api\Agreement;
use PayPal\Api\Payer;
use PayPal\Api\Plan;
use PayPal\Api\PaymentDefinition;
use PayPal\Api\PayerInfo;
use PayPal\Api\Item;
use PayPal\Api\ItemList;
use PayPal\Api\Amount;
use PayPal\Api\Transaction;
use PayPal\Api\RedirectUrls;
use PayPal\Api\Payment;
use PayPal\Api\PaymentExecution;
use Illuminate\Support\Facades\Input;
use Redirect;
use URL;
class PaymentController extends Controller
{
public function __construct()
{
/** 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 payWithpaypal()
{

$amountToBePaid = 100;
$payer = new Payer();
$payer->setPaymentMethod('paypal');

$item_1 = new Item();
$item_1->setName('Mobile Payment') /** item name **/
->setCurrency('USD')
->setQuantity(1)
->setPrice($amountToBePaid); /** unit price **/

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

$amount = new Amount();
$amount->setCurrency('USD')
->setTotal($amountToBePaid);
$redirect_urls = new RedirectUrls();
/** Specify return URL **/
$redirect_urls->setReturnUrl(URL::route('status'))
->setCancelUrl(URL::route('status'));

$transaction = new Transaction();
$transaction->setAmount($amount)
->setItemList($item_list)
->setDescription('Your transaction description');

$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('/');
} else {
\Session::put('error', 'Some error occur, sorry for inconvenient');
return Redirect::route('/');
}
}
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('/');
}

public function getPaymentStatus(Request $request)
{
/** 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($request->PayerID) || empty($request->token)) {
session()->flash('error', 'Payment failed');
return Redirect::route('/');
}
$payment = Payment::get($payment_id, $this->_api_context);
$execution = new PaymentExecution();
$execution->setPayerId($request->PayerID);
/**Execute the payment **/
$result = $payment->execute($execution, $this->_api_context);

if ($result->getState() == 'approved') {
session()->flash('success', 'Payment success');
return Redirect::route('/');
}
session()->flash('error', 'Payment failed');
return Redirect::route('/');
}}

That’s all folks! I really tried hard to make this one a copy-paste job for you.

Give a clap if it helped. Ask questions if you have, I am happy to answer them. :)

--

--

Parth Patel
In Laravel

Author | Full Stack Developer at Community Agency