Basic Stripe v3 checkout integration with laravel 5.8

I am using Laravel 5.8 the server quickstart example to send a user to Stripe to make a payment. I need to create a solution for users to buy credits.

https://stripe.com/docs/checkout/integration-builder

My HTML:

<form class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
                        <div class="input-group">
                          <div class="input-group-append">
                                <button id="checkout-button" class="btn btn-danger" type="button">
                                    Buy Credits
                                </button>
                            </div>
                            <select type="text" class="form-control bg-light border-0 small" placeholder="Search for..." aria-label="Search" aria-describedby="basic-addon2" id="credits">
                              <option value="10">10 credits (10 bookings) 50 eur</option>
                              <option value="30">30 credits (30 bookings) 120 eur</option>
                              <option value="50">50 credits (50 bookings) 150 eur</option>
                              <option value="100">100 credits (100 bookings) 200 eur</option>

                            </select>
                            
                        </div>
                    </form>

my JS code:

<script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1&features=fetch"></script>
    <script src="https://js.stripe.com/v3/"></script>
<script type="text/javascript">
    // Create an instance of the Stripe object with your publishable API key
    var stripe = Stripe("pk_test_5sdfsdfsdfsdfsdfE66bX2iZRmHlOWjh91PSdQx00aY4FMWxI");
    var checkoutButton = document.getElementById("checkout-button");
    var credits = document.getElementById("credits").value;
    checkoutButton.addEventListener("click", function () {
      fetch("/buy_credits/"+credits, {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
  </script>

and my server-side code:

use StripeStripe;
use StripeCustomer;
use StripeCharge;

use Auth; 
require_once base_path('vendor/stripe/stripe-php/init.php');


class BookingsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return IlluminateHttpResponse
     */

   

    public function buy_credits($credits)
    {

 StripeStripe::setApiKey('sk_test_51I9rQNIjkMFMwNsdfdsfsdfsdfsdp8CSkMl5iBl0pRMwFk643ZAM00WrbsJy3U');

 $YOUR_DOMAIN = 'http://localhost:8000';
       $checkout_session = StripeCheckoutSession::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'usd',
      'unit_amount' => $credits,
      'product_data' => [
        'name' => 'Credits',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => $YOUR_DOMAIN . '/success.html',
  'cancel_url' => $YOUR_DOMAIN . '/cancel.html',
]);
echo json_encode(['id' => $checkout_session->id]);

    }

I also using composer install Stripe-PHP library

and my route web.php:

Route::post('buy_credits/{credits}', '[email protected]_credits');

Now when I click on button ‘Buy Credits’ I got just 419 error page. Please help me to integrate Stripe with Laravel

Source: Laravel

Leave a Reply