How to integrate paypal payment gateway in laravel 5.4

How to integrate paypal payment gateway in laravel 5.4

In this post we will give you information about How to integrate paypal payment gateway in laravel 5.4. Hear we will give you detail about How to integrate paypal payment gateway in laravel 5.4And how to use it also give you demo for it if it is necessary.

Hello, today onlinecode share with you a one of the very nice tutorials of how to integrattion paypal payment gateway in your laravel to very easy way with simple example and with working code.

You are need to integration payment gateway in many laravel application and many developer guss is to hard but it is very easy and simple problem. here we are help to you how to integrate payment gateway in your laravel application with paypal.

Today paypal is major and world most very usefull payment gateway which many people want to integrate with thair website. so, onlinecode show you how to integrate paypal with laravel.

We are use here paypal/rest-api-sdk-php package for integrate paypal with laravel. this is very good paypal package for integrate paypal with laravel.

Here i give you full example of How to integrate paypal payment gateway step by step like create laravel project, migration, model, route, blade file etc. So you have to just follow few step as listed bellow.

Follow Bellow Few Step:

  • 1)Create new Laravel Application
  • 2)Database Configuration
  • 3)Install Required Packages
  • 4)Configuration paypal.php file
  • 5)Create route
  • 6)Create controller
  • 7)Create view file


Step : 1 Create new laravel application

Here, we are create new one laravel project by using collowing command

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

Step : 2 Database Configuration

After create new onw laravel application then after we need to configration our database setting in .env file like that


Step : 3 Install Required Packages

After configure .env file now we are install require package for integrate paypal payment gateway in our laravel application. we are paypal/rest-api-sdk-php package.

"guzzlehttp/guzzle": "~5.2",
"paypal/rest-api-sdk-php": "*",

After added above two package in your laravel application’s composer.json file and then after you are need to composer update using following command in your terminal or cmd

sudo composer update

After update composer and you get not any error during installation of package. then move to next step if incase you getting any error so, please try again.

Step : 4 Configuration paypal.php file

We need to create one confige file paypal.php in config folder and in this file we are set our paypal client_id and secret and more paypal configration options like this way

If you are not knowing how to create paypal client_id and secret in paypal sendbox. please show this video for it How to integrate paypal with laravel

/** set your paypal credential **/
'client_id' =>'paypal client_id',
'secret' => 'paypal secret ID',
* 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 : 5 Create route

No we are required three route in you routes/web.php file one is required for show paypal payment form view and one another is for make post HTTP request and therd for check our payment return status responce is true or false like this way

// route for view/blade file
Route::get('paywithpaypal', array('as' => 'paywithpaypal','uses' => '[email protected]',));
// route for post request
Route::post('paypal', array('as' => 'paypal','uses' => '[email protected]',));
// route for check status responce
Route::get('paypal', array('as' => 'status','uses' => '[email protected]',));

Step : 6 Create PaypalController


Now create PaypalController.php file in app/Http/Controllers folder like this way.

namespace AppHttpControllers;

use AppHttpRequests;
use IlluminateHttpRequest;
use Validator;
use URL;
use Session;
use Redirect;
use Input;

/** All Paypal Details class **/
use PayPalRestApiContext;
use PayPalAuthOAuthTokenCredential;
use PayPalApiAmount;
use PayPalApiDetails;
use PayPalApiItem;
use PayPalApiItemList;
use PayPalApiPayer;
use PayPalApiPayment;
use PayPalApiRedirectUrls;
use PayPalApiExecutePayment;
use PayPalApiPaymentExecution;
use PayPalApiTransaction;

class AddMoneyController extends HomeController
    private $_api_context;
     * Create a new controller instance.
     * @return void
    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']));

     * Show the application paywith paypalpage.
     * @return IlluminateHttpResponse
    public function payWithPaypal()
        return view('paywithpaypal');

     * Store a details of payment with paypal.
     * @param  IlluminateHttpRequest  $request
     * @return IlluminateHttpResponse
    public function postPaymentWithpaypal(Request $request)
        $payer = new Payer();

    	$item_1 = new Item();

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

        $item_list = new ItemList();

        $amount = new Amount();

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

        $redirect_urls = new RedirectUrls();
        $redirect_urls->setReturnUrl(URL::route('status')) /** Specify return URL **/

        $payment = new Payment();
            /** dd($payment->create($this->_api_context));exit; **/
        try {
        } catch (PayPalExceptionPPConnectionException $ex) {
            if (Config::get('app.debug')) {
                Session::put('error','Connection timeout');
                return Redirect::route('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('paywithpaypal');
                /** die('Some error occur, sorry for inconvenient'); **/

        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::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 **/
        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);
        /** 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);
        /** 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('paywithpaypal');
        Session::put('error','Payment failed');

		return Redirect::route('paywithpaypal');

Step : 7 Create view file

Now, we are create one resources/views/paywithpaypal.blade.php for display paypal form


<div >
    <div >
        <div >
            <div >
                @if ($message = Session::get('success'))
                <div >
                    <button type="button"  data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                <?php Session::forget('success');?>

                @if ($message = Session::get('error'))
                <div >
                    <button type="button"  data-dismiss="alert" aria-hidden="true"></button>
                    {!! $message !!}
                <?php Session::forget('error');?>
                <div >Paywith Paypal</div>
                <div >
                    <form  method="POST" id="payment-form" role="form" action="{!! URL::route('addmoney.paypal') !!}" >
                        {{ csrf_field() }}

                        <div >
                            <label for="amount" >Amount</label>

                            <div >
                                <input id="amount" type="text"  name="amount" value="{{ old('amount') }}" autofocus>

                                @if ($errors->has('amount'))
                                    <span >
                                        <strong>{{ $errors->first('amount') }}</strong>
                        <div >
                            <div >
                                <button type="submit" >
                                    Paywith Paypal

Now we are ready to run our example so run bellow command ro quick run:

php artisan serve

Now you can open bellow URL on your browser:


I hope it can help you…

Hope this code and post will helped you for implement How to integrate paypal payment gateway in laravel 5.4. if you need any help or any feedback give it in comment section or you have good idea about this post you can give it comment section. Your comment will help us for help you more and improve us. we will give you this type of more interesting post in featured also so, For more interesting post and code Keep reading our blogs

For More Info See :: laravel And github

We're accepting well-written guest posts and this is a great opportunity to collaborate : Contact US