Skip to content

Instantly share code, notes, and snippets.

@briancollins
Forked from maccman/StripeTutorialPage.html
Last active October 10, 2019 23:10
Show Gist options
  • Save briancollins/6365455 to your computer and use it in GitHub Desktop.
Save briancollins/6365455 to your computer and use it in GitHub Desktop.
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Stripe Getting Started Form</title>
<!-- The required Stripe lib -->
<script type="text/javascript" src="https://js.stripe.com/v2/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
// This identifies your website in the createToken call below
Stripe.setPublishableKey('YOUR_PUBLISHABLE_KEY');
var stripeResponseHandler = function(status, response) {
var $form = $('#payment-form');
if (response.error) {
// Show the errors on the form
$form.find('.payment-errors').text(response.error.message);
$form.find('button').prop('disabled', false);
} else {
// token contains id, last4, and card type
var token = response.id;
// Insert the token into the form so it gets submitted to the server
$form.append($('<input type="hidden" name="stripeToken" />').val(token));
// and re-submit
$form.get(0).submit();
}
};
jQuery(function($) {
$('#payment-form').submit(function(e) {
var $form = $(this);
// Disable the submit button to prevent repeated clicks
$form.find('button').prop('disabled', true);
Stripe.card.createToken($form, stripeResponseHandler);
// Prevent the form from submitting with the default action
return false;
});
});
</script>
</head>
<body>
<h1>Charge $10 with Stripe</h1>
<form action="" method="POST" id="payment-form">
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number"/>
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" data-stripe="exp-month"/>
</label>
<span> / </span>
<input type="text" size="4" data-stripe="exp-year"/>
</div>
<button type="submit">Submit Payment</button>
</form>
</body>
</html>
@jlocashio
Copy link

@reggi: stripe doesn't know it's a $10 charge at this point; this script generates a token for the card, not a charge. The token is used on the server-side to generate the charge of whatever amount you choose.

This is a great start, but the example is terribly incomplete. The token is appended to the form, but the initial values of the card fields are left intact, which means that the token's purpose of keeping card information off your server logs is lost; you are still getting a card number and expiration in your POST.

Make sure that your stripeResponseHandler function includes code to blank out the values of all form fields related to the card before submitting, e.g. in jQuery you could use $form.find('[data-stripe]').val('');.

@robwheeler
Copy link

@ jlocashio: the createToken call seems to remove those fields from the form.

@jlocashio
Copy link

@robwheeler: Funny, it didn't for me. I guess that might be due to the fact that my CC fields are part of a larger form, and have arrayed names, like [card]name and [card]number. Either way, it's never a bad idea to add redundancy, especially when it's 1 line of script.

@alexcasalboni
Copy link

@jlocashio as described here:

Note how input fields representing sensitive card data (number, CVC, expiration month and year) do not have a "name" attribute. This prevents them from hitting your server when the form is submitted.

@grosscorporation
Copy link

I have tried everything, I can't get this to actually work? can I call it a s a file?

<title>Stripe Getting Started Form</title> <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <script type="text/javascript"> // This identifies your website in the createToken call below Stripe.setPublishableKey('pk_test_gvgLjhbCHLx1i3u2lzlhkafX'); ``` var stripeResponseHandler = function(status, response) { var $form = $('#payment-form'); if (response.error) { // Show the errors on the form $form.find('.payment-errors').text(response.error.message); $form.find('button').prop('disabled', false); } else { // token contains id, last4, and card type var token = response.id; // Insert the token into the form so it gets submitted to the server $form.append($('').val(token)); // and re-submit $form.get(0).submit(); } }; jQuery(function($) { $('#payment-form').submit(function(e) { var $form = $(this); // Disable the submit button to prevent repeated clicks $form.find('button').prop('disabled', true); Stripe.card.createToken($form, stripeResponseHandler); // Prevent the form from submitting with the default action return false; }); }); ``` </script>

Charge $10 with Stripe

<div class="form-row">
  <label>
    <span>Card Number</span>
    <input type="text" size="20" data-stripe="number"/>
  </label>
</div>

<div class="form-row">
  <label>
    <span>CVC</span>
    <input type="text" size="4" data-stripe="cvc"/>
  </label>
</div>

<div class="form-row">
  <label>
    <span>Expiration (MM/YYYY)</span>
    <input type="text" size="2" data-stripe="exp-month"/>
  </label>
  <span> / </span>
  <input type="text" size="4" data-stripe="exp-year"/>
</div>

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

@duleitony
Copy link

Hey,
I have a question about payment form.
There are Card Number, CVC and Expiration in your payment form.
There is no cardholder name in this form.
Is it not necessary ?

@digitalwin
Copy link

Thanks for this, but I'm trying to get customer information. I'm using the testing environment but I checked the logs and I'm not seeing the captured information such as name, email, etc. it says "null" and I'm sure I'm missing out on something. What code should I include? Please help. Newbie here. Thanks in advance

@JackWells
Copy link

When I use the jquery-generated pop-up form method, all is well. But when I try this, I get "This customer has no attached card." Tried every possible combination of ideas from SO. My advice: if a client wants an inline-form, tell them that will be 10 billiable hours additional - minimum.

@NodexTech
Copy link

schir1964

$ prefixes in variables will not cause an error in javascript.

@mrgoldfinder
Copy link

ALL VERY NICE BUT, WHERE DOWS THE CUSTOMER GO TO COLLECT THE ITEM HE HAS JUST BOUGHT?

@webtronix1
Copy link

Very nice Demo and scripts...............

@ryomaito
Copy link

Does the stripe library always use jsonp? or does it use XHR too? I see code for both in the library

