How To Integrate Stripe Payment Gateway in Laravel 9

  • 03-09-2022
  • 1291
  • Laravel 9
  • Haresh Chauhan

How To Integrate Stripe Payment Gateway in Laravel 9; using composer require stripe/stripe-php we will install stripe composer in our application. Before that, you must need a signup stripe business account and from there you must need to generate your API key.

composer require stripe/stripe-php using this composer we will install stripe dependency in your laravel application. This package provided a very simply integrate stripe payment gateway in our laravel application. To integrate your application just follow the below-given step and integrate it in your application.

Stripe payment integration laravel; the first customer provided their card details and then clicks on the pay button those card details enter the stripe payment gateway server with encrypted data information and make a transaction then after it will redirect back to which you passed in a callback to the HTTP request.

Preview:

img

Laravel stripe payment integration. By the end of this article you will be able to integrate stripe payment gateway in your laravel 9 app. so let's start integrating.

Step 1. Create Project

Create a laravel 9 project using the below-provided command, open your cmd command line or your system terminal and paste the below-provided command in the terminal, and hit enter. It will take some time to install the project.

composer create-project laravel/laravel stripe

Go to your project directory using "cd" and then give your project name and hit enter in your terminal.

cd stripe

Step 2. Install Stripe Composer

Laravel Tap Payment Gateway Integration Tutorial Example

Next, In this step we will install the stripe dependency library in our application, Below provided command paste in your project terminal, and install stripe composer in your application.

composer require stripe/stripe-php

Copy provided command and also install in your app.

composer require cartalyst/stripe-laravel

Register stripe as a global name space in your application. goto app.php file, this file you will find in the config folder. there will be providers and aliases as per the below given example to add in this both array attribute stripe class name and service provider.

config/app.php
'providers' => [
    .....
    Cartalyst\Stripe\Laravel\StripeServiceProvider::class,
],

'aliases' => [
    ......
    'Stripe' => Cartalyst\Stripe\Laravel\Facades\Stripe::class,
],

Goto your business stripe account and generate api keys from there.

image

Now open your app .env file, and there will be one root. just add this below given two keys at the end of the file.

.env
STRIPE_KEY=pk_test_xxxxxxxxxxxxxxxxxxx
STRIPE_SECRET=sk_test_xxxxxxxxxxxxxx

How to Integrate PayUMoney Payment Gateway in Laravel 9

Step 3. Route Define

Create a stripe controller using the below-provided command in your project terminal.

php artisan make:controller StripePaymentController

Define the route as per the below example given just copy these two routes and paste them into your app web.php file. before that import stripe payment controller at the top file.

routes/web.php
<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\StripePaymentController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('stripe',[StripePaymentController::class,'paymentStripe'])->name('addmoney.paymentstripe');
Route::post('add-money-stripe',[StripePaymentController::class,'postPaymentStripe'])->name('addmoney.stripe');

Step 4. Stripe Controller

Here is our stripe payment controller, in this controller first method, will return to us the stripe payment form, and the second method for the callback method Handel from the stripe payment account.

Import script payment class at the controller as per the below example given and copy both method codes and paste into your controller.

app/Http/Controllers/StripePaymentController.php
<?php<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Validator;

use Stripe;

class StripePaymentController extends Controller
{
    public function paymentStripe()
    {
        return view('stripe');
    }

    public function postPaymentStripe(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'card_no' => 'required',
            'ccExpiryMonth' => 'required',
            'ccExpiryYear' => 'required',
            'cvvNumber' => 'required',
            // 'amount' => 'required',
        ]);

        $input = $request->except('_token');

        if ($validator->passes()) { 
        
            $stripe = Stripe::setApiKey(env('STRIPE_SECRET'));
            
            try {

                
                $token = $stripe->tokens()->create([
                    'card' => [
                        'number' => $request->get('card_no'),
                        'exp_month' => $request->get('ccExpiryMonth'),
                        'exp_year' => $request->get('ccExpiryYear'),
                        'cvc' => $request->get('cvvNumber'),
                    ],
                ]);

        
                if (!isset($token['id'])) {

                    return redirect()->route('stripe.add.money');
                }
                
                $charge = $stripe->charges()->create([
                    'card' => $token['id'],
                    'currency' => 'USD',
                    'amount' => 20.49,
                    'description' => 'wallet',
                ]);
                
                if($charge['status'] == 'succeeded') {
                
                    dd($charge);
                    
                    return redirect()->route('addmoney.paymentstripe');

                } else {

                    return redirect()->route('addmoney.paymentstripe')->with('error','Money not add in wallet!');
                }

            } catch (Exception $e) {

                return redirect()->route('addmoney.paymentstripe')->with('error',$e->getMessage());
                
            } catch(\Cartalyst\Stripe\Exception\CardErrorException $e) {
                
                return redirect()->route('addmoney.paymentstripe')->with('error',$e->getMessage());
                
            } catch(\Cartalyst\Stripe\Exception\MissingParameterException $e) {
                
                return redirect()->route('addmoney.paymentstripe')->with('error',$e->getMessage());
            }
        }
    }
}

Step 5. View Blade File

This is our stripe payment view blade file. We are using bootstrap 5 libraries to make an easy template. You can see there is a Pay button and card details enter form. just enter card details and click on the pay button it will redirect to the stripe payment page and after successful payment, it will redirect back to our callback method.

resources/views/stripe.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>How To Integrate Stripe Payment Gateway in Laravel 9 - Webappfix</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
    <style>
        .submit-button {
            margin-top: 10px;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class='row'>
            <div class='col-md-4'></div>
            <div class='col-md-4'>
                @if (Session::has('error'))
                    <font color="red">{{ Session::get('error') }}</font>
                @endif
                <form class="form-horizontal" method="post" id="payment-form" role="form" action="{!!route('addmoney.stripe')!!}" >
                    @csrf
                    <div class='form-row'>
                        <div class='col-xs-12 form-group card required'>
                            <label class='control-label'>Card Number</label>
                            <input autocomplete='off' class='form-control card-number' size='20' type='text' name="card_no">
                        </div>
                    </div>

                    <div class='form-row'>
                        <div class='col-xs-4 form-group cvc required' style="margin-right: 10px">
                            <label class='control-label'>CVV</label>
                            <input autocomplete='off' class='form-control card-cvc' placeholder='ex. 311' size='4' type='text' name="cvvNumber">
                        </div>

                        <div class='col-xs-4 form-group expiration required' style="margin-right: 10px">
                            <label class='control-label'>Expiration</label>
                            <input class='form-control card-expiry-month' placeholder='MM' size='4' type='text' name="ccExpiryMonth">
                        </div>

                        <div class='col-xs-4 form-group expiration required' style="margin-right: 10px">
                            <label class='control-label'>Year</label>
                            <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='text' name="ccExpiryYear">
                            <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='hidden' name="amount" value="300">
                        </div>
                    </div>

                    <div class='form-row'>
                        <div class='col-md-12' style="margin-left:-15px;">
                            <div class='form-control total btn btn-primary' >Total:
                                <span class='amount'>$300</span>
                            </div>
                        </div>
                    </div>
                    
                    <div class='form-row'>
                        <div class='col-md-12 form-group'>
                            <button class='form-control btn btn-success submit-button' type='submit'>Pay »</button>
                        </div>
                    </div>
                    
                    <div class='form-row'>
                        <div class='col-md-12 error form-group hide'>
                            <div class='alert-danger alert'>
                                Please correct the errors and try again.
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div class='col-md-4'></div>
        </div>
    </div>
</body>
</html>

How to Integrate Razorpay Payment Gateway in Laravel 9 Example


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :