How to add Stripe payment gateway to Laravel

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Integrating a payment gateway into a web application is essential for businesses today. Stripe is one of the most powerful and widely used payment gateways, providing a variety of payment processing solutions for online businesses. Laravel, being a robust and popular PHP framework, offers a clean and simple way to integrate Stripe using its built-in functionalities and packages. In this tutorial, we’ll walk you through the process of adding Stripe to a Laravel application, from setup to successful payment processing.

Setting Up Your Environment

Before integrating Stripe into your Laravel application, you’ll need to have a development environment ready. Ensure you have Composer and Laravel installed on your system. Create a new Laravel project if you haven’t already, or navigate to your existing project directory. Next, you’ll need the Stripe PHP SDK, which you can install via Composer:

composer require stripe/stripe-php

After installing the Stripe PHP SDK, set up your Stripe keys. You’ll find these in your Stripe Dashboard under the Developers < code > API keys < / code > section. Set your secret key and publishable key in your .env file:

STRIPE_KEY=your_publishable_key STRIPE_SECRET=your_secret_key

Adding the Stripe Service Provider

Laravel includes a Service Provider that helps in registering services and dependencies. Place the following service provider inside your config/app.php file’s providers array:

App\Providers\StripeServiceProvider::class,

You will need to create this service provider. Use the following Laravel artisan command:

php artisan make:provider StripeServiceProvider

In your newly created StripeServiceProvider, register the Stripe client:

use Stripe\StripeClient;

public function register()
{
    $this->app->singleton(StripeClient::class, function ($app) {
        return new StripeClient(config('services.stripe.secret'));
    });
}

Don’t forget to add Stripe credentials to your config/services.php:

'stripe' => [
    'model' => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Preparing the Frontend

The next step is to prepare your application’s frontend to accept payment information. Stripe provides a feature called Stripe.js and Stripe Elements, which allow you to securely collect payment details. Include Stripe.js in your blade template:

<script src="https://js.stripe.com/v3/"></script>

Create a form that will receive credit card information using Stripe Elements:

<form id="payment-form">
    <div id="card-element">
        <!-- Stripe.js injects the Card Element -->
    </div>
    
    <!-- Add a button to submit the form -->
    <button id="submit">Pay</button>
</form>

The button will be disabled until Stripe.js fully loads. Add the necessary JavaScript to mount the elements and handle the form submission:

<script>
    var stripe = Stripe('your_publishable_key');
    var elements = stripe.elements();

    var card = elements.create('card');
    card.mount('#card-element');

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

        stripe.createToken(card).then(function(result) {
            if (result.error) {
                // Inform the user if there was an error.
            } else {
                // Send the token to your server.
            }
        });
    });
</script>

Creating the Payment Route and Controller

In your web.php file, create a route for processing the payment:

Route::post('/payment', 'PaymentController@store');

Then, generate a PaymentController:

php artisan make:controller PaymentController

In your PaymentController, add the function to handle the payment:

use Stripe\StripeClient;
use Illuminate\Http\Request;

class PaymentController extends Controller
{
    protected $stripe;

    public function __construct(StripeClient $stripe)
    {
        $this->stripe = $stripe;
    }

    public function store(Request $request)
    {
        $token = $request->stripeToken;

        try {
            $charge = $this->stripe->charges->create([
                'amount' => 1000, // $10, in cents
                'currency' => 'usd',
                'description' => 'Example charge',
                'source' => $token,
            ]);
        } catch (\Exception $e) {
            return back()->with('error', $e->getMessage());
        }

        return back()->with('success', 'Payment successful');
    }
}

With this code, you can process payments through Stripe. Ensure to handle exceptions properly to avoid exposing sensitive information.

Testing the Integration

Before making your application live, test the payment flow using Stripe’s test mode and card numbers. Switch to ‘Viewing test data’ in your Stripe Dashboard, and you can use test card numbers provided by Stripe for simulation.

Remember to add CSRF protection in your payment form:

@csrf

See also: How to disable/enable CSRF protection in Laravel.

and ensure that you’re passing the Stripe token to your route by adding it to your form using a hidden input:

<input type="hidden" name="stripeToken" id="stripeToken">

This setup is for a simple one-time payment. However, Stripe can handle much more complex scenarios such as subscriptions, which would require additional steps to manage.

Conclusion

Integrating Stripe into Laravel is a straightforward process that significantly empowers your application’s payment processing capabilities. By following the methods detailed in this tutorial, you can add robust payment functionalities to your Laravel project and customize it according to your business needs. Remember to handle sensitive data with care and always keep your Stripe and Laravel packages up to date for security and performance improvements.