@vladimir-tosev-etondigital

Can we use two digits year. It passes in test mode but it is nowhere stated.

@shivam-developer
Copy link

Hi ,
I tried this ,but after submitting and getting token it doesn't give response like alert success or transaction success related info i.e. when i get token what should be happened at stripe end side.
Is it possible in android?

@donaldhwong
Copy link

Run the code and got an error: HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used.

What's wrong?

@lgs
Copy link

lgs commented Dec 25, 2014

@JackWells Just turn off turbo links by adding data-no-turbolink to the body tag and will works:

<body data-no-turbolink>
...
</body>

@devdemi
Copy link

devdemi commented Jan 20, 2015

Is there any way to add possibility to Remeber me as on Embedded form?

@mhavard999
Copy link

Why is the whole form submitted at the end? Isn't the point that you use stripe.js to get the token so you don't have to send the card number, cvc, and exp date to your own server?

Edit: Nevermind. Already answered in the tutorial. They don't have name attributes so they won't get submitted to the server.

@synic
Copy link

synic commented Mar 27, 2015

Using this method, how does one protect against XSS like <img src=x onerror=alert(1)> in the exp-year or exp-month fields?

Try it yourself, you will get an alert.

@deepjyoti
Copy link

How to get customerid? As we can not use same token Id for multiple payment.

@claudio-dalicandro
Copy link

I can't find any example about the "Remember me" checkbox in the custom form, you can have that functionality only with the javascript version of the form?

@demental
Copy link

demental commented Jun 4, 2015

For some reason I cannot explain (yet), exp, card number and cvc hit our servers when submitting form.
I added $('.stripe-sensitive').remove(); before submitting as a workaround but this is an ugly patch.

Looking at the html generated code I get this :

<input id="cardNumber-checkout" type="text" maxlength="20" autocomplete="off" class="card-number stripe-sensitive form-control required" placeholder="Card number"  data-stripe="number" />

So far so good...

But when I inspect with the browser devtools, I get this :

<input id="cardNumber-checkout" type="text" maxlength="20" autocomplete="off" class="card-number stripe-sensitive form-control required" placeholder="Card number" data-stripe="number" name="card-number">

So it seems that some javascript add the name attribute to the fields. Anybody experiencing the same issue ?

@nghuuphuoc
Copy link

Based on this tutorial page, the Validating custom Stripe form example covers steps to create a simple payment form in Bootstrap, validate the fields and connect with Stripe API.

@tyrw
Copy link

tyrw commented Sep 17, 2015

+1 for enabling (or better documenting) the "Remember Me" functionality in custom forms.

@samvloeberghs
Copy link

@synic, how does this relate to security vulnerability? You can basically put an alert ( or any other code ) on every page on the web you want. The point is that you don't save this information inputted anywhere in your webapplication, so it won't get injected in other places of the website for other users. Stripe handles / validates the inputted values.

@jkarnowski
Copy link

I want to allow users to input the amount of money they pay me. I do not want a fixed, set amount. How do I set the variable amount so that I send Stripe a varied amount of money? I am using Rails + the custom form for Stripe.

@cbu123
Copy link

cbu123 commented Jan 16, 2016

After the data is captured, how is it processed ? when i fill the form out i do not see the balance on my stripe dashboard.

Copy link

ghost commented Mar 9, 2016

@jkarnowski

I did the user input as the following (in my controller in Laravel)

       `<form action="" method="POST" id="payment-form">
      <span class="payment-errors"></span>
      <div class="form-row">

        <label>
          <span>Donation Amount (USD only)</span>
          <input type="text" size="20" name="donationAmount"/>
        </label>
      </div>

      <div class="form-row">
        <label>
          <span>Card Number</span>
          <input type="text" size="20" data-stripe="number"/>
        </label>
      </div>

      <div class="form-row">
        <label>
          <span>CVC</span>
          <input type="text" size="4" data-stripe="cvc"/>
        </label>
      </div>

      <div class="form-row">
        <label>
          <span>Expiration (MM/YYYY)</span>
          <input type="text" size="2" data-stripe="exp-month"/>
        </label>
        <span> / </span>
        <input type="text" size="4" data-stripe="exp-year"/>
      </div>

      <button type="submit">Submit Payment</button>
    </form>`

Then in my controller I put:

         `public function getDonorInformation(){
        // Get the credit card details submitted by the form
        $token = Input::get('stripeToken');
        $donation = Input::get('donationAmount');

        function getMoneyAsCents($donation)
            {
                $donation = preg_replace("/\,/i","",$donation);
                $donation = preg_replace("/([^0-9\.\-])/i","",$donation);

                if (!is_numeric($donation))
                {
                    return 0.00;
                }
                // convert to a float explicitly
                $donation = (float)$donation;
                return round($donation,2)*100;
            }

        $value = getMoneyAsCents($donation);

        try {
          $charge = Stripe_Charge::create(array(
            "amount" => $value, // amount in cents, again
            "currency" => "usd",
            "source" => $token,
            "description" => "Example charge"
            ));
        } catch(Stripe_CardError $e) {
          // The card has been declined
        }`

It works.

@antonydenyer
Copy link

Just wanted to double check the possible values for the data-stripe attribute and incase anyone was have the same problem I had. Looking at the source for https://js.stripe.com/v2/ it looks like it should be:

number
cvc
exp
exp_month
exp_year
name
address_line1
address_line2
address_city
address_state
address_zip
address_country
currency

Is that right? Is there any other documentation that I'm missing?

Thanks

@MladenJanjetovic
Copy link

Can I use data-stripe="name" for cardholder name?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment