Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Devkhaled94's avatar

Stripe auth (Token field)

Hi guys so I'm trying to make a stripe auth and i don't find the stripe_token field

my form code:-

@csrf
                        <!--Grid column-->
                        <div class="col-md-6 mb-2">

                            <!--firstName-->
                            <div class="md-form ">
                                <input type="text" name="fname" id="firstName" class="form-control">
                                <label for="firstName" class="">First name</label>
                            </div>

                        </div>
                        <!--Grid column-->

                        <!--Grid column-->
                        <div class="col-md-6 mb-2">


                            <!--lastName-->
                            <div class="md-form">
                                <input type="text" name="lname" id="lastName" class="form-control">
                                <label for="lastName" class="">Last name</label>
                            </div>

                        </div>
                        <!--Grid column-->

                    </div>
                    <!--Grid row-->

                    <!--Username-->
                    <div class="md-form input-group pl-0 mb-5">
                        <div class="input-group-prepend">
                            <span class="input-group-text" id="basic-addon1">@</span>
                        </div>
                        <input type="text" name="username" class="form-control py-0" placeholder="Username" aria-describedby="basic-addon1">
                    </div>

                    <!--email-->
                    <div class="md-form mb-5">
                        <input type="text" name="email" id="email" class="form-control" placeholder="[email protected]">
                        <label for="email" class="">Email (optional)</label>
                    </div>

                    <!--address-->
                    <div class="md-form mb-5">
                        <input type="text" name="address1" id="address" class="form-control" placeholder="1234 Main St">
                        <label for="address" class="">Address</label>
                    </div>

                    <!--address-2-->
                    <div class="md-form mb-5">
                        <input type="text" name="address2" id="address-2" class="form-control" placeholder="Apartment or suite">
                        <label for="address-2" class="">Address 2 (optional)</label>
                    </div>

                    <!--Grid row-->
                    <div class="row">

                        <!--Grid column-->
                        <div class="col-lg-4 col-md-12 mb-4">

                            <label for="country">Country</label>
                            <select class="custom-select d-block w-100" id="country" required>
                                <option value="">Choose...</option>
                                <option>United States</option>
                            </select>
                            <div class="invalid-feedback">
                                Please select a valid country.
                            </div>

                        </div>
                        <!--Grid column-->

                        <!--Grid column-->
                        <div class="col-lg-4 col-md-6 mb-4">

                            <label for="state">State</label>
                            <select class="custom-select d-block w-100" id="state" required>
                                <option value="">Choose...</option>
                                <option>California</option>
                            </select>
                            <div class="invalid-feedback">
                                Please provide a valid state.
                            </div>

                        </div>
                        <!--Grid column-->

                        <!--Grid column-->
                        <div class="col-lg-4 col-md-6 mb-4">

                            <label for="zip">Zip</label>
                            <input type="text" class="form-control" id="zip" placeholder="" required>
                            <div class="invalid-feedback">
                                Zip code required.
                            </div>

                        </div>
                        <!--Grid column-->

                    </div>
                    <!--Grid row-->

                    <hr>

                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="same-address">
                        <label class="custom-control-label" for="same-address">Shipping address is the same as my billing address</label>
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="save-info">
                        <label class="custom-control-label" for="save-info">Save this information for next time</label>
                    </div>

                    <hr>

                    <div class="custom-control custom-radio">
                        <label for="card-element">
                            Credit or debit card
                        </label>
                        <div id="card-element">

                        </div>

                        <!-- Used to display form errors. -->
                        <div id="card-errors" role="alert"></div>
                    </div>
                    <hr class="mb-4">
                    <button class="btn btn-primary btn-lg btn-block" type="submit">Continue to checkout</button>

                </form>

the JS code :-

// Create a Stripe client.
var stripe = Stripe('pk_test_b8q5cHdyHfhmOcpPseCUzTwM00ZbPCQx4Z');
// 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',
        fontFamily: '"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();


    var optinas = {
        address1 : document.getElementById('address').value(),
        address2 : document.getElementById('address-2').value(),
        country : document.getElementById('country').value(),
        state : document.getElementById('state').value(),
        zip : document.getElementById('zip').value()
    }

    stripe.createToken(card , optinas).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;
        } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
        }
    });
});

// Submit the form with the token ID.
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(); }

PS:- i tried to give the form an id (id="payment-form") but when i click submit it dosent work at all

0 likes
7 replies
auflyer2's avatar

It looks like you're using Stripe Checkout.

If you look at the method in your javascript stripe.createToken(), you will see it checks for result.error:

stripe.createToken(card , optinas).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;
        } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
        }
    });

If no error is found, it hits the else block:

else {
            // Send the token to your server.
            stripeTokenHandler(result.token);
        }

which takes you to the stripeTokenHandler() method:

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);

This function:

  1. Accepts the token that was returned from the API
  2. Creates a hiddenInput
  3. Sets the name of the hidden input to "stripeToken"
  4. Sets the value of the hidden input to "token.id"
  5. And finally adds the hidden input element to the form

When the form is submitted the token will be part of the POST data sent to your server.

To troubleshoot, first try dd($response->all()); after post. If stripe_token doesn't show up there, it's an issue on the front end.

Either you there is an error, meaning you are getting caught in the else block (meaning the token is never attached to the form), or you have some kind of JS issue. You can use Dev Tools to add breakpoints or just drop some console.log()'s in there to start tracing what is being returned by Stripe.

1 like
auflyer2's avatar

That should of course be $request->all() to troubleshoot :-)

