Saturday, May 4, 2024
HomePHPLaravel Stripe integration tutorial - Phppot

Laravel Stripe integration tutorial – Phppot


by Vincy. Final modified on February twenty fourth, 2024.

This tutorial guides to combine Stripe right into a PHP Laravel software. It makes use of the essential PHP SDK supplied by Stripe to entry its API.

We’ve already seen an instance of Stripe integration with easy PHP.

Following are the steps to allow Stripe fee gateway in a Laravel app.

  1. Set up Stripe PHP SDK through composer.
  2. Login to the Stripe dashboard and get the API keys.
  3. Configure the keys into the Laravel Stripe app.
  4. Create the app config to return the stripe keys and the product particulars.
  5. Design Laravel templates for “fee” and “thanks” pages.
  6. Provoke the Stripe Checkout from the Laravel app controller.

This instance will assist to combine fee options into your easy PHP buying cart or any eCommerce net software.

stripe payment hosted checkout page

1. Set up Stripe PHP through composer

Run this composer command to put in the stripe-php library into the Laravel App. This library is an middleman to get use of the Stripe fee API companies from the Laravel software.

composer require stripe/stripe-php

2. Login to the Stripe dashboard and get the API keys

It requires Stripe keys to be configured into the PHP Laravel .env file. Login to the Stripe dashboard and navigate to the “Builders” menu to get the API keys.

stripe api keys in dashboard

 

3. Configure the keys into the Laravel Stripe app

Then, configure the Stripe publishable key and secret_key within the Laravel .env file. We’ve seen this in a primary Laravel software created for rookies to implement a product CRUD system.

.env

STRIPE_SECRET_KEY = sk_test_51OIqw1JRNtX7K3SsxQvUoxqtkKZ6GGnhuThMWnbkVs8uYJHO5troMUZVqYVJEVW54tJGTYdtBHaXAh48rAathGno00QqnvZfK6
STRIPE_PUBLISHABLE_KEY = pk_test_51OIqw1JRNtX7K3Ss3PLgYcrIjglMSBBzIBb1vQU6FtNJZN5KPCkLNfxFNOyEGQBVkMcPImdlaRv9zN9bTKioXvnl00AuNE53Zf

These surroundings variables are used within the Stripe config created for this instance.

4. Create the app config to return the stripe keys and the product particulars

The beneath PHP file is created within the Laravel app config listing that returns an array of fee supplier keys and product on the market.

config/stripe.php

<?php

return [
    'stripe_publishable_key' => env('STRIPE_PUBLISHABLE_KEY'),
    'stripe_secret_key' => env('STRIPE_SECRET_KEY'),

    'product' =>[
        'name' => 'Classic Quartz Watch',
        'description' => 'Water resistant, Stop watch, Alarm features.',
        'price' => 1000, 
    ]
];
?>

stripe logo

5. Design Laravel templates for “fee” and “thanks” pages

This instance has two template recordsdata. One is for viewing a product web page with a “Purchase now” button. The opposite template is the HTML view for the Laravel Stripe fee’s “success” web page.

laravel stripe payment page

The beneath template file, stripe.blade.php exhibits the product photograph, title, and outline for the front-end customers. It additionally incorporates a “Purchase now” button that triggers sending the fee request to Stripe.

The “Purchase now” hyperlink refers back to the stripe.checkout route outlined on this instance for processing the checkout request.

assets/views/stripe.blade.php

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
        <meta identify="viewport" content material="width=device-width, initial-scale=1">
    <title>Laravel Stripe integration tutorial</title>
    <hyperlink href="https://cdn.jsdelivr.internet/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="nameless">
</head>
<physique>
      
<div class="container">
      
    <h1 class="my-5 text-center">Laravel Stripe integration tutorial</h1>
    <div class="row justify-content-center"> 
        <div class="col-md-4">
            <div class="card" type="width: 18rem;">
              <img src="{{ asset('photos/watch.jpg') }}" class="card-img-top" alt="...">
              <div class="card-body">
                <h5 class="card-title">{{ $product['name'] }}</h5>
                <p class="card-text">{{ $product['description'] }}</p>
                <a href="{{ route('stripe.checkout', ['price' => $product['price'] , 'product' => $product['name']]) }}" class="btn btn-primary">Pay ${{ $product['price'] }}</a>
              </div>
            </div>
        </div>
       
    </div>
          
