Site Admin
Site Admin Founder of MeaningArticles
1855 Views

Laravel 8 Integrate Paypal Payment Gateway

Hello Dev.

Laravel 8 PayPal Integration is the important feature, mainly when growing an e-commerce app or allowing sell functions. It makes the shopping for revel in fun and gives unbound ease to customers. With that, they are able to make bills through a PayPal account or Credit Card.

For implementing PayPal integration, we are going to believe on srmklive/laravel-paypal package’s discretion. As soon as you install and configure this third-party plugin for your laravel app.

you'll notice that you may take a look at out quickly with its explicit checkout method in laravel 8 sincerely, PayPal is one of the best payment gateways of the present day generation. in relation to cash transfer, then is no different payment gateway is near to it. higher UX, customer support, and extra sizeable network make it aside from the frenzy.

i will inform you about installing and the use of a srmklive composer package for integrating the paypal payment gateway in laravel 8. you have to consecutively give the proper attention to assimilate the muse topics of this article.

let's start with below steps and get proper and beautiful output...


Step 1: Create new project in laravel

As usual, i take my first step through installing the new and clean project. right here we can write the complete memoir of this article. Execute the subsequent command to install a brand new laravel application.

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

As soon as the installation is completed, thereafter, get inside the project folder.

cd laravel-paypal-app


Step 2: Database Configuration

Usually, to manage the data in any application, we have to make the database connection.

As you open the .env file, likewise, you will see the DB_CONNECTION line. Here you have to add your database details. To make the consensus about data synchronization in between laravel and your server.
.env

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

If you see the following error, so it mostly occurs when using MAMP as a local server.

SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from information_schema.tables where table_schema = laravel_db and table_name = migrations and table_type = ‘BASE TABLE’)

Add the following line just after the database details in .env.
.env

DB_HOST=localhost;unix_socket=/Applications/MAMP/tmp/mysql/mysql.sock


Step 3: Install  Package For Paypal Using Composer

This is going to be the foundational step of this tutorial. Generically, to integrate payment gateway in Laravel is not that difficult. We can rely on srmklive/paypal composer package.

Run the command to install the package, and through this plugin, we are going to integrate Paypal Payment Gateway in Laravel 8...

composer require srmklive/paypal

As soon as you are done with the plugin installation. Get inside the config/app.php and register the required PayPal service in providers and aliases arrays.
app.php

....
....
providers' => [

    ....

    Srmklive\PayPal\Providers\PayPalServiceProvider::class

]
....
....
providers' => [

    ....

    'PayPal' => Srmklive\PayPal\Facades\PayPal::class

]

The archetype of the srmklive’s PayPal package allows custom changes through the following command and set up the config file in config/paypal.php.

As soon as you run the command mentioned above, you will see the theoretical output in the config/paypal.php file.
paypal.php

<?php
/**
 * PayPal Setting & API Credentials
 * Created by Raza Mehdi <[email protected]>.
 */

return [
    'mode'    => env('PAYPAL_MODE', 'sandbox'), // Can only be 'sandbox' Or 'live'. If empty or invalid, 'live' will be used.
    'sandbox' => [
        'username'    => env('PAYPAL_SANDBOX_API_USERNAME', ''),
        'password'    => env('PAYPAL_SANDBOX_API_PASSWORD', ''),
        'secret'      => env('PAYPAL_SANDBOX_API_SECRET', ''),
        'certificate' => env('PAYPAL_SANDBOX_API_CERTIFICATE', ''),
        'app_id'      => 'APP-80W284485P519543T', // Used for testing Adaptive Payments API in sandbox mode
    ],
    'live' => [
        'username'    => env('PAYPAL_LIVE_API_USERNAME', ''),
        'password'    => env('PAYPAL_LIVE_API_PASSWORD', ''),
        'secret'      => env('PAYPAL_LIVE_API_SECRET', ''),
        'certificate' => env('PAYPAL_LIVE_API_CERTIFICATE', ''),
        'app_id'      => '', // Used for Adaptive Payments API
    ],

    'payment_action' => 'Sale', // Can only be 'Sale', 'Authorization' or 'Order'
    'currency'       => env('PAYPAL_CURRENCY', 'USD'),
    'billing_type'   => 'MerchantInitiatedBilling',
    'notify_url'     => '', // Change this accordingly for your application.
    'locale'         => '', // force gateway language  i.e. it_IT, es_ES, en_US ... (for express checkout only)
    'validate_ssl'   => true, // Validate SSL when creating api client.
];


