Stripe Integration with laravel – Boost Your E-commerce Website

In today’s digital age, online transactions have become the norm, especially with the rise of e-commerce websites. Integrating a reliable payment system into your website is crucial to ensure seamless transactions and customer satisfaction. Stripe is a popular payment gateway that offers a range of features and benefits to e-commerce businesses. In this article, we will guide you through the process of integrating Stripe with Laravel, a popular PHP framework, using step-by-step instructions and code examples.

Effortlessly integrate Google Pay with Laravel

Benefit of using stripe with laravel

  1. Easy integration: Stripe offers a well-documented API that makes integration with Laravel easy and straightforward. This means that developers can quickly set up payment processing functionality within their Laravel applications.
  2. Security: Stripe is known for its strong security measures, including encryption and PCI compliance. When used with Laravel, Stripe’s security features can help protect sensitive customer data and prevent fraudulent transactions.
  3. Flexibility: Stripe offers a variety of payment methods, including credit cards, Apple Pay, and Google Pay. This flexibility can be especially useful for Laravel developers who want to offer their customers a range of payment options.
  4. Customization: Stripe allows developers to customize their payment forms and checkout pages to match their brand and provide a seamless user experience. This level of customization can help improve conversion rates and increase customer satisfaction.
  5. Analytics and reporting: Stripe provides detailed analytics and reporting tools that allow developers to track payments, view transaction history, and generate reports. This information can be used to optimize payment processing and improve business operations.

Step 1:

Create a Stripe Account Before we begin integrating Stripe with Laravel, you need to create a Stripe account. You can sign up for a free account on their website by providing basic information about yourself and your business. Once you have created an account, you will be provided with API keys that you will need to use during the integration process.

Step 2:

Install the Package Once you have a account, you need to install the  package in your Laravel project. You can do this by running the following command in your terminal:

composer require stripe/stripe-php

Step 3:

Add API Keys to .env file After installing the package, you need to add your API keys to the .env file in your Laravel project. Open the file and add the following lines of code, replacing the placeholders with your actual API keys:

STRIPE_KEY=pk_test_XXXXXXXXXXXXXXX
STRIPE_SECRET=sk_test_XXXXXXXXXXXXXXX

Step 4: Create a Route

Next, you need to create a route in your Laravel project that will handle the payment process. You can do this by adding the following code to your web.php file:

<?php

Route::post('/pay', function () {
    $stripe = new \Stripe\StripeClient(
        env('STRIPE_SECRET')
    );
    $paymentIntent = $stripe->paymentIntents->create([
        'amount' => 1000,
        'currency' => 'usd',
    ]);
    return view('payment', [
        'client_secret' => $paymentIntent->client_secret
    ]);
});

In this code, we are creating a new payment intent for an amount of $10 (in cents) with the currency set to USD. We are also returning a view called ‘payment’ and passing the client secret for the payment intent to the view.

Step 5: Create the Payment View

Now that we have created the route, we need to create the payment view. Create a new file called payment.blade.php in your resources/views folder and add the following code:

<script src="https://js.stripe.com/v3/"></script>

<form action="/charge" method="post" id="payment-form">
    <div class="form-row">
        <label for="card-element">
            Credit or debit card
        </label>
        <div id="card-element">
            <!-- A Stripe Element will be inserted here. -->
        </div>

        <!-- Used to display form errors. -->
        <div id="card-errors" role="alert"></div>
    </div>

    <button>Submit Payment</button>
</form>

<script>
    var stripe = Stripe('{{ env('STRIPE_KEY') }}');

    var elements = stripe.elements();
    var cardElement = elements.create('card');

    cardElement.mount('#card-element');

javascript

var cardErrors = document.getElementById('card-errors');

cardElement.on('change', function (event) {
    if (event.error) {
        cardErrors.textContent = event.error.message;
    } else {
        cardErrors.textContent = '';
    }
});

var form = document.getElementById('payment-form');

form.addEventListener('submit', function (event) {
    event.preventDefault();

    stripe.createToken(cardElement).then(function (result) {
        if (result.error) {
            // Inform the user if there was an error.
            cardErrors.textContent = result.error.message;
        } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
        }
    });
});

function stripeTokenHandler(token) {
    var form = document.getElementById('payment-form');
    var hiddenInput = document.createElement('input');
    hiddenInput.setAttribute('type', 'hidden');
    hiddenInput.setAttribute('name', 'stripeToken');
    hiddenInput.setAttribute('value', token.id);
    form.appendChild(hiddenInput);

    form.submit();
}

</script>

In this code, we are creating a payment form that will allow the user to enter their credit card details. We are using Elements to create the credit card input field, and we are also displaying any errors that may occur during the payment process. When the user submits the form, we are creating a token using the user’s credit card details and sending it to the server.

Step 6: Create the Charge Route

Now that we have created the payment view, we need to create the route that will handle the token and create a charge. Add the following code to your web.php file:

<?php

Route::post('/charge', function (Request $request) {
    $stripe = new \Stripe\StripeClient(
        env('STRIPE_SECRET')
    );

    $token = $request->input('stripeToken');

    $charge = $stripe->charges->create([
        'amount' => 1000,
        'currency' => 'usd',
        'description' => 'Example Charge',
        'source' => $token,
    ]);

    return 'Payment Successful';
});

In this code, we are creating a new charge for an amount of $10 (in cents) with the currency set to USD. We are also including a description for the charge and using the token from the payment form as the source of the charge. Finally, we are returning a simple message to indicate that the payment was successful.

Conclusion:

Integrating Stripe with Laravel is a relatively straightforward process that can greatly enhance your e-commerce website’s payment system. By following the steps outlined in this guide, you can seamlessly integrate Stripe into your Laravel project and offer your customers a reliable and secure payment gateway. With the help of code examples and clear instructions, you can create a smooth payment process for your customers, which can lead to increased customer satisfaction and repeat business.

You may also like...

Creating a Shopify App using Laravel How to Create Custom WordPress Plugin? How to Build a Telegram Bot using PHP How to Convert Magento 2 into PWA?