</div>
      
</physique>
  
</html>

The opposite template file success.blade.php is created to point out an acknowledgment to the client after making the sale.

This Laravel view web page exhibits a “thanks” message to let the client know that the one-time fee request has been acquired.

assets/views/success.blade.php

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta identify="viewport" content material="width=device-width, initial-scale=1">

    <title>Laravel Stripe integration tutorial</title>
    <hyperlink href="https://cdn.jsdelivr.internet/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="nameless">
    <type>
        .bg {
            background-color: #ffc72c;
            border-color: #ffd98e #ffbe3d #de9300;
        }

        .bg:hover {
            background-color: #f7c027;
        }
    </type>
</head>

<physique>
    <div class="container text-center mt-5 pt-5">
        <img src="{{ asset('check-circle.svg') }}" class="tick-img">
        <h1 class="text-center">Thanks for making fee</h1>
        <h3 class="text-center mt-3">{{ $successMessage }}</h3>

        <a href="{{ route('stripe.index') }}" class="btn mt-5 bg">Proceed Procuring</a>
    </div>
</physique>

</html>

stripe thank you page redirect

6. Provoke the Stripe Checkout from the Laravel app controller

This PHP Laravel controller file StripePaymentController.php prepares Stripe fee requests. It units the road objects of the sale, fee technique, and success URL with the fee request.

It units the Stripe secret key with the API occasion earlier than utilizing this to name the API service. After receiving the fee request, the API will redirect the consumer to the success_url with the CHECKOUT_SESSION_ID in its question string.

This CHECKOUT_SESSION_ID is used to get the fee entity standing and extra particulars through the Stripe API.

app/Http/Controllers/StripePaymentController.php

<?php

namespace AppHttpControllers;

use IlluminateHttpRequest;
use IlluminateSupportFacadesConfig;

class StripePaymentController extends Controller
{

    public perform stripe()
    {
        $product = Config::get('stripe.product');
        return view('stripe', compact('product'));
    }

    public perform stripeCheckout(Request $request)
    {
        $stripe = new StripeStripeClient(Config::get('stripe.stripe_secret_key'));

        $redirectUrl = route('stripe.checkout.success') . '?session_id={CHECKOUT_SESSION_ID}';
        $response =  $stripe->checkout->sessions->create([
            'success_url' => $redirectUrl,
            'payment_method_types' => ['link', 'card'],
            'line_items' => [
                [
                    'price_data'  => [
                        'product_data' => [
                            'name' => $request->product,
                        ],
                        'unit_amount'  => 100 * $request->value,
                        'forex'     => 'USD',
                    ],
                    'amount'    => 1
                ],
            ],
            'mode' => 'fee',
            'allow_promotion_codes' => false
        ]);

        return redirect($response['url']);
    }

    public perform stripeCheckoutSuccess(Request $request)
    {
        $stripe = new StripeStripeClient(Config::get('stripe.stripe_secret_key'));

        $session = $stripe->checkout->sessions->retrieve($request->session_id);
        information($session);

        $successMessage = "We've acquired your fee request and can let  shortly.";

        return view('success', compact('successMessage'));
    }
}
?>

Laravel stripe funds net routes

These Laravel net routes are for touchdown the fee initiating web page and thank-you web page on the browser. The stripe/checkout URL sends the consumer request to the handler that initiates making a Stripe Checkout Session through API.

routes/net.php

Route::get("https://phppot.com/", [StripePaymentController::class, 'stripe'])->identify('stripe.index');
Route::get('stripe/checkout', [StripePaymentController::class, 'stripeCheckout'])->identify('stripe.checkout');
Route::get('stripe/checkout/success', [StripePaymentController::class, 'stripeCheckoutSuccess'])->identify('stripe.checkout.success');

Obtain

↑ Again to Prime

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments