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.


165 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


That is additionally a very good article that I absolutely loved reading. It is not every day that I am getting to look at something like this. oogie boogie hoodie Desire you may have many extra top articles to share with us.


symmetrel 100mg cheap oral amantadine 100mg avlosulfon for sale online


online casino no deposit bonus sports gambling levoxyl generic


order clomiphene 50mg without prescription buy imdur 40mg generic imuran 50mg ca


methylprednisolone 8mg tablets medrol 4 mg online triamcinolone 10mg usa


buy levitra 10mg pill buy generic zanaflex online buy zanaflex pill


order coversum buy generic clarinex 5mg oral fexofenadine 180mg


order dilantin 100mg online brand dilantin where can i buy oxytrol


where can i buy ozobax toradol order online buy toradol


claritin 10mg tablet loratadine cheap brand priligy 90mg


baclofen 10mg uk toradol uk generic toradol


alendronate medication buy alendronate sale buy macrodantin online


purchase inderal without prescription motrin 400mg over the counter buy generic plavix for sale


buy glimepiride 1mg online oral glimepiride order etoricoxib 60mg sale


buy generic warfarin metoclopramide 10mg oral order metoclopramide online


buy generic orlistat order mesalamine generic oral diltiazem 180mg


famotidine 20mg tablet purchase prograf for sale buy tacrolimus 5mg online


how to get azelastine without a prescription avapro pills avalide pills


esomeprazole 40mg sale order remeron online cheap purchase topamax


buy generic imitrex 25mg dutasteride tablet avodart pills


buy cheap allopurinol clobetasol brand crestor cheap


ranitidine 300mg cheap mobic 15mg cheap celecoxib cheap


buy flomax 0.2mg pills zofran canada brand zocor


motilium 10mg generic buy generic sumycin over the counter tetracycline 500mg us


buy spironolactone 100mg pills valacyclovir 1000mg us buy finasteride 1mg online


help writing a paper for college academicwriters best essay writing websites


forcan us buy fluconazole 100mg order cipro 500mg for sale


sildenafil tablet buy aurogra paypal brand yasmin


metronidazole medication cephalexin 125mg sale order keflex 125mg pill


lamotrigine 50mg price buy mebendazole generic order vermox 100mg for sale


order cleocin without prescription buy ed pills best otc ed pills


tretinoin where to buy buy stendra pills avanafil 200mg tablet


buy tamoxifen without a prescription purchase nolvadex sale cost budesonide


tadacip over the counter buy generic indocin 50mg purchase indocin pill


buy generic cefuroxime 250mg methocarbamol 500mg without prescription buy robaxin online


desyrel 100mg for sale clindamycin generic clindamycin online buy


purchase lamisil online order terbinafine generic slot online


order aspirin generic online gambling with real payouts real casino online


academic writers online argument essay writing suprax 200mg sale


my childhood essay writing list online gambling real money best online casino games


buy amoxicillin 500mg online buy trimox 500mg pills how to buy macrobid


rocaltrol 0.25mg tablet buy labetalol pills tricor 200mg over the counter


buy catapres tablets buy tiotropium bromide 9mcg generic where can i buy spiriva


acne treatments for teen girls best acne treatment teen boys oxcarbazepine for sale online


minomycin order online generic requip 1mg requip 1mg drug


uroxatral 10mg oral buy alfuzosin generic vomiting medicine name list


basic care sleep aid hair loss treatment without minoxidil buy prescription weight loss medication online


letrozole 2.5mg ca aripiprazole 20mg without prescription buy abilify online


helpful medication to quit smoking purchase prescription medication online pain medications online pharmacies


order provera generic order medroxyprogesterone 5mg for sale how to buy microzide


types of antiviral drug are there alternatives to jardiance diabetes symptoms type 2 test


periactin online buy buy luvox without prescription purchase ketoconazole generic


oral antifungal for skin infection herpes simplex 1 antiviral medication does drinking water help lower blood pressure


buy cymbalta 20mg pill modafinil 100mg canada brand provigil


classification of peptic ulcer drugs order antibiotics for uti online get antibiotic for uti online


phenergan over the counter stromectol 12mg us buy ivermectin canada


online birth control refill medication for treating premature ejaculation vitamins that help with libido


buy prednisone tablets order deltasone 10mg buy cheap generic amoxicillin


how to cure indigestion quickly supplements that help with gerd de gas 48 priceline


buy zithromax generic neurontin 100mg us neurontin 800mg without prescription


ursodiol order online oral zyrtec zyrtec canada


order strattera 25mg without prescription where to buy seroquel without a prescription zoloft 50mg canada


lasix cheap get antihistamine pills online albuterol tablet


order escitalopram 20mg sale naltrexone 50mg for sale revia 50 mg generic


cost augmentin 625mg cost augmentin 375mg buy clomiphene medication


combivent ca buy dexamethasone online linezolid for sale


starlix 120mg cheap capoten 25 mg tablet buy atacand online


vardenafil order buy zanaflex without prescription hydroxychloroquine 200mg cost


buy carbamazepine without prescription buy generic ciplox for sale buy lincocin no prescription


purchase cenforce generic chloroquine 250mg pill order metformin 1000mg without prescription


purchase duricef pill order cefadroxil for sale epivir canada


buy lipitor 10mg pill buy norvasc no prescription buy generic zestril 5mg


order omeprazole 10mg generic order tenormin generic brand tenormin 50mg


buy cabergoline how to buy dostinex order dapoxetine 30mg for sale


can i buy depo-medrol online buy cheap medrol order clarinex 5mg


buy misoprostol cheap buy diltiazem sale how to get diltiazem without a prescription


purchase nootropil online cheap buy generic betnovate anafranil pills


order zovirax order zovirax generic order rosuvastatin 10mg online


itraconazole 100mg usa buy generic prometrium tinidazole 500mg cheap


buy ezetimibe generic motilium 10mg buy sumycin online cheap


zyprexa 10mg for sale bystolic 20mg oral diovan online


cyclobenzaprine uk how to get toradol without a prescription order toradol 10mg generic


buy colchicine for sale buy plavix sale brand methotrexate 10mg


acne ointment by prescription only buy cleocin best acne treatment for adults


allergy medications prescription list phenergan buy online kirkland allergy pills toronto


which anti anxiety drugs increase heartburn buy altace 5mg online



prednisone 40mg pill deltasone 20mg cost


best painkiller for sensitive stomach buy clozapine 50mg online cheap


acne ointment by prescription only betnovate 20 gm uk best dermatologist acne medication


allergy medication primary name order asthma pills costco canada cold and sinus


medicine used for tummy ache lincomycin 500mg brand


order isotretinoin 20mg online buy generic isotretinoin accutane cheap


Заказал потрясающий букет на "Цветов.ру" для свидания с девушкой. Цветы сразу создали атмосферу волшебства, а ее улыбка стала самым ценным моментом вечера. Рекомендую "Цветов.ру" для создания моментов, которые запомнятся на всю жизнь. Советую! Вот ссылка [url=https://fm-upgrade.ru/grozny/]магазин цветов[/url]


Друзья нуждались в поддержке, и я решил подарить им цветы. "Цветов.ру" сделал этот процесс простым, а красочный букет точно придал им немного света в серых буднях. Советую! Вот ссылка [url=https://groznyj-sweet-smoke.ru/nnov/]купить букет[/url]


strongest non prescription sleeping pills buy generic provigil over the counter


amoxicillin 1000mg oral amoxicillin where to buy amoxicillin without prescription


azithromycin 250mg pill azithromycin 500mg pill buy zithromax 500mg pill


order neurontin 100mg without prescription gabapentin 800mg sale


order azithromycin 500mg without prescription generic azipro 250mg buy generic azithromycin for sale


buy lasix online buy lasix for sale diuretic


order prednisolone 40mg generic omnacortil for sale online prednisolone oral


prednisone over the counter cheap prednisone 10mg


cheap amoxil 500mg order amoxicillin 1000mg generic buy generic amoxil over the counter



cost albuterol ventolin pills buy ventolin 4mg online


buy augmentin 375mg pills buy clavulanate tablets


buy levothroid without prescription buy synthroid for sale synthroid 75mcg generic


levitra 20mg brand cost vardenafil 10mg


buy clomid 100mg generic clomiphene oral buy clomid paypal


zanaflex cost order generic tizanidine 2mg tizanidine for sale


Я всегда считал, что здоровое питание - это сложно и дорого. Но с [url=https://blender-bs5.ru/collection/sokovyzhimalki-dlya-granata]ручной соковыжималкой для граната[/url] от "Все соки" я обнаружил, что это весело, просто и вкусно! Теперь свежевыжатый гранатовый сок - мой любимый завтрак.


rybelsus 14mg for sale semaglutide for sale purchase semaglutide online cheap


Начав правильно питаться, я искал хороший пресс для масла. 'Все соки' предложили отличный вариант. Теперь я могу делать свежее масло прямо у себя дома, что гарантирует его качество. [url=https://h-100.ru/collection/maslopressy]Пресс для масла[/url] помог мне вести здоровый образ жизни.


buy deltasone 10mg pills buy deltasone generic buy deltasone 10mg


rybelsus online order order semaglutide 14 mg sale purchase rybelsus sale


buy accutane cheap absorica online buy buy isotretinoin


buy generic amoxil 1000mg amoxil 1000mg generic order amoxicillin 1000mg for sale


where to buy albuterol without a prescription order albuterol generic purchase ventolin without prescription


zithromax 250mg price order zithromax 250mg generic order generic azithromycin 250mg


generic augmentin 375mg amoxiclav sale generic augmentin


buy generic omnacortil for sale omnacortil 5mg pills omnacortil sale


levoxyl pill levothyroxine buy online oral levothroid


buy semaglutide 14mg for sale brand rybelsus 14 mg order rybelsus 14mg generic


online black jack online casino real money paypal online poker free


vardenafil 10mg pills buy vardenafil 20mg buy cheap vardenafil


lyrica online buy buy pregabalin 150mg lyrica 75mg price


buy hydroxychloroquine online cheap oral hydroxychloroquine 200mg generic hydroxychloroquine


order triamcinolone generic order aristocort 10mg generic buy triamcinolone 4mg online


tadalafil us cialis dosage 40 mg tadalafil 40mg uk


desloratadine 5mg sale order desloratadine 5mg clarinex brand


brand cenforce 50mg buy generic cenforce buy cenforce sale


where to buy loratadine without a prescription buy loratadine 10mg pill how to buy claritin


buy aralen pills buy generic chloroquine 250mg aralen 250mg usa


xenical 60mg usa xenical ca buy diltiazem paypal


glycomet 1000mg without prescription purchase glycomet metformin 1000mg us


Leave a comment

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

Related Articles