Step 4: Configuration paypal.php file

Here are the details that we are going to register in the .env file. We are testing PayPal payments with PayPal username, secret, and signature key, as mentioned below.

Follow this article to get your Sandbox API credentials.

You will see such type of popup screen consist of your API Credentials.


Step 5: Create Route

Routes are essentials, HTTP methods can be bound with routes to take care of incoming or outgoing data.

In this foundational step, we will create three routes simultaneously with the GET method to handle Payments in Laravel, Payment Success, and Payment Cancelation. Let’s respectively define all the routes inside the routes/web.php file.
web.php

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| here is wherein you may register web routes for your application. these
| routes are loaded with the aid of the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something tremendous!|
|
*/

Route::get('/', function () {
    return view('home');
});


Route::get('handle-payment', 'PayPalPaymentController@handlePayment')->name('make.payment');
Route::get('cancel-payment', 'PayPalPaymentController@paymentCancel')->name('cancel.payment');
Route::get('payment-success', 'PayPalPaymentController@paymentSuccess')->name('success.payment');


Step 6: Create Controller

So far, we have cautiously and consecutively dealt with every situation. To comprehend the payment gateway integration process. Theoretically, we have to create a controller, and define the required functions and methods to make, cancel the payment with prudence.

Run command to generate a new controller.

php artisan make:controller PayPalPaymentController

In response to the above command, we have got a new controller file. You can now invoke the app/Http/Controllers/PayPalPaymentController.php file by adding the following code.
PayPalPaymentController.php

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Srmklive\PayPal\Services\ExpressCheckout;

class PayPalPaymentController extends Controller
{
    public function handlePayment()
    {
        $product = [];
        $product['items'] = [
            [
                'name' => 'Nike Joyride 2',
                'price' => 112,
                'desc'  => 'Running shoes for Men',
                'qty' => 2
            ]
        ];
  
        $product['invoice_id'] = 1;
        $product['invoice_description'] = "Order #{$product['invoice_id']} Bill";
        $product['return_url'] = route('success.payment');
        $product['cancel_url'] = route('cancel.payment');
        $product['total'] = 224;
  
        $paypalModule = new ExpressCheckout;
  
        $res = $paypalModule->setExpressCheckout($product);
        $res = $paypalModule->setExpressCheckout($product, true);
  
        return redirect($res['paypal_link']);
    }
   
    public function paymentCancel()
    {
        dd('Your payment has been declend. The payment cancelation page goes here!');
    }
  
    public function paymentSuccess(Request $request)
    {
        $paypalModule = new ExpressCheckout;
        $response = $paypalModule->getExpressCheckoutDetails($request->token);
  
        if (in_array(strtoupper($response['ACK']), ['SUCCESS', 'SUCCESSWITHWARNING'])) {
            dd('Payment was successfull. The payment success page goes here!');
        }
  
        dd('Error occured!');
    }
}


Step 7: Create blade View

Create a product.blade.php file, and here we will create a simple button. By clicking on this button, you will be able to see the PayPal payment gateway in action. Meanwhile, you incorporate the following code inside the blade view template file.
product.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel 8 PayPal Payment Gateway Integration - MEANINGARTICLES.COM</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
</head>

<body>
    <div class="container mt-5 text-center">
        <h2>Laravel 8 PayPal Integration Example - MEANINGARTICLES.COM</h2>

        <a href="{{ route('make.payment') }}" class="btn btn-primary mt-3">Pay $224 via Paypal</a>
    </div>
</body>

</html>

Next, we have to run the application.

php artisan serve

Above command starts your application on the following URL...

http://127.0.0.1:8000

i'm hoping it assist you to, thanks for visit my article if you like my article then proportion together with your friend and social platform.