Implement Razorpay Payment in Laravel: A Complete Guide

by Saloni 3 minute read 7 views

Integrating Razorpay with Laravel ensures secure payments, seamless checkout, easy setup, real-time verification, and smooth transactions for businesses, developers, and modern web applications.

Key Points

  • Integrating Razorpay with Laravel payment systems results in 35% higher checkout conversion rates.
  • 99.9% uptime guarantees that businesses can process payments without interruptions or technical downtime.
  • More than 8 million businesses depend on Razorpay for secure payments and seamless customer experiences.

Introduction

Seamless payment integration is vital for custom website and web app development. Without a secure and smooth payment gateway, businesses risk losing customers at checkout. That’s why many developers opt for Razorpay, a trusted platform that supports payments via UPI, credit/debit cards, wallets, and net banking.

Integrating Razorpay into your Laravel backend gives users a smooth, secure, and easy transaction experience. Whether you're creating an eCommerce platform, SaaS solution, or subscription service, Razorpay provides the right APIs and SDKs to make integration simple.

This step-by-step guide will walk you through how to implement Razorpay payment in Laravel, ensuring you can create a full-stack payment solution that improves user experience and business efficiency.

Why Razorpay for Payment Integration?

Before diving into the Laravel code, let’s look at why Razorpay is preferred for custom web app development projects:

  • Supports Multiple Payment Modes: Accept UPI, cards, wallets, and net banking.
  • Easy API Integration: Razorpay provides developer-friendly APIs and SDKs that make integration hassle-free.
  • Secure Transactions: Built-in encryption ensures customer data and payments are secure.
  • Real-Time Tracking: Get live updates on all transactions through the dashboard.
  • Webhook Support: Automate your system to capture transaction status updates without manual intervention.
  • International Payments: Expand your business globally with multi-currency support.

By choosing Razorpay, you simplify the payment process and enhance customer trust, which is key in custom website development and SaaS solutions.

Setting Up Razorpay Account

  1. Login to the Razorpay Dashboard.
  2. Go to Settings > API Keys.
  3. Generate a Test Key (for development).
  4. Save both key_id and key_secret.

Switch to Live Keys when you deploy your Laravel application.

Step 1: Install Razorpay SDK in Laravel

Run the following command:

                                        composer require razorpay/razorpay
                                    

This installs Razorpay’s official PHP SDK.

Step 2: Configure Environment Variables

In your Laravel .env:

                                        RAZORPAY_KEY_ID=rzp_test_123456
RAZORPAY_SECRET=your_test_secret
                                    

Step 3: Create Payment Controller

Run:

                                        php artisan make:controller PaymentController
                                    

Edit app/Http/Controllers/PaymentController.php:

                                        <?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Razorpay\Api\Api;

class PaymentController extends Controller
{
    // Create Razorpay Order
    public function createOrder(Request $request)
    {
        $api = new Api(env('RAZORPAY_KEY_ID'), env('RAZORPAY_SECRET'));

        $order = $api->order->create([
            'receipt'  => 'receipt_' . time(),
            'amount'   => $request->amount, // in paise (₹500 = 50000)
            'currency' => 'INR'
        ]);

        return response()->json([
            'success' => true,
            'orderId' => $order['id']
        ]);
    }

    // Verify Razorpay Payment
    public function verifyPayment(Request $request)
    {
        $razorpayOrderId   = $request->orderId;
        $razorpayPaymentId = $request->razorpayPaymentId;
        $razorpaySignature = $request->razorpaySignature;

        $generatedSignature = hash_hmac(
            'sha256',
            $razorpayOrderId . "|" . $razorpayPaymentId,
            env('RAZORPAY_SECRET')
        );

        if ($generatedSignature === $razorpaySignature) {
            return response()->json([
                'success' => true,
                'message' => 'Payment verified successfully'
            ]);
        } else {
            return response()->json([
                'success' => false,
                'message' => 'Invalid signature'
            ]);
        }
    }
}
                                    

Step 4: Define Routes

In routes/web.php (or api.php if using APIs):

                                        use App\Http\Controllers\PaymentController;

Route::post('/create-order', [PaymentController::class, 'createOrder']);
Route::post('/verify-payment', [PaymentController::class, 'verifyPayment']);
                                    

Step 5: Create Blade Payment Page

In resources/views/payment.blade.php:

                                        <!DOCTYPE html>
<html>
<head>
    <title>Laravel Razorpay Payment</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
    <h2>Pay with Razorpay</h2>

    <form id="paymentForm">
        <input type="number" name="amount" id="amount" placeholder="Enter amount" required>
        <button type="button" id="payBtn">Pay Now</button>
    </form>

    <script>
        document.getElementById('payBtn').onclick = async function () {
            let amount = document.getElementById('amount').value;

            let response = await fetch("/create-order", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                    "X-CSRF-TOKEN": "{{ csrf_token() }}"
                },
                body: JSON.stringify({ amount: amount * 100 })
            });

            let data = await response.json();

            var options = {
                key: "{{ env('RAZORPAY_KEY_ID') }}",
                amount: amount * 100,
                currency: "INR",
                name: "Your Company",
                description: "Laravel Razorpay Integration",
                order_id: data.orderId,
                handler: async function (response) {
                    let verify = await fetch("/verify-payment", {
                        method: "POST",
                        headers: {
                            "Content-Type": "application/json",
                            "X-CSRF-TOKEN": "{{ csrf_token() }}"
                        },
                        body: JSON.stringify(response)
                    });

                    let result = await verify.json();
                    alert(result.message);
                },
                prefill: {
                    name: "Test User",
                    email: "test@example.com",
                    contact: "9876543210",
                },
                theme: {
                    color: "#3399cc",
                },
            };

            var rzp1 = new Razorpay(options);
            rzp1.open();
        }
    </script>
</body>
</html>
                                    

Step 6: (Optional but Recommended) Handle Razorpay Webhooks

For production, you should set up webhooks so payments, failures, or refunds are automatically updated in your system.

In routes/web.php:

                                        Route::post('/razorpay-webhook', [PaymentController::class, 'handleWebhook']);
                                    

In PaymentController.php:

                                        public function handleWebhook(Request $request)
{
    $payload = $request->getContent();
    $sigHeader = $request->header('X-Razorpay-Signature');

    $expectedSignature = hash_hmac('sha256', $payload, env('RAZORPAY_SECRET'));

    if ($sigHeader === $expectedSignature) {
        // Update payment status in database
        return response()->json(['status' => 'Webhook verified']);
    } else {
        return response()->json(['status' => 'Invalid signature'], 400);
    }
}
                                    

Final Words

Integrating Razorpay with Laravel is essential for modern web and custom website development projects. It enables businesses to handle transactions securely while offering users a seamless payment experience.

If you’re building an eCommerce platform, subscription service, or SaaS product, Razorpay simplifies the process with its APIs and SDKs. Developers can easily implement order creation, secure payment verification, and webhook automation for real-time transaction updates.

For businesses aiming to speed up their digital transformation, it’s advised to hire Laravel developer experts who can not only implement Razorpay but also develop scalable, secure, and high-performance applications.

By following this guide, you now have a complete roadmap to implement Razorpay in Laravel and React successfully.

Tech Stack & Version

Frontend

  • HTML
  • CSS
  • JS

Backend

  • Laravel
  • PHP
  • MySQL

Deployment

  • AWS
  • DigitalOcean
img

©2025Digittrix Infotech Private Limited , All rights reserved.