Integrating Stripe Payment Gateway in Laravel 8 - deesoft service

Integrating Stripe Payment Gateway in Laravel 8

Deepak Tailor Image
Deepak Tailor - Jul 27 2023
Integrating Stripe Payment Gateway in Laravel 8

Laravel 8, the latest version of the popular PHP framework, provides a robust and elegant solution for integrating payment gateways into web applications. Stripe, a widely-used payment gateway, offers a simple and developer-friendly API for processing online payments securely. In this tutorial, we will guide you through the process of integrating the Stripe payment gateway into a Laravel 8 application step-by-step.

Section 1: Installing Laravel 8

Before we begin with the Stripe integration, ensure you have Laravel 8 installed on your system. If you haven't done this yet, follow these steps:

1. Composer Installation: Install Laravel using Composer by running the following command in your terminal or command prompt:

composer global require laravel/installer

2. Create Laravel Project: Create a new Laravel project using the following command:

Section 2: Installing Stripe Package for Laravel

Next, we need to install the Stripe package for Laravel, which simplifies the integration process. Follow these steps:

1. Install Package: Install the package via Composer by executing the following command in your project directory:

composer require stripe/stripe-php

2. Configuration: The package will automatically configure itself, and you don't need to add a service provider or alias manually. However, ensure you have your API keys ready for the next section.

Section 3: Setting API Key and Secret

To interact with the Stripe API, you need to set your API key and secret key. Follow these steps:

1. Obtain API Keys: Log in to your Stripe account ( or sign up if you don't have an account. After logging in, navigate to the "Developers" section and click on "API Keys."

2. Set Environment Variables: In Laravel, it is recommended to store sensitive information like API keys in the environment file (.env). Open the .env file in the root of your project and add the following lines:

Section 4: Creating Controller, Routes, and Blade Files

With the Stripe package configured and API keys set, we can now create the necessary components to handle payments.

1. Controller: Generate a new controller that will handle payment processing using the following command:,

php artisan make:controller PaymentController

2. Routes: Define the routes in the routes/web.php file to link the endpoints to the controller methods. For example:

use App\Http\Controllers\PaymentController;

Route::get('/payment', [PaymentController::class, 'showForm']);
Route::post('/payment/process', [PaymentController::class, 'processPayment']);
Route::get('/payment/success', [PaymentController::class, 'paymentSuccess']);
Route::get('/payment/cancel', [PaymentController::class, 'paymentCancel']);

3. Blade Files: Create appropriate Blade files to allow users to enter payment details and display payment status. For instance, you might create payment.blade.php, success.blade.php, and cancel.blade.php within the resources/views directory.

Section 5: Testing

Thoroughly testing your payment integration is crucial before deploying it to production. Here are some testing steps you should consider:

1. Test Card Details: Stripe provides test card details (e.g., 4242 4242 4242 4242) for simulating successful payments.

2. Test Invalid Card: Attempt a payment with an invalid card (e.g., 4000 0000 0000 0119) to check error handling.

3. Test Declined Card: Test with a declined card (e.g., 4000 0000 0000 0002) to verify how your application handles failed payments.

Open the resources/views/payment.blade.php file and add the following content:

<!DOCTYPE html>
    <title>Stripe Payment Form</title>
    <h1>Stripe Payment Form</h1>
    <form action="/payment/process" method="post">
        <label for="amount">Amount:</label>
        <input type="text" id="amount" name="amount" required>
        <label for="card">Card Number:</label>
        <input type="text" id="card" name="card" required>
        <label for="exp_month">Expiration Month:</label>
        <input type="text" id="exp_month" name="exp_month" required>
        <label for="exp_year">Expiration Year:</label>
        <input type="text" id="exp_year" name="exp_year" required>
        <label for="cvc">CVC:</label>
        <input type="text" id="cvc" name="cvc" required>
        <button type="submit">Pay Now</button>

In the PaymentController.php located in app/Http/Controllers, add the following methods:

public function processPayment(Request $request)

    $amount = $request->input('amount');
    $cardNumber = $request->input('card');
    $expMonth = $request->input('exp_month');
    $expYear = $request->input('exp_year');
    $cvc = $request->input('cvc');

    try {
        // Create a customer
        $customer = \Stripe\Customer::create([
            'email' => '', // Change to customer's email
            'source' => $cardNumber,

        // Create a charge using the customer
        $charge = \Stripe\Charge::create([
            'amount' => $amount * 100, // Stripe accepts the amount in cents
            'currency' => 'usd', // Change to your preferred currency
            'customer' => $customer->id,
            'description' => 'Payment for Order', // Change to your order description
            'receipt_email' => '', // Change to customer's email

        // Payment success logic (e.g., update database, send email, etc.)

        return redirect('/payment/success');
    } catch (\Stripe\Exception\CardException $e) {
        // Handle card error
        $error = $e->getError()->message;
        return back()->with('error', $error);
    } catch (\Stripe\Exception\RateLimitException $e) {
        // Handle rate limit error
        // Retry the payment at a later time
        return back()->with('error', 'Rate Limit Error: Please try again later.');
    } catch (\Stripe\Exception\InvalidRequestException $e) {
        // Handle invalid request error
        return back()->with('error', 'Invalid Request Error: Something went wrong. Please try again.');
    } catch (\Stripe\Exception\AuthenticationException $e) {
        // Handle authentication error
        return back()->with('error', 'Authentication Error: Please contact support.');
    } catch (\Stripe\Exception\ApiConnectionException $e) {
        // Handle API connection error
        return back()->with('error', 'API Connection Error: Please try again later.');
    } catch (\Stripe\Exception\ApiErrorException $e) {
        // Handle generic API error
        return back()->with('error', 'API Error: Something went wrong. Please try again.');
    } catch (\Exception $e) {
        // Handle other errors
        return back()->with('error', 'Error: Something went wrong. Please try again.');


public function paymentSuccess()
    return view('success');

public function paymentCancel()
    return view('cancel');

1. Create the success.blade.php and cancel.blade.php views in the resources/views directory:


<!DOCTYPE html>
    <title>Payment Successful</title>
    <h1>Payment Successful</h1>
    <p>Thank you for your payment!</p>


<!DOCTYPE html>
    <title>Payment Canceled</title>
    <h1>Payment Canceled</h1>
    <p>Your payment was canceled.</p>

when the payment is successfully processed, the user will be redirected to the payment/success route, which will display the "Payment Successful" message. In case the user cancels the payment, they will be redirected to the payment/cancel route, which will display the "Payment Canceled" message.


Integrating the Stripe payment gateway into your Laravel 8 application is a significant step towards building a functional and secure e-commerce platform. By following this guide, you have learned how to install Laravel 8, set up the Stripe package, configure API keys, create essential components, and perform testing. Remember always to keep your application and dependencies up to date and adhere to best practices to ensure a smooth and seamless payment experience for your users. Happy coding!

Deepak Tailor Image
Deepak Tailor

My name is Deepak tailor as a fullstack developer. I have been in the IT industry (PHP, Nodejs, flutter) for the last 5 years. For professional and customize web development & app development, you can send inquiry on our email.
You can contact him at