Integrating Razorpay in Laravel 8 - deesoft service

Integrating Razorpay in Laravel 8

Deepak Tailor Image
Deepak Tailor - Jul 29 2023
Integrating Razorpay in Laravel 8

Introduction

In the fast-paced digital age, the world of e-commerce and online transactions continues to thrive. As businesses move online, offering a seamless and secure payment gateway is essential for user satisfaction and business success. Laravel, a popular PHP web framework, provides developers with a robust platform to build web applications, including online stores and payment processing systems. One of the most versatile and user-friendly payment gateways that can be seamlessly integrated into Laravel projects is Razorpay.

In this comprehensive guide, we will walk you through the step-by-step process of integrating Razorpay into a Laravel 8 application. From the initial setup to creating routes and files, we will cover all the essential aspects of the integration process. By the end of this article, you will have a solid understanding of how to implement Razorpay and simplify online payment processing for your Laravel-based web application.

Integrating the Razorpay payment gateway into a Laravel 8 application can be accomplished step-by-step by following the instructions below:

How to Install Laravel

Before we dive into the integration process, let's quickly go over the installation steps for Laravel 8. If you have already set up Laravel, feel free to skip this section.

1. Prerequisites: Ensure that you have PHP, Composer, and Laravel Installer installed on your system. You can install them by following the official documentation for each tool.

2. Install Laravel: Open your terminal or command prompt and run the following command to install Laravel using the Laravel Installer:

composer global require laravel/installer

3. Create a New Laravel Project: Once Laravel Installer is installed, navigate to the directory where you want to create your project and execute the following command:

laravel new project-name

4. Start Development Server: Move into the newly created project directory:

cd project-name

Launch the development server with the following command:

php artisan serve

Congratulations! You now have a Laravel 8 project up and running.

How to Install the Laravel Razorpay Package

Laravel offers a convenient way to integrate external packages using Composer. To integrate Razorpay into your Laravel project, follow these steps:

1. Require Package: In your terminal, navigate to your Laravel project directory and execute the following command to install the Laravel Razorpay package via Composer:

composer require anandpilania/laravel-razorpay

2. Service Provider (For Laravel 5.5 and below): If you are using Laravel version 5.5 or below, add the Razorpay package's service provider to the config/app.php file in the providers array:

'providers' => [
    // Other providers...
    Anand\LaravelRazorpay\RazorpayServiceProvider::class,
],

3. Publish Configuration File (Optional): If you wish to modify any Razorpay integration settings, you can publish the configuration file. Run the following command in the terminal:

php artisan vendor:publish --provider="Anand\LaravelRazorpay\RazorpayServiceProvider"

To create a controller and blade files for the example payment process using Razorpay in Laravel 8, follow the steps below:

Step 1: Create a Controller

Run the following Artisan command in your terminal to create a controller named PaymentController:

php artisan make:controller PaymentController

Step 2: Implement Controller Methods

Open the PaymentController located at app/Http/Controllers/PaymentController.php. Add the necessary methods for payment processing:

namespace App\Http\Controllers;

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

class PaymentController extends Controller
{
    // Method to show the payment form
    public function showPaymentPage()
    {
        return view('payment');
    }

    // Method to process the payment
    public function processPayment(Request $request)
    {
        // Initialize Razorpay API with your key and secret
        $razorpayKey = 'your_razorpay_key';
        $razorpaySecret = 'your_razorpay_secret';
        $api = new Api($razorpayKey, $razorpaySecret);

        // Get payment details from the form
        $amount = $request->input('amount') * 100; // Amount in paise
        $currency = 'INR'; // Change to your desired currency code

        // Create an order on Razorpay
        $order = $api->order->create(array(
            'amount' => $amount,
            'currency' => $currency,
            'payment_capture' => 1 // Auto-capture the payment
        ));

        // Get the order ID
        $orderId = $order['id'];

        // Return the order ID to the payment form
        return response()->json(['order_id' => $orderId]);
    }

    // Method to handle payment success
    public function paymentSuccess()
    {
        return view('payment_success');
    }

    // Method to handle payment failure
    public function paymentFailure()
    {
        return view('payment_failure');
    }
}

Step 3: Create Blade Views

Create two new blade view files named payment.blade.php, payment_success.blade.php, and payment_failure.blade.php in the resources/views directory.

1.payment.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Payment Page</title>
</head>
<body>
    <h1>Make Payment</h1>
    <form action="{{ route('payment.process') }}" method="POST">
        @csrf
        <label for="amount">Amount (in INR):</label>
        <input type="text" name="amount" id="amount">
        <button type="submit">Pay Now</button>
    </form>

    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <script>
        // Handle Razorpay payment success/failure
        var orderId = @json($orderId);
        var razorpayKey = 'your_razorpay_key'; // Replace with your Razorpay key

        function onPaymentSuccess(response) {
            window.location.href = '{{ route('payment.success') }}';
        }

        function onPaymentFailure(error) {
            window.location.href = '{{ route('payment.failure') }}';
        }

        var options = {
            key: razorpayKey,
            amount: document.getElementById('amount').value * 100,
            currency: 'INR',
            name: 'Your Website Name',
            description: 'Payment for Order #123',
            order_id: orderId,
            handler: function(response) {
                onPaymentSuccess(response);
            },
            prefill: {
                name: 'John Doe',
                email: 'john.doe@example.com',
                contact: '+919876543210'
            }
        };

        var rzp = new Razorpay(options);

        document.querySelector('form').addEventListener('submit', function(e) {
            e.preventDefault();
            rzp.open();
        });
    </script>
</body>
</html>

2. payment_success.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Payment Success</title>
</head>
<body>
    <h1>Payment Successful!</h1>
    <p>Thank you for your payment. Your transaction has been completed successfully.</p>
</body>
</html>

3. payment_failure.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Payment Failure</title>
</head>
<body>
    <h1>Payment Failed</h1>
    <p>Oops! Something went wrong with your payment. Please try again later.</p>
</body>
</html>

Step 4: Define Routes

Open the routes/web.php file and add the following routes:

use App\Http\Controllers\PaymentController;

Route::get('/payment', [PaymentController::class, 'showPaymentPage'])->name('payment');
Route::post('/payment-process', [PaymentController::class, 'processPayment'])->name('payment.process');
Route::get('/payment-success', [PaymentController::class, 'paymentSuccess'])->name('payment.success');
Route::get('/payment-failure', [PaymentController::class, 'paymentFailure'])->name('payment.failure');

Conclusion

Congratulations! You have successfully created a controller and blade views to implement the example payment process using Razorpay in your Laravel 8 application. The payment form (payment.blade.php) will allow users to make payments, and based on the payment status, they will be redirected to the appropriate success (payment_success.blade.php) or failure (payment_failure.blade.php) page. Feel free to customize the views and add more functionality to suit your specific requirements. Happy coding!

Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
----
You can contact him at deepaktailor10@yahoo.in