Implementing Payment Gateway in Laravel Using Stripe

Published on : March 26,2023
Implementing Payment Gateway in Laravel Using Stripe

Introduction

Online payment is an essential aspect of e-commerce web development. It allows customers to make payments securely and easily, and it's crucial for the success of any online business. In this article, we'll take a closer look at how to implement a payment gateway in Laravel using Stripe, one of the most popular payment gateways available.

 

Section 1: Setting Up Stripe Account

The first step is to create a Stripe account and obtain your API keys. Stripe provides two types of API keys - publishable and secret. The publishable key is used in the client-side code, while the secret key is used in server-side code. We'll walk through the process of obtaining these keys.

 

1.1 Creating a Stripe Account

To create a Stripe account, go to the Stripe website and sign up. You'll be asked for some basic information, including your email address and a password. Once you've completed the signup process, you'll be taken to your Stripe dashboard.

 

1.2 Obtaining the API Keys

To obtain your Stripe API keys, go to your Stripe dashboard and click on the "Developers" tab. Here, you'll find your publishable and secret keys. Make sure to copy these keys and keep them safe, as we'll need them in the next step.

 

Section 2: Installing Stripe Package

Once we have our API keys, we need to install the Laravel Stripe package using Composer. This package provides a simple and intuitive interface for working with Stripe in Laravel.

 

2.1 Installing Laravel Stripe Package

To install the Laravel Stripe package, run the following command in your terminal:

composer require cartalyst/stripe-laravel

 

2.2 Configuring the Package

Next, we need to configure the Laravel Stripe package. Open the config/services.php file and add the following configuration:

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

Make sure to replace App\Models\User with the model you're using for authentication in your application. We'll also need to add our Stripe API keys to the .env file:

STRIPE_KEY=your_publishable_key
STRIPE_SECRET=your_secret_key

 

Section 3: Creating the Payment Form

Now that we've installed and configured the Laravel Stripe package, we can create the payment form. For this example, we'll create a simple checkout form that allows users to enter their payment details.

 

3.1 Creating the Checkout Form

Create a new view file named checkout.blade.php and add the following code:

<form action="{{ route('checkout') }}" method="POST" id="payment-form">
    @csrf
    <div class="form-group">
        <label for="cardholder-name">Cardholder Name</label>
        <input type="text" name="cardholder_name" id="cardholder-name" class="form-control">
    </div>
    <div class="form-group">
        <label for="card-element">Credit or debit card</label>
        <div id="card-element"></div>
        <div id="card-errors" role="alert"></div>
    </div>
    <button type="submit" class="btn btn-primary">Pay Now</button>
</form>

This form includes a text field for the cardholder's name and a Stripe element for the credit or debit card.

 

3.2 Adding Stripe Elements

We'll need to include Stripe.js and Stripe Elements in our view file. Add the following code in the <head> section of the checkout.blade.php file:

<script src="https://js.stripe.com/v3/"></script>
<script>
    var stripe = Stripe('{{ config('services.stripe.key') }}');
    var elements = stripe.elements();
    
    var cardElement = elements.create('card');
    cardElement.mount('#card-element');
    
    cardElement.addEventListener('change', function(event) {
        var displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
    });
</script>

This code initializes Stripe.js with our publishable key and creates a Stripe element for the credit or debit card. It also adds an event listener to the card element that displays any errors that occur during payment.

 

Section 4: Processing the Payment

With our form and Stripe Elements in place, we can now process the payment. We'll create a new controller method that handles the payment and redirects the user to a confirmation page.

 

4.1 Creating the Checkout Controller

Create a new controller named CheckoutController by running the following command in your terminal:

php artisan make:controller CheckoutController

In the CheckoutController, add the following code to process the payment:

use Cartalyst\Stripe\Laravel\Facades\Stripe;

