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

Advanced Certified MLOps Professional Program for Scalable AI Model Deployment Systems

Introduction The Certified MLOps Professional program from AIOpsSchool has emerged as a vital benchmark for engineers looking to bridge the gap between data science and production engineering….

Read More

Powerful Certified MLOps Engineer Program to Build Reliable ML Infrastructure

Introduction The integration of Machine Learning into production environments has created a significant gap between data science and traditional software engineering. The Certified MLOps Engineer program is…

Read More

Professional Skill Alignment Around MLOps Foundation Certification in Modern Workplaces

Introduction The MLOps Foundation Certification has emerged as a critical benchmark for professionals looking to bridge the gap between data science and production engineering. This guide is…

Read More

Certified AIOps Manager: Strategic Framework for Intelligent IT Operations

Introduction The Certified AIOps Manager program is a specialized training designed to help professionals lead the next wave of IT operations. This guide is for engineers and…

Read More

Advanced AIOps Architect Certification Roadmap for DevOps Engineers

Introduction The Certified AIOps Architect is a comprehensive professional program designed for engineers and architects who want to master the intersection of Artificial Intelligence and IT Operations….

Read More

Advanced Certified AIOps Professional Guide for Mastering AI Driven Operations Skills

Introduction Artificial Intelligence for IT Operations is the future of managing complex systems and large scale digital environments. The Certified AIOps Professional program is designed for those…

Read More