Home » Laravel Paypal Integration Tutorial With Example

Laravel Paypal Integration Tutorial With Example

Last updated on May 28, 2022 by

In this article, we will learn Laravel Paypal integration tutorial with example. We will integrate the Paypal API using srmklive/laravel-paypal composer package. Using this package you can process or refund payments and handle IPN (Instant Payment Notification) from PayPal in your Laravel application. Let’s dive into it.

Step 1: Install Laravel

If you already have installed Laravel on your local machine then you can skip this step. You can easily install the fresh version of Laravel by running the below command in your terminal. You can give it any name but in this case, we will name it demo-app.

composer create-project --prefer-dist laravel/laravel demo-app

Step 2: Install-Package

In this step, we need to install the srmklive/laravel-paypal composer package to use its functionalities to save time. Run the below command to install the package.

For Laravel 5.1 to 5.8

cd demo-app

composer require srmklive/paypal:~2.0

For Laravel 6, 7, & 8

cd demo-app

composer require srmklive/paypal:~3.0

Step 3: Configuration

Now open the config/app.php file and add the service provider and its alias.

config/app.php

'providers' => [
	....
	Srmklive\PayPal\Providers\PayPalServiceProvider::class
]
....

Publish Assets

If you would like to change anything custom like config, HTML blade, etc. then you can publish the assets to do that run the below command:

php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"

Step 4: Create Routes

We need to add routes in routes/web.php file to Laravel Paypal send payment, receive Paypal payment, to show success message, etc. So open the routes/web.php file and add the following route.

routes/web.php

<?php

use App\Http\Controllers\PayPalController;
use Illuminate\Support\Facades\Route;

Route::get('payment', ['PayPalController::class', 'payment'])->name('payment');
Route::get('cancel', ['PayPalController::class', 'cancel'])->name('payment.cancel');
Route::get('payment/success', ['PayPalController', 'success'])->name('payment.success');

Step 5: Create Controller

Let’s create a PaypalController to create a controller run the below command:

php artisan make:controller PaypalController

After running the above command a new file will be created in Controllers the directory, open it, and add the following code.

app/Http/Controllers/PaypalController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;

class PayPalController extends Controller
{
    public function payment()
    {
        $data = [];

        $data['product'] = [
            [
                'name' => 'Product 1',
                'price' => 100,
                'desc' => 'Description for Product 1',
                'qty' => 1
            ]
        ];

        $data['invoice_id'] = 1;

        $data['invoice_description'] = "Order #{$data['invoice_id']} Invoice";

        $data['return_url'] = route('payment.success');

        $data['cancel_url'] = route('payment.cancel');

        $data['total'] = 100;

        $provider = new ExpressCheckout;
        $response = $provider->setExpressCheckout($data);
        $response = $provider->setExpressCheckout($data, true);

        return redirect($response['paypal_link']);
    }

    public function cancel()
    {
        dd('Your payment is canceled. You can create cancel page here.');
    }

    public function success(Request $request)
    {
        $response = $provider->getExpressCheckoutDetails($request->token);

        if (in_array(strtoupper($response['ACK']) , ['SUCCESS', 'SUCCESSWITHWARNING']))
        {
            dd('Your payment was successfully. You can create success page here.');
        }
        
        dd('Something is wrong.');
    }
}


Step 6: Create Blade/HTML File

Let’s create checkout.blade.php file. We will add the button for the Paypal payment gateway in this file.

resources/views/checkout.blade.php


<!doctype html>
<html>
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <title>Laravel PayPal Integration Tutorial - ScratchCode.IO</title>
      <!-- Fonts -->
      <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha256-YLGeXaapI0/5IgZopewRJcFXomhRMlYYjugPLSyNjTY=" crossorigin="anonymous" />
      <!-- Styles -->
      <style>
         html, body {
         background-color: #fff;
         color: #636b6f;
         font-family: 'Nunito', sans-serif;
         font-weight: 200;
         height: 100vh;
         margin: 0;
         }
         .content {
         margin-top: 100px;
         text-align: center;
         }
      </style>
   </head>
   <body>
      <div class="flex-center position-ref full-height">
         <div class="content">
            <h1>Laravel PayPal Integration Tutorial - ScratchCode.IO</h1>
            <table border="0" cellpadding="10" cellspacing="0" align="center">
               <tr>
                  <td align="center"></td>
               </tr>
               <tr>
                  <td align="center"><a href="https://www.paypal.com/in/webapps/mpp/paypal-popup" title="How PayPal Works" onclick="javascript:window.open('https://www.paypal.com/in/webapps/mpp/paypal-popup','WIPaypal','toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, width=1060, height=700'); return false;"><img src="https://www.paypalobjects.com/webstatic/mktg/Logo/pp-logo-200px.png" border="0" alt="PayPal Logo"></a></td>
               </tr>
            </table>
            <a href="{{ route('payment') }}" class="btn btn-success">Pay $100 from Paypal</a>
         </div>
      </div>
   </body>
</html>

Step 7: Set Environment Variables

At last, let’s set the Paypal credentials into the .env file.

.env

PAYPAL_MODE=sandbox
PAYPAL_SANDBOX_API_USERNAME=sb-sdfhowej..
PAYPAL_SANDBOX_API_PASSWORD=LKFIU...
PAYPAL_SANDBOX_API_SECRET=BTlmsdf....
PAYPAL_CURRENCY=INR
PAYPAL_SANDBOX_API_CERTIFICATE=

Hurray! We have completed all steps for the Laravel Paypal integration tutorial. Let’s run the below command and see how it’s working.

php artisan serve

After running the above command, open your browser and visit the site below URL:

http://localhost:8000/

Additionally, read our guide:

  1. Laravel: Blade Switch Case Statement Example
  2. Laravel: Switch Case Statement In Controller Example
  3. Laravel: Change Column Type In Migration
  4. 2fa Laravel With SMS Tutorial With Example
  5. How To Use Where Date Between In Laravel
  6. How To Add Laravel Next Prev Pagination
  7. Laravel Remove Column From Table In Migration
  8. Laravel: Get Month Name From Date
  9. Laravel: Increase Quantity If Product Already Exists In Cart
  10. How To Update Pivot Table In Laravel
  11. How To Install Vue In Laravel 8 Step By Step
  12. How To Handle Failed Jobs In Laravel
  13. Best Ways To Define Global Variable In Laravel
  14. How To Get Latest Records In Laravel
  15. How To Break Nested Loops In PHP Or Laravel
  16. How To Pass Laravel URL Parameter
  17. Laravel Run Specific Migration
  18. Laravel Notification Tutorial With Example
  19. How To Schedule Tasks In Laravel With Example
  20. Laravel Collection Push() And Put() With Example

That’s it from our end. We hope this article helped you learn the Laravel Paypal integration tutorial with example.

Please let us know in the comments if everything worked as expected, your issues, or any questions. If you think this article saved your time & money, please do comment, share, like & subscribe. Thank you for reading this post 🙂 Keep Smiling! Happy Coding!

 
 

Leave a Comment