Welcome to CodeCrew Infotech

shape shape
Shape Shape Shape Shape
Blog

Step-by-Step Guide to Integrate Stripe Payment Gateway in Laravel 11

Integrating Stripe with Laravel 11 is a streamlined process that enables you to accept secure payments in your web application.

Prerequisites:

1. Create a project:-

Now, open a terminal and run this command:

composer create-project stripe-laravel

After Setup Project:

cd stripe-laravel

2. Install Stripe Package:-

Use Composer to install the official Stripe PHP library:

Now, open terminal

composer require stripe/stripe-php

3. Configuration:-

.env File: Add your Stripe API keys to your .env file:

STRIPE_KEY=your_publishable_key
STRIPE_SECRET=your_secret_key

Update your config/services.php file to include the Stripe configuration:

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

4. Create StripeController:-

Create a controller StripeController to handle payment requests:

Here The Command:

php artisan make:controller StripeController
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Stripe;

class StripeController extends Controller
{
    private $stripeSecretKey;

    public function __construct()
    {
        $this->stripeSecretKey = config('stripe.secret');
    }

    /**
     * Renders the payment view.
     *
     * This method is responsible for returning the view that displays the payment form to the user.
     *
     * @return \Illuminate\View\View
     */
    public function index()
    {
        return view('payment');
    }
    /**
     * Handle a payment request from the client.
     *
     * This method is responsible for processing a payment using the Stripe API. It takes the payment token from the client,
     * charges the customer, and redirects to the payment success page if the transaction is successful. If an error occurs
     * during the payment processing, it logs the error and returns an error message to the client.
     *
     * @param \Illuminate\Http\Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function handlePayment(Request $request)
    {
        try {
            Stripe\Stripe::setApiKey($this->stripeSecretKey);
            Stripe\Charge::create([
                'amount' => 10 * 100,
                'currency' => 'usd',
                'source' => $request->stripeToken,
                'description' => 'Your product or service description',
            ]);

            return redirect()->route('payment.success');
        } catch (\Exception $e) {
            \Log::error('Payment processing error: ' . $e->getMessage());
            return back()->withErrors(['error' => 'An error occurred during payment processing. Please try again.']);
        }
    }
}

5. Payment Form:-

create `resources/views/payment.blade.php

<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet"
        integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"
        integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
    </script>
</head>

<body>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-4 mt-4">
                <div class="card mt-4">
                    <div class="card-body">
                        @if (session('success'))
                            <div class="text-success">
                                Payment Successful!
                            </div>
                        @endif
                        <form id='checkout-form' method='post' action="{{ route('stripe.charge') }}">
                            @csrf
                            <input type='hidden' name='stripeToken' id='stripe-token-id'>
                            <label for="card-element" class="mb-5">Payment</label>
                            <br>
                            <div id="card-element" class="form-control"></div>
                            <button id='pay-btn' class="btn btn-primary mt-3 p-7" type="button" style="width: 100%;"
                                onclick="createToken()">PAY
                                $5</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://js.stripe.com/v3/"></script>
    <script>
        var stripe = Stripe('{{ env('STRIPE_KEY') }}');
        var elements = stripe.elements();
        var cardElement = elements.create('card');
        cardElement.mount('#card-element');

        function createToken() {
            document.getElementById("pay-btn").disabled = true;
            stripe.createToken(cardElement).then(function(result) {
                if (typeof result.error !== 'undefined') {
                    document.getElementById("pay-btn").disabled = false;
                    alert(result.error.message);
                }
                if (typeof result.token !== 'undefined') {
                    document.getElementById("stripe-token-id").value = result.token.id;
                    document.getElementById('checkout-form').submit();
                }
            });
        }
    </script>
</body>

</html>


Create 'resources/views/success.blade.php'.

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payment Successful</title>
</head>

<body>
    <h1>Payment Successful!</h1>

    <p>Thank you for your purchase. Your payment has been processed successfully.</p>

    <a href="{{ url('/') }}">Back to Home</a>
</body>

</html>

6. Add Routes:-

To begin, open your 'routes/web.php' file and make the necessary modifications to the existing code.

<?php

use App\Http\Controllers\StripeController;
use Illuminate\Support\Facades\Route; Route::get('stripe', [StripeController::class, 'index']); Route::post('/stripe/charge', [StripeController::class, 'handlePayment'])->name('stripe.charge'); Route::get('/payment/success', function () { return view('payment.success'); })->name('payment.success');

 

7. Run the Laravel Project:-

run the following command:

php artisan serve

Now, open your web browser and navigate to the provided URL to view the application output.

localhost:8000/stripe

Conclusion:-

In conclusion, integrating Stripe with Laravel 11 facilitates secure and efficient payment processing, enhancing user experience and application functionality while ensuring data security.

Thank you...