laravel stripe integration

Laravel 8 stripe payment integration

Laravel 8 has just dropped. With cool new features, Laravel 8 has made its way to cool sweet spot. In this post, I will show you how you can integrate Strip in Laravel 8. So get satrted with laravel stripe integration.

laravel stripe integration

Install package

First we need to install the stripe php sdk.

composer require stripe/stripe-php

Create Controller

Then create a controller. I will name it “StripeController”

php artisan make:controller StripeController 

Make Changes in Controller

Go to app/Http/Controllers and open StripeController. Edit that like below

<?php

namespace App\Http\Controllers;


use Stripe\Stripe;
use Stripe\StripeClient;
use Illuminate\Http\Request;

class StripeController extends Controller
{
    public function processStripeSuccess(){
        
        $stripe = new StripeClient(env('STRIPE_KEY'));

        if(!session()->has('stripe_payment_intent')){
            return back();
        }
        
        try{
			
            $payment_intent =$stripe->paymentIntents->capture(
                session()->get('stripe_payment_intent')
            );
            
			$data=$payment_intent['charges']['data'][0];
			$charge_id=$data['id'];
				
            session()->forget('stripe_payment_intent');

            session()->put('payment_method',['name'=>'stripe','id'=>$charge_id]);

            return back()->with('success','success');
        }
        catch(\Exception $e){
            return back()->withErrors('Error, try again');
        }
       
    }

    public function stripeCheckout(Request $request){
        try{
            Stripe::setApiKey(env('STRIPE_KEY'));

            $currency_code='USD';

            $amount=$request->amount;

            $session = \Stripe\Checkout\Session::create([
                'payment_method_types' => ['card'],
                'line_items' => [[
                    'price_data' => [
                    'currency' => $currency_code,
                    'product_data' => [
                        'name' => 'Product 1',
                    ],
                    'unit_amount' => $amount*100,
                    ],
                    'quantity' => 1,
                ]],
                'mode' => 'payment',
                'payment_intent_data' => [
                    'capture_method' => 'manual',
                ],
                'success_url' => route('stripe-success'),
                'cancel_url' => url('/'),
            ]);
            
            $stripe_session=$session['id'];
			
            session()->put('stripe_payment_intent',$session['payment_intent']);

            return response()->json($stripe_session);
        }
        catch(\Exception $e){
            return response()->json(['error'=>$e->getMessage()],404);
        }
        
    }

}

Make sure you give your secret STRIPE_KEY in your env file.

Make changes in web.php

go to routes and web.php and change as follows.

<?php

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('/',function(){
 return view('welcome');
});

/* stripe */
Route::post('/stripe/initiateCheckout','App\Http\Controllers\StripeController@stripeCheckout')->name('stripe-checkout')
Route::get('/stripe/success','App\Http\Controllers\StripeController@processStripeSuccess')->name('stripe-success');

Change the view

Go to resources/views and welcome.blade.php and add the following.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="csrf-token" content="{{csrf_token()}}">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css2?family=Nunito:wght@400;600;700&display=swap" rel="stylesheet">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
        <style>
            body {
                font-family: 'Nunito';
            }
        </style>
    </head>
    <body>
        <div class="row">
            <div class="col-lg-12 text-center">
                @if ($message = Session::get('success'))
                <div class="alert alert-success alert-block">
                    <button type="button" class="close" data-dismiss="alert">x</button>	
                    <strong>{{ $message }}</strong>
                </div>
                @endif
                @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div><br>
                @endif 
            </div>
        </div>
        <form>
            <div class="row">
                <div class="col-12">
                    <div class="form-group">
                        <label class="form-label text-dark" for="amount">Amount <span class="text-danger">*</span></label>
                        <div class="input-group mb-4">
                            <div class="input-group-prepend">
                                <span class="input-group-text"><i class="fas fa-money"></i></span>
                            </div>
                            <input class="form-control" id="amount" type="number" name="amount">
                        </div>
                    </div>
                </div>
                <input type="hidden" id="stripe_publishable" value="{{env('STRIPE_PUBLISHABLE')}}">
                <div class="col-12 mt-4">
                    <div class="text-center">
                        <button type="submit" id="donate" class="btn btn-secondary mt-4 animate-up-2"><span class="mr-2"><i class="fas fa-donate"></i></span>Donate</button>
                    </div>
                </div>
            </div>    
        </form>
        
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
        <script src="//js.stripe.com/v3/"></script>
        <script src="/checkout.js"></script>
    </body>
</html>    

In your public folder, add checkout.js and add the following lines.

(function($) {

	$(document).ready(function() {

        "use strict"

        $.ajaxSetup({
            headers: {
              'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        var stripe = Stripe($('#stripe_publishable').val());

        var donateButton = $('#donate');
        
        donateButton.on('click', function(e) {
            e.preventDefault();
            donateButton.prop('disabled',true);
            var amount = document.getElementById('amount').value;
            
            if(amount==''){
                alert('Please give some value');
                return;
            }
            $.ajax({
        
                url: '/stripe/initiateCheckout',
                type: 'POST',
                
                data: {
                    amount: amount 
                },
                
                success: function (data) { 
                    stripe.redirectToCheckout({
                        sessionId: data
                    })
                },
                error : function (data){
                    alert('Error');
                    donateButton.prop('disabled',false);
                }
            });
            
            
        });

    })

})(jQuery);	

Please make sure you put your stripe publishable key in env file as STRIPE_PUBLISHABLE.

Conclusion

Your stripe integration is ready now. Enjoy your app.

Leave a Comment

Your email address will not be published. Required fields are marked *


0 Shares
Tweet
Share
Pin
Share