How to Integrate Stripe Payment Gateway In Laravel 10

Spread the love

Hello Guys,

In this extensive guide, we will explore the process of smoothly integrating the Stripe Payment Gateway into Laravel 10. We’ll provide a practical example to demonstrate how to seamlessly incorporate the Stripe Payment Gateway within your Laravel 10 project. Follow this detailed, step-by-step tutorial to ensure a smooth connection between Stripe and Laravel, enhancing your payment processing capabilities for efficiency and convenience.

Example of Integrate Stripe Payment Gateway with laravel 10

Step 1: Install stripe-php package

composer require stripe/stripe-php

Step 2: Create a stripe.php

  1. Generate a dedicated stripe.php file within your configuration directory.
  2. Place the following code within the newly created stripe.php file.
<?php

return [
    'api_keys' => [
        'secret_key' => env('STRIPE_SECRET_KEY', null)
    ]
];

Step 3: Open .env file

To enhance your website’s security, make sure to set the Stripe secret key as an environment variable within your .env file

STRIPE_SECRET_KEY=       // your secret key

Stripe API Keys – https://dashboard.stripe.com/account/apikeys

Note:- On the Stripe dashboard, select Test Mode to access sandbox keys.
image How to Integrate Stripe Payment Gateway In Laravel 10

Step 4: Setup Stripe API

There are multiple methods within the Stripe API that streamline the integration process, making it more accessible. The Stripe payment process can be broken down into two key steps.

Tokenization – During this stage, Stripe securely collects sensitive data from a bank account or credit card and generates a token in return. This tokenization process ensures the security and privacy of your users’ financial information.

$stripe = new \Stripe\StripeClient(
    config('stripe.api_keys.secret_key')
);
$stripe->tokens->create([
    'card' => [
        'number' => '4242424242424242',
        'exp_month' => 12,
        'exp_year' => 2023,
        'cvc' => '123',
    ],
]);

Ref:- Stripe API Reference – Create a card token

Payment Process: Stripe utilizes the generated token from the tokenization process to initiate the transaction and charge the specified amount at this stage.

Also Read: How to use One to One Relationship in LARAVEL 10

$stripe = new \Stripe\StripeClient(
    config('stripe.api_keys.secret_key')
);
$stripe->charges->create([
    'amount' => 1000,
    'currency' => 'usd',
    'source' => 'tok_mastercard',
    'description' => 'My First Test Charge with itcodestuff.com',
]);

Please ensure to transmit funds in the smallest currency denomination feasible. For instance, 1000 units denote 10 US dollars in this example. There is no need for a description.

Within the metadata field, you can also include extra information as a key-value pair.

Ref:-Stripe API Reference – Create a charge

Step 5: Create a payment.blade.php

Place this code in a file called payment.blade.php in the resources/views directory.

<main>
    <div class="row">
        <aside class="col-sm-6 offset-3">
            <article class="card">
                <div class="card-body p-5">
                    <ul class="nav bg-light nav-pills rounded nav-fill mb-3" role="tablist">
                        <li class="nav-item">
                            <a class="nav-link active" data-toggle="pill" href="#nav-tab-card">
                            <i class="fa fa-credit-card"></i> Credit Card</a>
                        </li>
                    </ul>
                    <div class="tab-content">
                        <div class="tab-pane fade show active" id="nav-tab-card">
                            @foreach (['danger', 'success'] as $status)
                                @if(Session::has($status))
                                    <p class="alert alert-{{$status}}">{{ Session::get($status) }}</p>
                                @endif
                            @endforeach
                            <form role="form" method="POST" id="paymentForm" action="{{ url('/payment')}}">
                                @csrf
                                <div class="form-group">
                                    <label for="username">Full name (on the card)</label>
                                    <input type="text" class="form-control" name="fullName" placeholder="Full Name">
                                </div>
                                <div class="form-group">
                                    <label for="cardNumber">Card number</label>
                                    <div class="input-group">
                                        <input type="text" class="form-control" name="cardNumber" placeholder="Card Number">
                                        <div class="input-group-append">
                                            <span class="input-group-text text-muted">
                                            <i class="fab fa-cc-visa fa-lg pr-1"></i>
                                            <i class="fab fa-cc-amex fa-lg pr-1"></i>
                                            <i class="fab fa-cc-mastercard fa-lg"></i>
                                            </span>
                                        </div>
                                    </div>
                                </div>
                                <div class="row">
                                    <div class="col-sm-8">
                                        <div class="form-group">
                                            <label><span class="hidden-xs">Expiration</span> </label>
                                            <div class="input-group">
                                                <select class="form-control" name="month">
                                                    <option value="">MM</option>
                                                    @foreach(range(1, 12) as $month)
                                                        <option value="{{$month}}">{{$month}}</option>
                                                    @endforeach
                                                </select>
                                                <select class="form-control" name="year">
                                                    <option value="">YYYY</option>
                                                    @foreach(range(date('Y'), date('Y') + 10) as $year)
                                                        <option value="{{$year}}">{{$year}}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-sm-4">
                                        <div class="form-group">
                                            <label data-toggle="tooltip" title=""
                                                data-original-title="3 digits code on back side of the card">CVV <i
                                                class="fa fa-question-circle"></i></label>
                                            <input type="number" class="form-control" placeholder="CVV" name="cvv">
                                        </div>
                                    </div>
                                </div>
                                <button class="subscribe btn btn-primary btn-block" type="submit"> Confirm </button>
                            </form>
                        </div>
                    </div>
                </div>
            </article>
        </aside>
    </div>
