How to Integrate PayPal Payment Gateway in Laravel 10

Author: | Published: | Updated: | Category: Laravel
How to Integrate PayPal Payment Gateway in Laravel? Well, thats what i am going to answer through this tutorial and that too step by step.

Laravel PayPal Integration is the essential feature, especially when developing an e-commerce app or enabling sell features.

It makes the buying experience enjoyable and offers unbound ease to users. With that, they can make payments through a PayPal account or Credit Card.

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

You will notice that you can check out quickly with its express checkout method in laravel Without a doubt, PayPal is one of the best payment gateways of the modern era.

When it comes to money transfer, then is no other payment gateway is near to it. Better UX, customer support, and more extensive network make it apart from the rush.

I will tell you about installing and using a srmklive composer package for integrating the paypal payment gateway in laravel.

You have to consecutively give the proper attention to assimilate the foundation topics of this tutorial.

Invoke New Laravel Project

As usual, i take my first step by installing the project. Here we will write the entire memoir of this tutorial. Execute the following command to install a 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

Database Settings

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.

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.

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

Install Essential Composer Package

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

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.

....
....
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.

<?php
/**
 * PayPal Setting & API Credentials
 * Created by Raza Mehdi <srmk@outlook.com>.
 */
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.
];

Inject PayPal Details

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 tutorial to get your Sandbox API credentials.

PAYPAL_MODE=sandbox
PAYPAL_SANDBOX_API_USERNAME=xxxxx-xxx-xx
PAYPAL_SANDBOX_API_PASSWORD=abc123
PAYPAL_SANDBOX_API_SECRET=xxxxxxx-xxxxx-xxx
PAYPAL_CURRENCY=USD
PAYPAL_SANDBOX_API_CERTIFICATE=

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

Laravel Paypal Integration

Define Imperative Routes

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.

<?php
use Illuminate\Support\Facades\Route;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
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');

The Controller Archetype

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.

<?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!');
    }
}

Configure 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.

<!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 7 PayPal Payment Gateway Integration Tutorial</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 7 PayPal Integration Example</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

The Final Words

Eventually, we have completed this tutorial. In this tutorial, we learned how to deal with PayPal payment integration in Laravel.

I hope you must have seen every step with your discretion and assimilate the entire process of implementing the payment gateway integration in laravel. I hope you must have comprehended the whole tutorial and i am grateful to your intensive efforts.

Your single share describes your love and verily propels my efforts, which elevates my confidence.

Lastly, you can download the full code of this tutorial from GitHub.

Loved this? Share it with others:
Digamber - Author positronX.io

An experienced full-stack developer with a passion for providing top-notch web experiences, proficient in developing both the front and back ends of a web application by utilizing the expertise of HTML, CSS, JavaScript, PHP, and Python.