I'm always excited to take on new projects and collaborate with innovative minds.

Address

PP Trade Centre, 110 & 111 1st Floor, Netaji Subhash Place

Social Links

Tutorials

💳 How to Set Up Stripe Payment Gateway in Laravel: Step-by-Step Guide

Integrating Stripe with Laravel allows you to securely accept payments in your web application. In this guide, we'll walk you through every step of the process, from installation to implementation.

💳 How to Set Up Stripe Payment Gateway in Laravel: Step-by-Step Guide

🛠️ Step 1: Install a Fresh Laravel Project

If you haven't already, start by setting up a fresh Laravel project:

composer create-project laravel/laravel stripe-app
cd stripe-app

If you already have a Laravel project, you can skip this step.

📦 Step 2: Install Stripe PHP SDK via Composer

Stripe provides an official PHP SDK to interact with their API. Install it by running:

composer require stripe/stripe-php

🔑 Step 3: Create a Stripe Account and Get API Keys

  1. Go to Stripe's website.
  2. Sign up or log in to your account.
  3. Navigate to Developers > API keys on the Stripe dashboard.
  4. Copy the following keys:
    • Publishable Key (for front-end)
    • Secret Key (for back-end)

🔐 Step 4: Add Stripe Keys to .env

Open your .env file and add the following lines:

STRIPE_KEY=your_publishable_key
STRIPE_SECRET=your_secret_key

Replace the your_publishable_key and your_secret_key with your actual keys from Stripe.

🧠 Step 5: Configure config/services.php

Add Stripe configuration to the services.php file:

// config/services.php

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

💳 Step 6: Create a Payment Controller

Create a controller to handle the Stripe payment process:

php artisan make:controller PaymentController

Now, open app/Http/Controllers/PaymentController.php and add the following methods:

<?php

namespace App\Http\Controllers;

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

class PaymentController extends Controller
{
    public function index()
    {
        return view('payment');
    }

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

        // Token is created using Stripe.js or Checkout!
        $token = $request->stripeToken;

        try {
            $charge = Charge::create([
                'amount' => 5000, // Amount in cents (e.g., 5000 = $50.00)
                'currency' => 'usd',
                'description' => 'Payment for Laravel Stripe Integration',
                'source' => $token,
            ]);

            return back()->with('success', 'Payment successful!');
        } catch (\Exception $e) {
            return back()->with('error', 'Error: ' . $e->getMessage());
        }
    }
}

📄 Step 7: Create a Payment View (Frontend)

Create a view file that will contain the form for payment.

Run:

mkdir resources/views
touch resources/views/payment.blade.php

Now, open resources/views/payment.blade.php and add this code to include the Stripe.js library and create the payment form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stripe Payment</title>
    <script src="https://js.stripe.com/v3/"></script>
</head>
<body>

<h2>Pay with Stripe</h2>

@if (session('success'))
    <div style="color: green">{{ session('success') }}</div>
@endif

@if (session('error'))
    <div style="color: red">{{ session('error') }}</div>
@endif

<form action="{{ route('payment.charge') }}" method="POST" id="payment-form">
    @csrf
    <div>
        <label for="card-element">Credit or debit card</label>
        <div id="card-element">
            <!-- A Stripe Element will be inserted here. -->
        </div>

        <!-- Used to display form errors. -->
        <div id="card-errors" role="alert"></div>
    </div>

    <button type="submit" id="submit">Pay Now</button>
</form>

<script>
    var stripe = Stripe('{{ config('services.stripe.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.
                var errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                // Send the token to your server.
                var form = document.getElementById('payment-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>

 

🔗 Step 8: Define Routes

In routes/web.php, define the routes for displaying the payment form and handling the charge:

use App\Http\Controllers\PaymentController;

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

✅ Step 9: Test Your Payment Flow

Now, visit http://your-localhost/payment, and you should see the Stripe payment form.

  1. Enter your payment details (use Stripe's test card numbers like 4242 4242 4242 4242).
  2. Submit the form, and you should receive a success message!
  3.  
4 min read
Apr 16, 2025
By Aditya Kumar
Share

Related posts

Apr 28, 2025 • 4 min read
How To Install Linux, Apache, MySQL, PHP (LAMP) Stack on Ubuntu

A LAMP stack is a set of open-source software that works together to h...

Apr 16, 2025 • 2 min read
📞 How to Set Up Twilio in Laravel: Step-by-Step Guide

Need to send SMS or make voice calls in your Laravel app? Twilio makes...