Integrating Stripe with Laravel: A Step-by-Step Guide to Secure Payment Gateways

Introduction

Laravel is a widely-used PHP framework known for its elegant syntax and ability to handle various aspects of web development with ease. One critical feature of modern web applications is the integration of payment gateways to allow seamless, secure online transactions.

In this tutorial, we'll walk through how to integrate the Stripe API, a powerful payment platform, into a Laravel project.

You'll learn how to set up, configure, and test Stripe's payment system, bringing security and simplicity to your web application.

Setting Up a Laravel Project

1. Installing Laravel via Composer

To create a new Laravel project, use the Composer package manager. Open your terminal and run:

composer create-project --prefer-dist laravel/laravel stripe-payment-tutorial

This command installs a fresh Laravel project in a folder named stripe-payment-tutorial.

This will install the Laravel framework in a directory named stripe-payment-tutorial. Once installation is complete, navigate to the project folder:

cd stripe-payment-tutorial

2. Configuring Environment Settings

Once your project is created, configure your environment settings. Rename the .env.example file to .env, then update the database credentials (if necessary) and any other settings:

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:your-app-key
APP_DEBUG=true
APP_URL=http://localhost

# Database settings
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

3. Verifying the Laravel Installation

Now, you can verify your Laravel setup by running the built-in development server:

php artisan serve

Open your browser and go to http://localhost:8000. You should see the Laravel welcome page if everything is set up correctly.

SECTION TWO

Introduction to Stripe

1. Overview of Stripe Services

Stripe is a robust payment processing platform that provides tools to accept payments, manage subscriptions, and handle other financial services. It's easy to integrate and offers excellent documentation for developers.

2. Creating a Stripe Account

Sign up at Stripe's website to get started. Once your account is created, navigate to the Developers section and generate your API keys:

  • Publishable key: This is used on the client-side (your payment form).

  • Secret key: This is used on the server-side (in your controllers) to securely process payments.

3. Obtaining API Keys

In your Stripe dashboard, under Developers > API Keys, you can find the keys needed for integration. Copy both the publishable and secret keys as they will be used in your Laravel project.

SECTION THREE

Installing the Stripe PHP Library

1. Including the Stripe Package via Composer

To work with Stripe in Laravel, install the Stripe PHP library:

composer require stripe/stripe-php

2. Setting Up Configuration in Laravel

Add the Stripe keys to your .env file:

STRIPE_KEY=your_stripe_publishable_key
STRIPE_SECRET=your_stripe_secret_key

Now, link these values in your config/services.php file:

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

3. Verifying the Installation

To verify that Stripe is installed, check your vendor folder for the stripe/stripe-php library. You can also test the setup by running a simple Stripe request in a controller.

SECTION FOUR

Setting Up the Payment Gateway

1. Creating the Payment Form

Let’s create a simple HTML form for users to input their payment information. In resources/views/, create a checkout.blade.php file:

<form action="/checkout" method="POST">
    @csrf
    <script
        src="https://js.stripe.com/v3/"
        class="stripe-button"
        data-key="{{ env('STRIPE_KEY') }}"
        data-amount="1000"
        data-name="Test Payment"
        data-description="Payment for testing purposes"
        data-currency="usd">
    </script>
</form>

2. Designing the Form UI

Use some basic CSS to style the form, making it user-friendly and responsive.

3. Implementing Form Validation

Validate user input to ensure that fields like the email address and payment amount are filled correctly before submission. Laravel’s validation system makes this easy by adding a validation step in your controller:

$request->validate([
    'email' => 'required|email',
    'amount' => 'required|numeric',
]);

Introduction

Laravel is a widely-used PHP framework known for its elegant syntax and ability to handle various aspects of web development with ease. One critical feature of modern web applications is the integration of payment gateways to allow seamless, secure online transactions. In this tutorial, we'll walk through how to integrate the Stripe API—a powerful payment platform—into a Laravel project. You'll learn how to set up, configure, and test Stripe's payment system, bringing security and simplicity to your web application.


Setting Up a Laravel Project

1. Installing Laravel via Composer

To create a new Laravel project, use the Composer package manager. Open your terminal and run:

bashCopy codecomposer create-project --prefer-dist laravel/laravel stripe-payment-tutorial

This command installs a fresh Laravel project in a folder named stripe-payment-tutorial.

2. Configuring Environment Settings

Once your project is created, configure your environment settings. Rename the .env.example file to .env, then update the database credentials (if necessary) and any other settings:

plaintextCopy codeAPP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:your-app-key
APP_DEBUG=true
APP_URL=http://localhost

# Database settings
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password

3. Verifying the Laravel Installation

Now, you can verify your Laravel setup by running the built-in development server:

bashCopy codephp artisan serve

Open your browser and go to http://localhost:8000. You should see the Laravel welcome page if everything is set up correctly.


Introduction to Stripe

1. Overview of Stripe Services

Stripe is a robust payment processing platform that provides tools to accept payments, manage subscriptions, and handle other financial services. It's easy to integrate and offers excellent documentation for developers.

