How to Integrate PayPal Payment Gateway in Laravel 10 - Part 2

Category: Laravel
Updated on: 01 Nov, 2024
First, you have to install a fresh version of Laravel 10. You can go to the official documentation of Laravel:
You will see a section there: "Creating A Laravel Project". Here you will get your codes to install Laravel 10. I am going to write the commands you will need to install laravel. First, open your terminal where you want to install laravel on your computer. Then use these commands:
composer create-project laravel/laravel example-app
cd example-app
php artisan serve
You can run your application now using this url into your browser: http://127.0.0.1:8000
Now go to this location: resources > views > welcome.blade.php.

Change the codes of this page like this:
welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Laravel - PayPal Integration</title>
</head>
<body>
    <h2>Product: Laptop</h2>
    <h3>Price: $5</h3>
    <form action="{{ route('paypal') }}" method="post">
        @csrf
        <input type="hidden" name="price" value="5">
        <input type="hidden" name="product_name" value="Laptop">
        <input type="hidden" name="quantity" value="1">
        <button type="submit">Pay with payPal</button>
    </form>
</body>
</html>
There are many packages available using which you can integrate paypal easily in your application. You can use this package:
They have a doc file here from where you will be able to understand how to install this package.
Go to the folder where you have install laravel and open terminal there. Then put this code:
composer require srmklive/paypal:~3.0
Now go to "Publish Assets" section and copy the code. Then paste it into your terminal:
php artisan vendor:publish --provider "Srmklive\PayPal\Providers\PayPalServiceProvider"
I have these information according to the last episode:
Developer Account Email: developer@cwa.com
Personal Sandbox Account Email: sb-vhfyz28322584@personal.example.com
Business Sandbox Account Email: sb-6l43bc27296072@business.example.com
Client Id: AUepW_R8YYWL7R9nASWIkYSvoLg_3KzYFeb-tt0KMWuWOBwX_JmYlMGKMWbsg_bhPIB2CoNNy5AGk1dm
Secret: EFuwGqxMAPpSMCoxkmo6-WWnt02EjZFNtdN39Z9Ay-rmruF2gR2MmCPdQn1Rk1fH5z93yd96fB5hqP6s
You know I have the API credentials like client id and secret. Now I will use those. Copy the following code and into the last of .env file add it:
#PayPal API Mode
# Values: sandbox or live (Default: live)
PAYPAL_MODE=sandbox

#PayPal Setting & API Credentials - sandbox
PAYPAL_SANDBOX_CLIENT_ID=AUepW_R8YYWL7R9nASWIkYSvoLg_3KzYFeb-tt0KMWuWOBwX_JmYlMGKMWbsg_bhPIB2CoNNy5AGk1dm
PAYPAL_SANDBOX_CLIENT_SECRET=EFuwGqxMAPpSMCoxkmo6-WWnt02EjZFNtdN39Z9Ay-rmruF2gR2MmCPdQn1Rk1fH5z93yd96fB5hqP6s

#PayPal Setting & API Credentials - live
#PAYPAL_LIVE_CLIENT_ID=
#PAYPAL_LIVE_CLIENT_SECRET=
In .env file, setup database name, username and password. In my case, it is:
DB_DATABASE=paypal
DB_USERNAME=root
DB_PASSWORD=root
Create a migration file using this command:
php artisan make:migration create_payments_table
A migration file will be created in this location: "database > migrations > 2023_11_22_054928_create_payments_table.php"

Now write the following code here:
2023_11_22_114935_create_payments_table
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('payments', function (Blueprint $table) {
            $table->id();
            $table->string('payment_id');
            $table->string('product_name');
            $table->string('quantity');
            $table->string('amount');
            $table->string('currency');
            $table->string('payer_name');
            $table->string('payer_email');
            $table->string('payment_status');
            $table->string('payment_method');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('payments');
    }
};
Write this command to create the "payments" table.
php artisan migrate
You have to create a model now. The model name will be the singular form of the table name. So it will be "Payment". Run this command in the terminal to create this model:
php artisan make:model Payment
I am going to create a controller now. So run this command in terminal:
php artisan make:controller PaypalController
PaypalController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Srmklive\PayPal\Services\PayPal as PayPalClient;
use App\Models\Payment;

class PaypalController extends Controller
{
    public function paypal(Request $request)
    {
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $paypalToken = $provider->getAccessToken();
        $response = $provider->createOrder([
            "intent" => "CAPTURE",
            "application_context" => [
                "return_url" => route('success'),
                "cancel_url" => route('cancel')
            ],
            "purchase_units" => [
                [
                    "amount" => [
                        "currency_code" => "USD",
                        "value" => $request->price
                    ]
                ]
            ]
        ]);
        //dd($response);
        if(isset($response['id']) && $response['id']!=null) {
            foreach($response['links'] as $link) {
                if($link['rel'] === 'approve') {
                    session()->put('product_name', $request->product_name);
                    session()->put('quantity', $request->quantity);
                    return redirect()->away($link['href']);
                }
            }
        } else {
            return redirect()->route('cancel');
        }
    }
    public function success(Request $request)
    {
        $provider = new PayPalClient;
        $provider->setApiCredentials(config('paypal'));
        $paypalToken = $provider->getAccessToken();
        $response = $provider->capturePaymentOrder($request->token);
        //dd($response);
        if(isset($response['status']) && $response['status'] == 'COMPLETED') {
            
            // Insert data into database
            $payment = new Payment;
            $payment->payment_id = $response['id'];
            $payment->product_name = session()->get('product_name');
            $payment->quantity = session()->get('quantity');
            $payment->amount = $response['purchase_units'][0]['payments']['captures'][0]['amount']['value'];
            $payment->currency = $response['purchase_units'][0]['payments']['captures'][0]['amount']['currency_code'];
            $payment->payer_name = $response['payer']['name']['given_name'];
            $payment->payer_email = $response['payer']['email_address'];
            $payment->payment_status = $response['status'];
            $payment->payment_method = "PayPal";
            $payment->save();

            return "Payment is successful";

            unset($_SESSION['product_name']);
            unset($_SESSION['quantity']);

        } else {
            return redirect()->route('cancel');
        }
    }
    public function cancel()
    {
        return "Payment is cancelled.";
    }
}
Now go to "route > web.php"
web.php
<?php

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

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

Route::post('paypal', [PaypalController::class, 'paypal'])->name('paypal');
Route::get('success', [PaypalController::class, 'success'])->name('success');
Route::get('cancel', [PaypalController::class, 'cancel'])->name('cancel');

See Full Tutorial on YouTube

If you want to see the full functionality in live, you can see my videos in youtube.
Part 2 - Video 1
Part 2 - Video 2

Download Source Code

Please give your email address. We will send you the source code on your email.