Paypal Payment Gateway Integration in Laravel 11

Loading

Hello everyone,

In this post, we will guide you, how to implement Paypal Payment Gateway in Laravel 11. we will explain each step in detailed way that involves in implementing Paypal Payment Gateway in Laravel. if you are looking for any resources for Payment Gateway Implementation In Laravel 11 then you are right place.

Let me quickly introduce you to implement payment gateway in laravel applications, To do this, we will utilize the srmklive/paypal composer package. Firstly we will signup and generate Client ID and Secret ID, Then we will create an intent that capture payment, we will guide you through each and every steps of Paypal Payment Gateway Integration In laravel here.

Step for Laravel 10 PayPal Payment Gateway Integration

  • Step 1: Install Laravel
  • Step 2: Install srmklive/paypal Package
  • Step 3: Create PayPal Developer Account
  • Step 4: Create Route
  • Step 5: Create Controller
  • Step 6: Create Blade File
  • Run Laravel App

lets proceed to the step by step now:

1. Create a new project

Create a new project with the command as below.

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

After the new project has been created, go to your project directory.

cd paypal

2. Install Packages for Paypal Payment Gateway Using Composer

Run the following command.

we will install Laravel-Paypal for laravel 6,7, & 8

composer require srmklive/paypal:~3.0

3. Create PayPal credentials

After installing paypal package, we need client_id and secret_key for paypal integration, so we need to enter in paypal developer mode and create new sandbox account for the same. After login in paypal you need to get the client_id and secret_key as shown below. before getting client_id and secret_key we need to create application. So, check the screenshot below and build an app. Login to the Developer Dashboard.

Click Create Apps.

Next you need to add PAYPAL_MODE, PAYPAL_SANDBOX_CLIENT_ID and PAYPAL_SANDBOX_CLIENT_SECRET on .env file as like bellow:

PAYPAL_MODE=sandbox
PAYPAL_SANDBOX_CLIENT_ID=YourClientKey
PAYPAL_SANDBOX_CLIENT_SECRET=YourClientSecret

4. Create Routes

Now we will add all neccessary routes in our web.php file which you can find under routes directory

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\PayPalController;
  
/*
|--------------------------------------------------------------------------
| 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('paypal', [PayPalController::class, 'index'])->name('paypal');
Route::get('paypal/payment', [PayPalController::class, 'payment'])->name('paypal.payment');
Route::get('paypal/payment/success', [PayPalController::class, 'paymentSuccess'])->name('paypal.payment.success');
Route::get('paypal/payment/cancel', [PayPalController::class, 'paymentCancel'])->name('paypal.payment/cancel');

5. Create Controller

Now you need to make controller PaypalController using your default command console

php artisan make:controller PayPalController

and now open app/Http/Controllers/PayPalController.php. and make functions working like this

<?php
  
namespace App\Http\Controllers;
  
use Srmklive\PayPal\Services\PayPal as PayPalClient;
use Illuminate\Http\Request;
  
class PayPalController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view('paypal');
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function payment(Request $request)
    {
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $paypalToken = $provider->getAccessToken();
  
        $response = $provider->createOrder([
            "intent" => "CAPTURE",
            "application_context" => [
                "return_url" => route('paypal.payment.success'),
                "cancel_url" => route('paypal.payment/cancel'),
            ],
            "purchase_units" => [
                0 => [
                    "amount" => [
                        "currency_code" => "USD",
                        "value" => "100.00"
                    ]
                ]
            ]
        ]);
  
        if (isset($response['id']) && $response['id'] != null) {
  
            foreach ($response['links'] as $links) {
                if ($links['rel'] == 'approve') {
                    return redirect()->away($links['href']);
                }
            }
  
            return redirect()
                ->route('cancel.payment')
                ->with('error', 'Something went wrong.');
  
        } else {
            return redirect()
                ->route('create.payment')
                ->with('error', $response['message'] ?? 'Something went wrong.');
        }
    
    }
  
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function paymentCancel()
    {
        return redirect()
              ->route('paypal')
              ->with('error', $response['message'] ?? 'You have canceled the transaction.');
    }
  
    /**
     * Write code on Method 
     * Written by Appfinz Technologies
     * @return response()
     */
    public function paymentSuccess(Request $request)
    {
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $provider->getAccessToken();
        $response = $provider->capturePaymentOrder($request['token']);
  
        if (isset($response['status']) && $response['status'] == 'COMPLETED') {
            return redirect()
                ->route('paypal')
                ->with('success', 'Transaction complete.');
        } else {
            return redirect()
                ->route('paypal')
                ->with('error', $response['message'] ?? 'Something went wrong.');
        }
    }
}

6. Create View/Blade File

here, we need to create paypal.blade.php file and update following code on it.

resources/views/paypal.blade.php

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Paypal Payment Gateway Integration in Laravel - Appfinz.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="row mt-5 mb-5">
        <div class="col-10 offset-1 mt-5">
            <div class="card">
                <div class="card-header bg-primary">
                    <h3 class="text-white">Laravel PayPal Payment Gateway Integration Example - www.appfinz.com</h3>
                </div>
                <div class="card-body">
  
                    @if ($message = Session::get('success'))
                      <div class="alert alert-success alert-dismissible fade show" role="alert">
                        <strong>{{ $message }}</strong>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                      </div>
                    @endif
  
                    @if ($message = Session::get('error'))
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                          <strong>{{ $message }}</strong>
                          <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                        </div>
                    @endif
                          
                    <center>
                        <a href="{{ route('paypal.payment') }}" class="btn btn-success">Pay with PayPal </a>
                    </center>
  
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

Run Laravel App with Paypal Now

Open Command Console and hit PHP Artisan serve within the same directory of your laravel application

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/paypal

If you are looking for these tools

JPEG Image Compressor

Youtube Thumbnail Grabber

About Post Author