Laravel Livewire Subscription Integration with Stripe

Laravel Livewire Subscription Integration with Stripe

In this tutorial, learn how to implement a subscription payment system in a Laravel application using Livewire and Stripe. We’ll cover the installation of the Stripe and Livewire packages, setting up the subscription flow, and creating views to handle the payment process. Follow these steps to add subscription functionality with Stripe in your Laravel application.

Step 1: Install Livewire and Stripe Packages

First, install Laravel Livewire and the Stripe SDK via Composer:

composer require livewire/livewire
composer require stripe/stripe-php

Step 2: Configure Stripe API Keys

Get your API keys from the Stripe Dashboard and add them to your .env file:


STRIPE_KEY=your_stripe_public_key
STRIPE_SECRET=your_stripe_secret_key

Step 3: Create a Livewire Component for Subscription

Generate a Livewire component to handle the subscription logic. Run the following command:

php artisan make:livewire SubscriptionForm

In the generated component, open app/Http/Livewire/SubscriptionForm.php and add the following code to set up Stripe's checkout session and handle subscriptions:


<?php
namespace App\Http\Livewire;

use Livewire\Component;
use Stripe\Stripe;
use Stripe\Checkout\Session;

class SubscriptionForm extends Component
{
    public $plan;

    public function mount($planId)
    {
        $this->plan = $planId;
    }

    public function createCheckoutSession()
    {
        Stripe::setApiKey(env('STRIPE_SECRET'));

        $session = Session::create([
            'payment_method_types' => ['card'],
            'line_items' => [[
                'price' => $this->plan,
                'quantity' => 1,
            ]],
            'mode' => 'subscription',
            'success_url' => route('subscription.success'),
            'cancel_url' => route('subscription.cancel'),
        ]);

        return redirect($session->url);
    }

    public function render()
    {
        return view('livewire.subscription-form');
    }
}

Step 4: Define Routes for Subscription

Define routes in your web.php file to handle the subscription process. These include routes for the checkout page, success, and cancellation:


use App\Http\Livewire\SubscriptionForm;

Route::get('/subscribe/{plan}', SubscriptionForm::class);
Route::get('/subscription/success', function () {
    return 'Subscription successful!';
})->name('subscription.success');

Route::get('/subscription/cancel', function () {
    return 'Subscription canceled.';
})->name('subscription.cancel');

Step 5: Create the Subscription Blade View

In resources/views/livewire/subscription-form.blade.php, create a view that will display a "Subscribe" button to initiate the subscription:


<div>
    <h3>Subscribe to our Plan</h3>
    <button wire:click="createCheckoutSession" class="btn btn-primary">Subscribe Now</button>
</div>

Step 6: Include Livewire Scripts

In your main layout file (e.g., resources/views/layouts/app.blade.php), include Livewire’s styles and scripts:


<head>
    ...
    <livewire:styles />
</head>

<body>
    ...
    <livewire:scripts />
</body>

Conclusion

By following these steps, you can set up a subscription payment system using Livewire and Stripe in Laravel. This integration provides a smooth, interactive subscription flow for users. Remember to test the subscription with Stripe's test mode before switching to live credentials in production.

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.

Laravel UPI Payment Integration with Razorpay

Laravel UPI Payment Integration with Razorpay

Learn how to set up UPI payments in a Laravel application using Razorpay's API. This tutorial covers installing Razorpay's PHP SDK, setting up routes, and creating views to handle UPI transactions. Follow the steps below to get started with UPI payments in Laravel.

Step 1: Install the Razorpay PHP SDK

To begin, open your terminal and install the Razorpay PHP SDK via Composer:

composer require razorpay/razorpay

Step 2: Configure Razorpay API Keys

After installing the SDK, go to your Razorpay Dashboard and get your API Key ID and API Key Secret. Add them to your .env file:


RAZORPAY_KEY_ID=your_key_id
RAZORPAY_KEY_SECRET=your_key_secret

Step 3: Create a Payment Controller

In Laravel, create a controller to manage payment requests. Run the following Artisan command to create it:

php artisan make:controller PaymentController

Then, open PaymentController.php and add methods to initiate and verify the payment. Here’s the code for the controller:


<?php
namespace App\Http\Controllers;

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

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

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

    // Initiate Payment
    public function initiatePayment()
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);
        $order = $api->order->create([
            'amount' => 5000, // Amount in paise (e.g., 5000 paise = ₹50)
            'currency' => 'INR',
            'payment_capture' => 1, // Auto-capture payment
        ]);

        return view('payment.initiate', ['orderId' => $order->id, 'razorpayId' => $this->razorpayId]);
    }

    // Verify Payment
    public function verifyPayment(Request $request)
    {
        $api = new Api($this->razorpayId, $this->razorpayKey);

        try {
            $attributes = [
                'razorpay_order_id' => $request->input('razorpay_order_id'),
                'razorpay_payment_id' => $request->input('razorpay_payment_id'),
                'razorpay_signature' => $request->input('razorpay_signature'),
            ];
            $api->utility->verifyPaymentSignature($attributes);
            return redirect('/')->with('success', 'Payment successful.');
        } catch (\Exception $e) {
            return redirect('/')->with('error', 'Payment verification failed.');
        }
    }
}

Step 4: Define Routes for Payment

Add the following routes in your web.php file to handle payment initiation and verification:


use App\Http\Controllers\PaymentController;

Route::get('/payment', [PaymentController::class, 'initiatePayment']);
Route::post('/payment/verify', [PaymentController::class, 'verifyPayment']);

Step 5: Create a Payment View

Create a Blade view in resources/views/payment/initiate.blade.php to display the payment interface:


<!DOCTYPE html>
<html>
<head>
    <title>UPI Payment</title>
    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
</head>
<body>
    <h2>Pay with UPI</h2>
    <button id="payButton">Pay ₹50 with UPI</button>

    <script>
        document.getElementById('payButton').onclick = function () {
            var options = {
                "key": "{{ $razorpayId }}",
                "amount": "5000", // Amount in paise (₹50)
                "currency": "INR",
                "name": "Your Company Name",
                "order_id": "{{ $orderId }}",
                "handler": function (response) {
                    fetch("/payment/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 ? "Payment successful!" : "Payment failed"));
                }
            };
            var rzp1 = new Razorpay(options);
            rzp1.open();
        };
    </script>
</body>
</html>

Conclusion

With these steps, you can easily set up UPI payments in Laravel using Razorpay. Once testing is complete, switch to live credentials in the Razorpay dashboard. This setup enables seamless UPI transactions in your Laravel application.