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

Elevating DevSecOps and SRE Efficiency with a Software Delivery Governance Platform

Introduction Enterprise software engineering has reached a tipping point where systemic complexity threatens structural delivery stability. Modern engineering organizations routinely support highly fragmented ecosystems populated by hundreds…

Read More

Best Hospitals in India for International Patients and Affordable Surgery Costs

Introduction Global healthcare costs are rising rapidly, forcing many families to look for alternative solutions when facing serious medical diagnoses. In countries like the United States, the…

Read More

A Beginner Guide to Data Analytics Automation using Enterprise DataOps Workflows

Organizations rely heavily on fast, accurate, and reliable business intelligence to make critical commercial decisions. Whether it is predicting customer churn or managing real-time inventory levels, business…

Read More

Integrating AI Tools in DataOps Pipelines: A Comprehensive Guide

Introduction Modern organizations deal with a massive influx of data from applications, IoT devices, and cloud services. Managing these data volumes requires speed, accuracy, and agility. Traditional…

Read More

Modern Cloud DataOps Platforms for Reliable Data Pipelines

Introduction Modern organizations depend heavily on data. Every department, from finance and sales to healthcare, manufacturing, marketing, and customer support, needs reliable data to make better decisions….

Read More

Advanced DataOps Monitoring Tools for Enterprises: A Comprehensive Implementation Guide

Introduction Enterprise data environments are becoming more complex as organizations depend on cloud platforms, data lakes, data warehouses, real-time pipelines, analytics tools, and automated workflows. When one…

Read More