</main>

Step 6: Create a PaymentController

php artisan make:controller PaymentController

Add this code to PaymentController.php by opening it.

Also Read: how to integrate chatgpt API in laravel 10

<?php

namespace App\Http\Controllers;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Stripe\Exception\CardException;
use Stripe\StripeClient;

class PaymentController extends Controller
{
    private $stripe;
    public function __construct()
    {
        $this->stripe = new StripeClient(config('stripe.api_keys.secret_key'));
    }

    public function index()
    {
        return view('payment');
    }

    public function payment(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'fullName' => 'required',
            'cardNumber' => 'required',
            'month' => 'required',
            'year' => 'required',
            'cvv' => 'required'
        ]);

        if ($validator->fails()) {
            $request->session()->flash('danger', $validator->errors()->first());
            return response()->redirectTo('/');
        }

        $token = $this->createToken($request);
        if (!empty($token['error'])) {
            $request->session()->flash('danger', $token['error']);
            return response()->redirectTo('/');
        }
        if (empty($token['id'])) {
            $request->session()->flash('danger', 'Payment failed.');
            return response()->redirectTo('/');
        }

        $charge = $this->createCharge($token['id'], 1000);
        if (!empty($charge) && $charge['status'] == 'succeeded') {
            $request->session()->flash('success', 'Payment completed.');
        } else {
            $request->session()->flash('danger', 'Payment failed.');
        }
        return response()->redirectTo('/');
    }

    private function createToken($cardData)
    {
        $token = null;
        try {
            $token = $this->stripe->tokens->create([
                'card' => [
                    'number' => $cardData['cardNumber'],
                    'exp_month' => $cardData['month'],
                    'exp_year' => $cardData['year'],
                    'cvc' => $cardData['cvv']
                ]
            ]);
        } catch (CardException $e) {
            $token['error'] = $e->getError()->message;
        } catch (Exception $e) {
            $token['error'] = $e->getMessage();
        }
        return $token;
    }

    private function createCharge($tokenId, $amount)
    {
        $charge = null;
        try {
            $charge = $this->stripe->charges->create([
                'amount' => $amount,
                'currency' => 'usd',
                'source' => $tokenId,
                'description' => 'My first payment with itcodestuff.com'
            ]);
        } catch (Exception $e) {
            $charge['error'] = $e->getMessage();
        }
        return $charge;
    }
}

Note: You can use $charge['id'] to record a transaction id and then use that id to later retrieve charge data.

Ref:- Stripe API Reference – Retrieve a charge

Step 7: Open web.php

Add this code to web.php by opening it.

<?php

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

/*
|--------------------------------------------------------------------------
| 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('/',         [PaymentController::class, 'index']);
Route::post('/payment', [PaymentController::class, 'payment']);

Run your app:

Also Read: How to add Custom Validation Error Message in LARAVEL 10

php artisan serve
http://127.0.0.1:8000
For Testing:-

Card Number: 4242424242424242

Month/Year: Any future date

CVV: Any 3 digits

Ref:- Testing Cards | Stripe

We trust you’ll discover our Laravel Blogs to be a valuable resource.

Leave a Comment