2. Creating a Stripe Account

Sign up at Stripe's website to get started. Once your account is created, navigate to the Developers section and generate your API keys:

  • Publishable key: This is used on the client-side (your payment form).

  • Secret key: This is used on the server-side (in your controllers) to securely process payments.

3. Obtaining API Keys

In your Stripe dashboard, under Developers > API Keys, you can find the keys needed for integration. Copy both the publishable and secret keys as they will be used in your Laravel project.


Installing the Stripe PHP Library

1. Including the Stripe Package via Composer

To work with Stripe in Laravel, install the Stripe PHP library:

bashCopy codecomposer require stripe/stripe-php

2. Setting Up Configuration in Laravel

Add the Stripe keys to your .env file:

plaintextCopy codeSTRIPE_KEY=your_stripe_publishable_key
STRIPE_SECRET=your_stripe_secret_key

Now, link these values in your config/services.php file:

phpCopy code'stripe' => [
    'secret' => env('STRIPE_SECRET'),
],

3. Verifying the Installation

To verify that Stripe is installed, check your vendor folder for the stripe/stripe-php library. You can also test the setup by running a simple Stripe request in a controller.


Setting Up the Payment Gateway

1. Creating the Payment Form

Let’s create a simple HTML form for users to input their payment information. In resources/views/, create a checkout.blade.php file:

htmlCopy code<form action="/checkout" method="POST">
    @csrf
    <script
        src="https://js.stripe.com/v3/"
        class="stripe-button"
        data-key="{{ env('STRIPE_KEY') }}"
        data-amount="1000"
        data-name="Test Payment"
        data-description="Payment for testing purposes"
        data-currency="usd">
    </script>
</form>

2. Designing the Form UI

Use some basic CSS to style the form, making it user-friendly and responsive.

3. Implementing Form Validation

Validate user input to ensure that fields like the email address and payment amount are filled correctly before submission. Laravel’s validation system makes this easy by adding a validation step in your controller:

phpCopy code$request->validate([
    'email' => 'required|email',
    'amount' => 'required|numeric',
]);

Integrating Stripe Checkout

1. Setting Up the Client-side Integration

Stripe provides a JavaScript library, Stripe.js, for handling the payment process on the client-side. This securely handles customer input and tokenizes sensitive data.

2. Handling Customer Input

When the form is submitted, Stripe sends a token representing the customer's payment details to your server.


Implementing Server-side Logic

1. Creating a Controller for Payment Processing

Run this Artisan command to generate a controller:

php artisan make:controller PaymentController

Inside the controller, write a method to handle the payment:

public function checkout(Request $request)
{
    \Stripe\Stripe::setApiKey(env('STRIPE_SECRET'));

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

        return 'Payment Successful!';
    } catch (\Exception $e) {
        return $e->getMessage();
    }
}

This method uses the Stripe PHP library to create a charge on the server using the tokenized customer data.

2. Error Handling and Validation

It’s important to implement robust error handling in case a payment fails. For example, you might encounter errors such as invalid card details or network issues. By catching exceptions, you can gracefully handle these errors and return appropriate responses to the user.


Testing the Payment Gateway

1. Setting Up a Testing Environment

To test the payment gateway, ensure you're using the test API keys from Stripe. You can perform test transactions without affecting real customer data.

2. Using Stripe Test Cards

Stripe provides a variety of test card numbers that simulate different payment scenarios. The most commonly used test card is:

  • Card number: 4242 4242 4242 4242

  • Expiration date: Any future date

  • CVC: Any 3 digits

Use these test cards to simulate transactions, ensuring that your integration works as expected.

3. Managing Test Transactions in the Stripe Dashboard

In the Stripe Dashboard, you can view all test transactions under the Payments tab. This allows you to confirm successful payments, review failures, and analyze transaction data.


Deploying to Production

1. Switching from Test to Live Environment

When moving your project to production, replace the test API keys with live keys in the .env file:

STRIPE_KEY=your_live_publishable_key
STRIPE_SECRET=your_live_secret_key

This step is crucial to ensure that real payments are processed correctly.

2. Ensuring Secure Transactions

To protect sensitive payment information, make sure your production environment uses HTTPS. This is a critical security measure to encrypt data between the client and server.


Conclusion

In this detailed tutorial, we’ve walked through how to integrate Stripe with Laravel, covering everything from project setup to handling payments securely. By implementing this payment gateway, you provide users with a smooth and reliable payment experience.

10
Subscribe to my newsletter

Read articles from Omodara Similoluwa directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Omodara Similoluwa
Omodara Similoluwa

I’m a dedicated technical writer with a passion for transforming complex technologies into accessible, engaging content. With a solid foundation in software development, I specialize in crafting clear, concise documentation and intuitive tutorials that empower users and developers alike. My mission is to bridge the gap between innovation and understanding, ensuring that anyone can harness the power of technology. Whether I’m penning in-depth guides, creating user-friendly manuals, or developing API documentation, I thrive on making tech approachable and exciting. Let’s simplify the digital world together