1 like
Devkhaled94's avatar

Thank's guys for your consideration , but i did dd($requset->all()) and the stripe token field value doesn't show up and I already tried to track the js code and didn't found any errors related to the stripe js code

auflyer2's avatar

This is from an older project that I worked on, but looks to be very similar to the code you are working with:

// 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: '"Helvetica Neue", Helvetica, sans-serif',
        fontSmoothing: 'antialiased',
        border: '1px solid',
        fontSize: '16px',
        '::placeholder': {
            color: '#aab7c4'
        }
    },
    invalid: {
        color: '#fa755a',
        iconColor: '#fa755a'
    }
};

// Create an instance of the card Element.
var card = elements.create('card', {style: style});

// 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 = '';
    }
});

//Custom Button Text to allow this code to work on multiple pages with different button text
let btn_text = document.getElementById('btn_text').textContent;

// Handle form submission.
var form = document.getElementById('payment-form');
form.addEventListener('submit', function(event) {
    event.preventDefault();
    $('#subscribe_submit').html('<button class="btn btn-danger btn-round btn-xl mt-4" disabled="disabled"><i class="fa fa-spin fa-spinner"></i> Processing, Please Wait</button>');

    stripe.createToken(card).then(function(result) {
        if (result.error) {
            //Set the button back to normal
            $('#subscribe_submit').html('<button class="btn btn-danger btn-round btn-xl mt-4">' + btn_text + '</button>');
            // Inform the user if there was an error.
            var errorElement = document.getElementById('card-errors');
            errorElement.textContent = result.error.message;
        } else {
            // Send the token to your server.
            stripeTokenHandler(result.token);

        }
    });
});

// Submit the form with the token ID.
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();
}

I can confirm that it continues to work in production with live users, so maybe go through line by line and try to isolate where the problem is.

Since you aren't getting anything on the dd(), it has to be before stripeTokenHandler() adds the token as a hidden input.

Try console.log(result) after stripe.createToken() and post what you get.

It should either have an error or the token should be there.

Devkhaled94's avatar

[ "_token" => "cewP1iMMiv906XrXAfJ4VD5QyIPN4qQogqN90CKq" "fname" => "khaled" "lname" => "waleed" "username" => "khaled94" "email" => "[email protected]" "address1" => "24 Abo baker elsdek" "address2" => null ]

that's the resulat i got every time on dd() no stripe token shows up PS i used that part from your code and still nothing

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();
}
auflyer2's avatar

I'm using your code below and stripped out a bunch of stuff to make it clearer what's going on.

Also added some comments to explain where the token comes from and how it's added to the form.

This is working for me. Try it out and then add back whatever else you want to the form once you have it returning the token:

<form id="payment-form">

    <div id="card-element"></div>

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

    <button type="submit">Submit</button>

</form>

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

<script>

    // Create a Stripe client.
    let stripe = Stripe('pk_test_b8q5cHdyHfhmOcpPseCUzTwM00ZbPCQx4Z');
    // Create an instance of Elements.
    let elements = stripe.elements();

    // Create an instance of the card Element.
    let card = elements.create('card', {
        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) {
        let displayError = document.getElementById('card-errors');
        if (event.error) {
            displayError.textContent = event.error.message;
        } else {
            displayError.textContent = '';
        }
    });

    // Handle form submission.
    let form = document.getElementById('payment-form');

    //Check your console to see what this looks like BEFORE clicking submit
    //Be sure to look before submitting or it will be overridden and you will see the new form in the console
    //Note there is no hidden input - it will be added later with the token
    console.log('Form html PRIOR TO attaching the hidden input', form);

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

        let options = {
            //Add options here - check the console to ensure all fields are found

            // address1 : document.getElementById('address').value(),
            // address2 : document.getElementById('address-2').value(),
            // country : document.getElementById('country').value(),
            // state : document.getElementById('state').value(),
            // zip : document.getElementById('zip').value()
        };

        stripe.createToken(card , options).then(function(result) {

            //This is your token, it will be passed to the stripeTokenHandler function
            //and then added to the form in a hidden input
            console.log('Your Stripe Token that will be added to form as a hidden input', result.token);

            if (result.error) {
                // Inform the user if there was an error.
                let errorElement = document.getElementById('card-errors');
                errorElement.textContent = result.error.message;
            } else {
                // Send the token to your server.
                stripeTokenHandler(result.token);
            }
        });
    });

    // Submit the form with the token ID.
    function stripeTokenHandler(token) {
        // Insert the token ID into the form so it gets submitted to the server

        //let form = document.getElementById('payment-form'); //1.  finds and set form to variable.  This is unnecessary because we already set form in the global scope

        let hiddenInput = document.createElement('input'); //2.  creates a new input on the form
        hiddenInput.setAttribute('type', 'hidden'); //3.  sets the new input's type to "hidden"
        hiddenInput.setAttribute('name', 'stripeToken'); //4.  sets the new input's name to "stripeToken"
        hiddenInput.setAttribute('value', token.id); //5.  sets the new input's value to the stripe token *** this is the value you are looking for
        form.appendChild(hiddenInput); //6.  attaches the new input to the form

        console.log('Form html AFTER to attaching the hidden input', form);  //Check your console to see what this looks like before we add the token

        //form.submit(); //7.  submits the form manually
    }
</script>

retouching25's avatar

Thanks for sharing, I actually trying to get a stripe subscription for my business ( clipping path ) but stripe is saying its unavailable in my country.

Please or to participate in this conversation.