public function checkout(Request $request)
{
    $user = auth()->user();
    $token = $request->input('stripeToken');
    $amount = 100; // Replace with your desired amount
    
    try {
        $charge = Stripe::charges()->create([
            'amount' => $amount,
            'currency' => 'USD',
            'source' => $token,
            'description' => 'Test Payment',
            'receipt_email' => $user->email,
        ]);
        
        return redirect()->route('confirmation')->with('success', 'Payment successful.');
    } catch (\Exception $e) {
        return back()->with('error', $e->getMessage());
    }
}

This code uses the Stripe facade provided by the Laravel Stripe package to create a charge using the Stripe API. It also redirects the user to a confirmation page if the payment is successful, or back to the checkout page with an error message if the payment fails.

 

4.2 Updating the Routes

Finally, we need to update our routes to handle the payment and confirmation pages. Add the following code to your web.php file:

Route::get('/checkout', function () {
    return view('checkout');
})->name('checkout');

Route::post('/checkout', [App\Http\Controllers\CheckoutController::class, 'checkout'])->name('checkout');

Route::get('/confirmation', function () {
    return view('confirmation');
})->name('confirmation');

 

Conclusion:

In this article, we learned how to implement a payment gateway in Laravel using Stripe. We started by setting up a Stripe account and obtaining our API keys, then installed the Laravel Stripe package and configured it. We then created a payment form with Stripe Elements and processed the payment using the Stripe API. By following these steps, we can easily accept payments in our Laravel application and provide a seamless checkout experience for our customers.

Categories : Laravel

Tags : Laravel Laravel 8 Stripe Payment Gateway

Abhay Dudhatra
Abhay Dudhatra
I am a full-stack developer who is passionate about creating innovative solutions that solve real-world problems. With expertise in technologies such as PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap, I love to share my knowledge and help others in the industry through writing tutorials and providing tips. Consistency and hard work are my mantras, and I constantly strive to improve my skills and stay up-to-date with the latest advancements in the field. As the owner of Open Code Solution, I am committed to providing high-quality services to my clients and helping them achieve their business objectives.


29 Comments

fenofibrate 200mg pill fenofibrate 160mg oral order tricor 200mg online cheap


tadalafil 10mg brand viagra 100mg for sale buy viagra 100mg


zaditor pills ziprasidone 40mg generic order tofranil online


minoxidil tablet buy tadalafil 40mg sale non prescription erection pills


precose 50mg canada buy repaglinide pills cost fulvicin 250 mg


order aspirin 75mg online zovirax us imiquad without prescription


order dipyridamole 100mg without prescription purchase pravastatin generic buy pravachol 20mg without prescription


order generic dydrogesterone 10mg order jardiance without prescription jardiance 10mg for sale


order florinef generic aciphex 10mg tablet buy imodium 2mg sale


monograph for sale online colospa over the counter order cilostazol pills


order prasugrel cheap chlorpromazine 100mg buy tolterodine 2mg generic


buy generic ferrous 100 mg order ascorbic acid for sale betapace ca


purchase mestinon for sale feldene sale maxalt canada


buy vasotec 10mg buy vasotec online buy generic duphalac online


latanoprost order order xeloda for sale order exelon online cheap


betahistine 16 mg canada probenecid tablet probenecid 500mg canada


premarin online dostinex 0.5mg oral viagra 100mg cheap


buy omeprazole without prescription order omeprazole 20mg lopressor 100mg price


buy micardis 80mg buy micardis 80mg generic order molnunat 200mg sale


tadalafil 10mg canada tadalafil 5mg us order sildenafil 50mg pills


cenforce 50mg drug buy cenforce 100mg generic buy aralen tablets


buy cheap modafinil prednisone 10mg tablet order prednisone 10mg for sale


cefdinir 300 mg without prescription cefdinir 300 mg pills buy prevacid 15mg pills


buy accutane 20mg pill buy azithromycin 500mg pill buy azithromycin 500mg online


buy azithromycin 500mg sale prednisolone 10mg without prescription buy neurontin no prescription


order lipitor order norvasc generic buy norvasc 5mg sale


real casino slots real money spins buy lasix 100mg pill


buy pantoprazole 20mg pill pyridium usa buy generic phenazopyridine over the counter


online slots for real money play casino purchase albuterol generic


Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles