Laravel Subscription Payment Integration with Razorpay

Laravel Subscription Payment Integration with Razorpay

Learn how to set up subscription payments in a Laravel application using Razorpay's API. This tutorial will guide you through installing Razorpay’s PHP SDK, setting up routes, and creating views to handle recurring subscription payments. Follow these steps to integrate Razorpay’s subscription feature into your Laravel project.

Step 1: Install the Razorpay PHP SDK

Start by installing the Razorpay PHP SDK via Composer:

composer require razorpay/razorpay

Step 2: Configure Razorpay API Keys

Next, get your API Key ID and API Key Secret from the Razorpay Dashboard. Add them to your .env file:


RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_key_secret

Step 3: Create a Subscription Plan in Razorpay

In the Razorpay Dashboard, create a subscription plan with a recurring payment interval (e.g., monthly or yearly). Take note of the plan_id for this subscription, as you'll use it in your Laravel application.

Step 4: Create a Subscription Controller

Generate a controller to manage the subscription flow:

php artisan make:controller SubscriptionController

In the SubscriptionController.php, add methods to create the subscription and verify payment details. Here’s the code:


<?php
namespace App\Http\Controllers;

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

class SubscriptionController extends Controller
{
    private $razorpayId;
    private $razorpayKey;

    public function __construct()
    {
        $this->razorpayId = env('RAZORPAY_KEY_ID');
        $this->razorpayKey = env('RAZORPAY_KEY_SECRET');
    }

    // Create a new subscription
    public function createSubscription()
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        $subscription = $api->subscription->create([
            'plan_id' => 'your_plan_id', // Replace with Razorpay plan ID
            'customer_notify' => 1,
            'total_count' => 12, // Number of billing cycles
        ]);

        return view('subscription.subscribe', ['subscriptionId' => $subscription->id, 'razorpayId' => $this->razorpayId]);
    }

    // Verify subscription after payment
    public function verifySubscription(Request $request)
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        try {
            $attributes = [
                'razorpay_subscription_id' => $request->input('razorpay_subscription_id'),
                'razorpay_payment_id' => $request->input('razorpay_payment_id'),
                'razorpay_signature' => $request->input('razorpay_signature'),
            ];

            $api->utility->verifyPaymentSignature($attributes);

            return redirect('/')->with('success', 'Subscription successful.');
        } catch (\Exception $e) {
            return redirect('/')->with('error', 'Subscription verification failed.');
        }
    }
}

Step 5: Define Routes for Subscription

Add the following routes in your web.php file to handle subscription creation and verification:


use App\Http\Controllers\SubscriptionController;

Route::get('/subscribe', [SubscriptionController::class, 'createSubscription']);
Route::post('/subscribe/verify', [SubscriptionController::class, 'verifySubscription']);

Step 6: Create a Subscription View

In resources/views/subscription/subscribe.blade.php, create a Blade view to display the subscription interface:


<!DOCTYPE html>
<html>
<head>
    <title>Subscription Payment</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
    <h2>Subscribe to our Monthly Plan</h2>
    <button id="payButton">Subscribe Now</button>

    <script>
        document.getElementById('payButton').onclick = function () {
            var options = {
                "key": "{{ $razorpayId }}",
                "subscription_id": "{{ $subscriptionId }}",
                "name": "Your Company Name",
                "description": "Monthly Subscription",
                "handler": function (response) {
                    fetch("/subscribe/verify", {
                        method: "POST",
                        headers: { "Content-Type": "application/json", "X-CSRF-TOKEN": "{{ csrf_token() }}" },
                        body: JSON.stringify(response)
                    }).then(res => res.json())
                      .then(data => alert(data.success ? "Subscription successful!" : "Subscription failed"));
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        };
    </script>
</body>
</html>

Conclusion

With these steps, you can set up a subscription payment system in Laravel using Razorpay. Once you've tested your setup, switch to live credentials in Razorpay's dashboard to start accepting recurring payments. This integration allows you to manage subscription payments efficiently in your Laravel application.

No comments:

Post a Comment