stripe payment system with laravel and livewire component

author

By Freecoderteam

Jul 06, 2024

226

image

Integrating a payment system into your web application can be a daunting task. However, with the powerful combination of Laravel and Livewire, and the robust capabilities of Stripe, this task becomes significantly simpler. In this blog post, I will walk you through the steps to integrate Stripe payments into your Laravel application using Livewire components.

Prerequisites

Before we begin, ensure you have the following:

  1. A Laravel project setup
  2. Livewire installed
  3. A Stripe account
  4. Your Stripe API keys

Step 1: Install Stripe PHP SDK

First, we need to install the Stripe PHP SDK. You can do this via Composer:

composer require stripe/stripe-php

Step 2: Create the Payment Component

Let's create a Livewire component that will handle the payment process.

php artisan make:livewire PaymentForm

This will create two files: PaymentForm.php in app/Http/Livewire and payment-form.blade.php in resources/views/livewire.

Step 3: Set Up the Component

Open PaymentForm.php and set up the component as follows:

namespace App\Http\Livewire;

use Livewire\Component;
use Stripe\StripeClient;
use Gloudemans\Shoppingcart\Facades\Cart;

class PaymentForm extends Component
{
    public $token;

    public function checkout()
    {
        $stripe = new StripeClient(env('STRIPE_SECRET'));

        $stripe->charges->create([
            'amount' => Cart::subtotal() * 100,
            'currency' => 'usd',
            'source' => $this->token,
            'description' => 'My First Test Charge (created for API docs)',
        ]);
    }

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

Step 4: Create the Blade View

Next, open payment-form.blade.php and set up the Stripe elements:

<div>
    <form id="payment-form" wire:submit.prevent="checkout">
        <div id="card-element"></div>
        <div id="card-errors" role="alert"></div>
        <button class="badge-btn" type="submit" disabled>Submit Payment</button>
    </form>
</div>

@push('scripts')
<script src="https://js.stripe.com/v3/"></script>
<script>
    const stripe = Stripe('{{ env('STRIPE_KEY') }}');
    const elements = stripe.elements();
    const style = {
        base: {
            fontSize: '16px',
            color: '#32325d',
            borderRadius: '4px',
            padding: '12px 16px',
            fontFamily: '"Inter", sans-serif',
            fontSmoothing: 'antialiased',
            '::placeholder': {
                color: '#CFD7DF',
            },
        },
    };
    const cardElement = elements.create('card', {style: style});
    cardElement.mount('#card-element');

    cardElement.on('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
            document.querySelector('.badge-btn').disabled = true;
        } else {
            displayError.textContent = '';
            document.querySelector('.badge-btn').disabled = false;
        }
    });

    const form = document.getElementById('payment-form');
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        stripe.createToken(cardElement).then((result) => {
            if (result.error) {
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                @this.set('token', result.token.id);
                @this.call('checkout');
            }
        });
    });
</script>
@endpush

@push('styles')
<style>
    .badge-btn[disabled] {
        opacity: 0.5;
        cursor: not-allowed;
    }

    #card-element {
        width: 100%;
        padding: 20px;
        border: 1px solid #dfe4ea;
        border-radius: 5px;
        margin: 0 auto;
        box-shadow: 0px 10px 24px rgba(0, 0, 0, 0.03);
        background: #fff;
    }

    #card-errors {
        color: #cc686e;
        font-size: 12px;
        margin-top: 2px;
    }

    .badge-btn {
        background: #5469d4;
        font-family: Arial, sans-serif;
        color: #ffffff;
        border-radius: 4px;
        border: 0;
        padding: 12px 16px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        display: block;
        transition: all 0.2s ease;
        box-shadow: 0px 4px 5.5px 0px rgba(0, 0, 0, 0.07);
        width: 100%;
    }
</style>
@endpush

Step 5: Configure Stripe Keys

Add your Stripe keys to your .env file:

STRIPE_KEY=your_stripe_key
STRIPE_SECRET=your_stripe_secret

Step 6: Display the Component

Finally, include the component in your view:

<livewire:payment-form />

That's it! You have successfully integrated Stripe payments into your Laravel application using a Livewire component. Your users can now securely make payments using their credit cards.

Conclusion

Integrating a payment gateway like Stripe can enhance the functionality of your application and provide a seamless experience for your users. With Laravel and Livewire, you can achieve this with minimal effort and maximum efficiency.

Feel free to reach out if you have any questions or need further assistance. Happy coding!

Subscribe to Receive Future Updates

Stay informed about our latest updates, services, and special offers. Subscribe now to receive valuable insights and news directly to your inbox.

No spam guaranteed, So please don’t send any spam mail.