EN ES
Home > Web development > Laravel Tutorials > How to Integrate Stripe in Laravel 11

How to Integrate Stripe in Laravel 11

Diego Cortés
Diego Cortés
October 11, 2024
How to Integrate Stripe in Laravel 11

Integrating a payment system into your web application is essential for facilitating transactions and enhancing user experience. In this article, you will learn how to integrate Stripe, one of the most popular payment platforms, into an application developed with Laravel 11. This tutorial is helpful for both beginner and experienced developers looking to optimize payment management in their projects.

What is Stripe?

Stripe is an online payment platform that allows businesses to accept payments, send payments, and manage their business online. It provides APIs and tools that make integration simple and fast. With support for multiple currencies, payment methods, and advanced security, it is a popular choice among developers.

Prerequisites

Before you start integrating Stripe into Laravel 11, make sure you have the following:

  • PHP 8.x: Laravel 11 requires PHP 8.0 or higher.
  • Composer: Necessary for managing Laravel dependencies.
  • A Stripe account: Sign up at Stripe and get your API keys.

Creating a New Laravel Application

If you don’t have a Laravel application yet, follow these steps:

  1. Install Laravel:
  2. composer create-project --prefer-dist laravel/laravel project-name
    cd project-name
  3. Configure the database: Edit the .env file and add your database information.

Installing Stripe PHP SDK

To integrate Stripe, you first need to install the Stripe SDK. Run the following command in your terminal within your project directory:

composer require stripe/stripe-php

Configuring Stripe Credentials

Once the SDK is installed, add your API keys in the .env file. You can find your keys in the Stripe dashboard.

STRIPE_KEY=your_public_key
STRIPE_SECRET=your_secret_key

Additionally, make sure to configure the Stripe key in config/services.php:

'stripe' => [
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Creating a Payment Form

Now that you have everything set up, create a form in your view. Navigate to resources/views and create a file named payment.blade.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Payment with Stripe</title>
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body>
    <form action="{{ route('charge') }}" method="POST" id="payment-form">
        @csrf
        <div>
            <label for="card-element">Credit or Debit Card</label>
            <div id="card-element"></div>
            <div id="card-errors" role="alert"></div>
        </div>
        <button type="submit">Pay</button>
    </form>

    <script>
        var stripe = Stripe('{{ config('services.stripe.key') }}');
        var elements = stripe.elements();
        var cardElement = elements.create('card');
        cardElement.mount('#card-element');

        var form = document.getElementById('payment-form');
        form.addEventListener('submit', function(event) {
            event.preventDefault();

            stripe.createToken(cardElement).then(function(result) {
                if (result.error) {
                    // Show the error in the form
                    document.getElementById('card-errors').textContent = result.error.message;
                } else {
                    // Insert the token into the form
                    var hiddenInput = document.createElement('input');
                    hiddenInput.setAttribute('type', 'hidden');
                    hiddenInput.setAttribute('name', 'stripeToken');
                    hiddenInput.setAttribute('value', result.token.id);
                    form.appendChild(hiddenInput);

                    // Submit the form
                    form.submit();
                }
            });
        });
    </script>
</body>
</html>

Validating and Processing Payments

Create a route and a controller to handle the payment logic. First, add the route in routes/web.php:

use App\Http\Controllers\PaymentController;

Route::get('/payment', function () {
    return view('payment');
});

Route::post('/charge', [PaymentController::class, 'charge'])->name('charge');

Then, generate the controller with the following command:

php artisan make:controller PaymentController

Open app/Http/Controllers/PaymentController.php and add the following code:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe\Stripe;
use Stripe\Charge;

class PaymentController extends Controller
{
    public function charge(Request $request)
    {
        Stripe::setApiKey(config('services.stripe.secret'));

        $charge = Charge::create([
            'amount' => 1000, // Amount in cents: $10.00
            'currency' => 'usd',
            'description' => 'Test Payment',
            'source' => $request->stripeToken,
        ]);

        // Handle the successful response
        return back()->with('success', 'Payment successfully completed!');
    }
}

Handling Responses and Errors

To handle errors and display success messages, you can add a block to show messages in your payment view. In payment.blade.php, add the following right before the form:

@if(session('success'))
    <div>{{ session('success') }}</div>
@endif

@if(session('error'))
    <div>{{ session('error') }}</div>
@endif

This will allow you to display messages to the user based on whether the payment was successful or not.

Conclusion

Integrating Stripe into Laravel 11 is a relatively straightforward process that can significantly expand your application’s capabilities. By following this tutorial, you will have implemented a secure and reliable payment system, allowing your users to make transactions with ease.

Always remember to test your integration in Stripe’s test environment before going live. Additionally, consider implementing more advanced security measures depending on your application's needs. While this article covered the basics, there are many more features of Stripe that you can explore and take advantage of.

For more information, check out the official Stripe documentation and stay updated with Laravel’s updates. Happy coding!

Diego Cortés
Diego Cortés
Full Stack Developer, SEO Specialist with Expertise in Laravel & Vue.js and 3D Generalist

Categories

Page loaded in 29.21 ms