TokenKey from Stripe is not being send after submit

  laravel, php, stripe-payments

I’m trying to implement Stripe as payment method and I can’t get the value of the stripeToken after submiting the paymente form. I been trying for hours figuring it out, with no success. I don’t understand much of JS so I don’t know if the problem is there. But it shouldn’t be, since I saw the code elsewhere.

Note:

  • @section(‘extra_head’) is in the end of . @section(‘extra_js’) is before the . And I created a Stripe account and the values of the keys in .env are mine.

  • I don’t know if this is a weird behaviour but I tried a few Exceptions (https://cartalyst.com/manual/stripe/2.0#exceptions) and the only Exception shown was a common one from Laravel "UnexpectedValueException". Could it be that the package was not well installed? My auto-discovery is not working and I have laravel 8 (yeah, I know it’s weird but it’s true). Could it be that causing some bad installation?

If someone needs any more information, please let me know.

I’m using cartalyst/stripe-laravel, I installed as follow:

In composer.json I placed this -> "cartalyst/stripe-laravel": "^13.0" and then did php composer update.

config/app.php:

// in providers array 

        CartalystStripeLaravelStripeServiceProvider::class,
...

// in aliases array

        'Stripe' => CartalystStripeLaravelFacadesStripe::class,

config/services.php:

    'stripe' => [
        'model' => AppModelsUser::class,
        'key' => env('STRIPE_KEY'),
        'secret' => env('STRIPE_SECRET'),
    ],

.env:

STRIPE_KEY=<public_key>
STRIPE_SECRET=<secret_key>

Controller:

<?php


namespace AppHttpControllers;

use IlluminateHttpRequest;
use GloudemansShoppingcartFacadesCart;
use CartalystStripeLaravelFacadesStripe;
use CartalystStripeExceptionCardErrorException;
use AppModelsProduct;

class PaymentController extends Controller
{

    public function index()
    {
        return view('checkout.list');
    }


    public function store(Request $request)
    {
        dd($request->all());

        try {
            $charge = Stripe::charges()->create(
                [
                    'amount' => Cart::total(), // amount in cents
                    'currency' => 'EUR',
                    'source' => $request->stripeToken,
                    'description' => 'Order',
                    'metadata' => [

                    ],
                ]);

            return back()->with('sucess', 'Testing');

        } catch(CartalystStripeExceptionServerErrorException $e) {

            $message = $e->getMessage();
        }

    }


This is the checkout view, where the form is:

@extends('layouts.app')

@section('extra_head')
    <script src="https://js.stripe.com/v3/"></script>
@endsection

@section('content')

         <h1 class="checkout-heading stylish-heading">Checkout</h1>
        <div class="checkout-section">
            <div>
                <form action="{{ route('checkout.store') }}" method="POST" id="payment-form">
                    {{ csrf_field() }}
                    <h2>Billing Details</h2>

                    <div class="form-group">
                        <label for="email">Email Address</label>
                        @if (auth()->user())
                            <input type="email" class="form-control" id="email" name="email" value="{{ auth()->user()->email }}" readonly>
                        @else
                            <input type="email" class="form-control" id="email" name="email" value="{{ old('email') }}" required>
                        @endif
                    </div>
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" class="form-control" id="name" name="name" value="{{ old('name') }}" required>
                    </div>
                    <div class="form-group">
                        <label for="address">Address</label>
                        <input type="text" class="form-control" id="address" name="address" value="{{ old('address') }}" required>
                    </div>

                    <div class="half-form">
                        <div class="form-group">
                            <label for="city">City</label>
                            <input type="text" class="form-control" id="city" name="city" value="{{ old('city') }}" required>
                        </div>
                        <div class="form-group">
                            <label for="province">Province</label>
                            <input type="text" class="form-control" id="province" name="province" value="{{ old('province') }}" required>
                        </div>
                    </div> <!-- end half-form -->

                    <div class="half-form">
                        <div class="form-group">
                            <label for="postalcode">Postal Code</label>
                            <input type="text" class="form-control" id="postalcode" name="postalcode" value="{{ old('postalcode') }}" required>
                        </div>
                        <div class="form-group">
                            <label for="phone">Phone</label>
                            <input type="text" class="form-control" id="phone" name="phone" value="{{ old('phone') }}" required>
                        </div>
                    </div> <!-- end half-form -->

                    <div class="spacer"></div>

                    <h2>Payment Details</h2>

                    <div class="form-group">
                        <label for="name_on_card">Name on Card</label>
                        <input type="text" class="form-control" id="name_on_card" name="name_on_card" value="">
                    </div>

                    <div class="form-group">
                        <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>
                    <div class="spacer"></div>

                    <button type="submit" id="complete-order" class="button-primary full-width">Complete Order</button>



                </form>

            </div>



            <div class="checkout-table-container">
                <h2>Your Order</h2>

                <div class="checkout-table">
                    @foreach (Cart::content() as $item)
                    <div class="checkout-table-row">
                        <div class="checkout-table-row-left">
                            <div class="checkout-item-details">
                                <div class="checkout-table-item">{{ $item->model->title }}</div>
                                <div class="checkout-table-price">{{ $item->model->price }}</div>
                            </div>
                        </div> <!-- end checkout-table -->

                        <div class="checkout-table-row-right">
                            <div class="checkout-table-quantity">{{ $item->qty }}</div>
                        </div>
                    </div> <!-- end checkout-table-row -->
                    @endforeach

                </div> <!-- end checkout-table -->

            </div>

        </div> <!-- end checkout-section -->
    </div>

@endsection

@section('extra_js')

    <script>
        (function(){
                    // Create a Stripe client
                    var stripe = Stripe('{{ config('services.stripe.key') }}');
                    // Create an instance of Elements
                    var elements = stripe.elements();
                    // Custom styling can be passed to options when creating an Element.
                    // (Note that this demo uses a wider set of styles than the guide below.)
                    var style = {
                                base: {
                                            color: '#32325d',
                                            lineHeight: '18px',
                                            fontFamily: '"Roboto", Helvetica Neue", Helvetica, sans-serif',
                                            fontSmoothing: 'antialiased',
                                            fontSize: '16px',
                                            '::placeholder': {
                                                        color: '#aab7c4'
                                                    }
                                        },
                                invalid: {
                                            color: '#fa755a',
                                            iconColor: '#fa755a'
                                        }
                            };
                    // Create an instance of the card Element
                    var card = elements.create('card', {
                                style: style,
                                hidePostalCode: true
                            });

                    // Add an instance of the card Element into the `card-element` <div>
                    card.mount('#card-element');
                    // Handle real-time validation errors from the card Element.
                    card.addEventListener('change', function(event) {
                                var displayError = document.getElementById('card-errors');
                                if (event.error) {
                                            displayError.textContent = event.error.message;
                                        } else {
                                                    displayError.textContent = '';
                                                }
                            });
                    // Handle form submission
                    var form = document.getElementById('payment-form');
                    form.addEventListener('submit', function(event) {
                                event.preventDefault();
                                // Disable the submit button to prevent repeated clicks
                                document.getElementById('complete-order').disabled = true;
                                var options = {
                                            name: document.getElementById('name_on_card').value,
                                            address_line1: document.getElementById('address').value,
                                            address_city: document.getElementById('city').value,
                                            address_state: document.getElementById('province').value,
                                            address_zip: document.getElementById('postalcode').value
                                        }
                                stripe.createToken(card, options).then(function(result) {
                                            if (result.error) {
                                                        // Inform the user if there was an error
                                                        var errorElement = document.getElementById('card-errors');
                                                        errorElement.textContent = result.error.message;
                                                        // Enable the submit button
                                                        document.getElementById('complete-order').disabled = false;
                                                    } else {
                                                                // Send the token to your server
                                                                stripeTokenHandler(result.token);
                                                            }
                                        });
                            });
                    function stripeTokenHandler(token) {
                                // Insert the token ID into the form so it gets submitted to the server
                                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);
                                // Submit the form
                                form.submit();
                            }
                })();
    </script>

@endsection

Debugging

After dd($request->all() ) in store method the striveToken is missing:

array:9 [▼
  "_token" => "IWUpmaswjyWfMRGk8UWbc7kMzdJfUXhrlbU79Kht"
  "email" => "[email protected]"
  "name" => "asdasda"
  "address" => "sdasd"
  "city" => "asdasd"
  "province" => "adsasd"
  "postalcode" => "asd"
  "phone" => "asd"
  "name_on_card" => "asdasd"
]

Source: Laravel

Leave a Reply