PayPal Payment Gateway Integration in Laravel

In this post, we learn Paypal payment gateway integration in Laravel step by step, Paypal Is a world-famous payment gateway and this is too easy with Laravel.

Create a PayPal account:

https://developer.paypal.com/

Step 1: Create a new Project

laravel new paypal

Step 2: Install the package omnipayvia the composer.

composer require league/omnipay omnipay/paypal

Step 3: Create some routes

app/routes/web.php

Route::post('pay', [App\Http\Controllers\paypalController::class, 'pay'])->name('paypal');
Route::get('success', [App\Http\Controllers\paypalController::class, 'success']);
Route::get('error', [App\Http\Controllers\paypalController::class, 'error']);
Route::get('myorder', [App\Http\Controllers\paypalController::class, 'myorder'])->name('myorder');

Step 4: Update the migration 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.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('paypals', function (Blueprint $table) {
            $table->id();
            $table->string('payment_id');
            $table->string('payer_id');
            $table->string('payer_email');
            $table->float('amount', 10, 2);
            $table->string('currency');
            $table->string('payment_status');
            $table->string('org_slug');
            $table->string('admin_email');
            $table->string('user_name');
            $table->string('admin_id');
            $table->string('slug');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('paypals');
    }
};

Step 5: Make a Models

Step 6: Make a controller

php artisan make:controller PaypalController

controller code :

<?php

namespace App\Http\Controllers;

use App\Models\Payment;
use Illuminate\Http\Request;
use Omnipay\Omnipay;
class paypalController extends Controller
{
    private $gateway;

    public function __construct()
    {
        $this->gateway = Omnipay::create('PayPal_Rest');
        $this->gateway->setClientId(env('PAYPAL_CLIENT_ID'));
        $this->gateway->setSecret(env('PAYPAL_SECRET_ID'));
        $this->gateway->setTestMode(true);
    }

    public function pay(Request $request)
    {
        try {
            Log::info("pay success m kya aa rha h" . $request);

            $response = $this->gateway->purchase(array(
                'amount' => $request->amount,
                'org_slug' => $request->org_slug,
                'admin_email' => $request->admin_email,
                'user_name' => $request->user_name,
                'admin_id' => $request->admin_id,
                'slug' => $request->slug,
                'currency' => env('PAYPAL_CURRENCY'),
                'returnUrl' => url('success'),
                'cancelUrl' => url('error')
            ))->send();

            if ($response->isRedirect()) {
                $response->redirect();
                $request->session()->put('admin_id', $request->admin_id); 
                $request->session()->put('org_slug', $request->org_slug); 
                $request->session()->put('admin_email', $request->admin_email); 
                $request->session()->put('user_name', $request->user_name); 
                $request->session()->put('slug', $request->slug); 
            } else {
                return $response->getMessage();
            }
        } catch (\Throwable $th) {
            return $th->getMessage();
        }
    }

    public function success(Request $request)

    {

        Log::info("paypal success m kya aa rha h" . $request);
        if ($request->input('paymentId') && $request->input('PayerID')) {

            Log::info("paypal request m kya aa rha h" . $request);
            $transaction = $this->gateway->completePurchase(
                array(
                    'payer_id' => $request->input('PayerID'),
                    'admin_id' => $request->input('admin_id'),
                    'user_name' => $request->input('user_name'),
                    'slug' => $request->input('slug'),
                    'admin_email' => $request->input('admin_email'),
                    'org_slug' => $request->input('org_slug'),
                    'transactionReference' => $request->input('paymentId'),
                )
            );


            $response = $transaction->send();
           


            if ($response->isSuccessful()) {

                Log::info("response paypal success m kya aa rha h");

                $arr = $response->getData();

                $payment = new paypal();
                $payment->payment_id = $arr['id'];
                $payment->payer_id = $arr['payer']['payer_info']['payer_id'];
                $payment->payer_email = $arr['payer']['payer_info']['email'];
                $payment->amount = $arr['transactions'][0]['amount']['total'];
                $payment->currency = env('PAYPAL_CURRENCY');
                $payment->payment_status = $arr['state'];
                $payment->admin_id = $request->session()->get('admin_id');
                $payment->user_name = $request->session()->get('user_name');
                $payment->slug = $request->session()->get('slug');
                $payment->admin_email = $request->session()->get('admin_email');
                $payment->org_slug = $request->session()->get('org_slug');
                $payment->save();
                // Store the admin_id in the session
                // $request->session()->put('admin_id', $request->input('admin_id'));
                // return "Payment is Successfull. Your Transaction Id is : " . $arr['id'];
                return back()->with("success", "Payment is Successfull. Your Transaction Id is : " . $arr['id']);
            } else {
                return $response->getMessage();
            }
        } else {
            return back()->with("danger", "Payment declined!!");
        }
    }

    public function error()
    {
        return back()->with("danger", "User declined the payment!");
    }
}

Step 7: Update .env file with PayPal credential details.

Related Posts

Best Free Programming Ebooks to Learn Software Development

Learning modern technology can feel overwhelming when tutorials are scattered across dozens of websites. Many software developers, engineering students, and IT professionals struggle to find comprehensive study…

Read More

FinOps Training: Understanding Cost Visibility and Optimization

Introduction Moving workloads to the cloud can simplify infrastructure management, but it can also introduce a new financial challenge. Teams can provision resources whenever they need them,…

Read More

The Architecture of Intelligent DataOps: From Ingestion to Automation

Introduction Modern organizations run on distributed data ecosystems. On any given day, an enterprise environment ingests, transforms, and serves petabytes of records sourced from transactional databases, external…

Read More

Transforming Data Reliability: How DataOps Platforms Drive Proactive Monitoring

Introduction Traditional monitoring focuses almost entirely on infrastructure availability and binary job execution states—whether a server is up or whether a task completed. However, modern distributed environments…

Read More

Navigating Pipeline Risks with Expert DevSecOps Consulting Services

Software delivery moves faster today than at any point in technological history. High-performing engineering organizations push code changes to production multiple times a day using automated deployment…

Read More

DevOps Support Services: Key Practices for Stable Production Environments

Introduction Running modern software infrastructure is an ongoing responsibility. A development team may successfully launch an application, but keeping that application reliable in production requires continuous attention….

Read More