"Credit Card Payment with Stripe (updated)"
Bootstrap 3.3.0 Snippet by wmhilton

<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> <!------ Include the above in your HEAD tag ----------> <!-- The MIT License (MIT) Copyright (c) 2015 William Hilton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --> <!-- Vendor libraries --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css"> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.payment/1.2.3/jquery.payment.min.js"></script> <!-- If you're using Stripe for payments --> <script type="text/javascript" src="https://js.stripe.com/v2/"></script> <div class="container"> <div class="row"> <!-- You can make it whatever width you want. I'm making it full width on <= small devices and 4/12 page width on >= medium devices --> <div class="col-xs-12 col-md-4"> <!-- CREDIT CARD FORM STARTS HERE --> <div class="panel panel-default credit-card-box"> <div class="panel-heading display-table" > <div class="row display-tr" > <h3 class="panel-title display-td" >Payment Details</h3> <div class="display-td" > <img class="img-responsive pull-right" src="http://i76.imgup.net/accepted_c22e0.png"> </div> </div> </div> <div class="panel-body"> <form role="form" id="payment-form" method="POST" action="javascript:void(0);"> <div class="row"> <div class="col-xs-12"> <div class="form-group"> <label for="cardNumber">CARD NUMBER</label> <div class="input-group"> <input type="tel" class="form-control" name="cardNumber" placeholder="Valid Card Number" autocomplete="cc-number" required autofocus /> <span class="input-group-addon"><i class="fa fa-credit-card"></i></span> </div> </div> </div> </div> <div class="row"> <div class="col-xs-7 col-md-7"> <div class="form-group"> <label for="cardExpiry"><span class="hidden-xs">EXPIRATION</span><span class="visible-xs-inline">EXP</span> DATE</label> <input type="tel" class="form-control" name="cardExpiry" placeholder="MM / YY" autocomplete="cc-exp" required /> </div> </div> <div class="col-xs-5 col-md-5 pull-right"> <div class="form-group"> <label for="cardCVC">CV CODE</label> <input type="tel" class="form-control" name="cardCVC" placeholder="CVC" autocomplete="cc-csc" required /> </div> </div> </div> <div class="row"> <div class="col-xs-12"> <div class="form-group"> <label for="couponCode">COUPON CODE</label> <input type="text" class="form-control" name="couponCode" /> </div> </div> </div> <div class="row"> <div class="col-xs-12"> <button class="subscribe btn btn-success btn-lg btn-block" type="button">Start Subscription</button> </div> </div> <div class="row" style="display:none;"> <div class="col-xs-12"> <p class="payment-errors"></p> </div> </div> </form> </div> </div> <!-- CREDIT CARD FORM ENDS HERE --> </div> <div class="col-xs-12 col-md-8" style="font-size: 12pt; line-height: 2em;"> <p><h1>Features:</h1> <ul> <li>As-you-type, input formatting</li> <li>Form field validation (also as you type)</li> <li>Graceful error feedback for declined card, etc</li> <li>AJAX form submission w/ visual feedback</li> <li>Creates a Stripe credit card token</li> </ul> </p> <p>Be sure to replace the dummy API key with a valid Stripe API key.</p> <p>Built upon: Bootstrap, jQuery, <a href="http://jqueryvalidation.org/">jQuery Validation Plugin</a>, <a href="https://github.com/stripe/jquery.payment">jQuery.payment library</a>, and <a href="https://stripe.com/docs/stripe.js">Stripe.js</a> </p> </div> </div> </div>
/* Padding - just for asthetics on Bootsnipp.com */ body { margin-top:20px; } /* CSS for Credit Card Payment form */ .credit-card-box .panel-title { display: inline; font-weight: bold; } .credit-card-box .form-control.error { border-color: red; outline: 0; box-shadow: inset 0 1px 1px rgba(0,0,0,0.075),0 0 8px rgba(255,0,0,0.6); } .credit-card-box label.error { font-weight: bold; color: red; padding: 2px 8px; margin-top: 2px; } .credit-card-box .payment-errors { font-weight: bold; color: red; padding: 2px 8px; margin-top: 2px; } .credit-card-box label { display: block; } /* The old "center div vertically" hack */ .credit-card-box .display-table { display: table; } .credit-card-box .display-tr { display: table-row; } .credit-card-box .display-td { display: table-cell; vertical-align: middle; width: 50%; } /* Just looks nicer */ .credit-card-box .panel-heading img { min-width: 180px; }
/* The MIT License (MIT) Copyright (c) 2015 William Hilton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ var $form = $('#payment-form'); $form.find('.subscribe').on('click', payWithStripe); /* If you're using Stripe for payments */ function payWithStripe(e) { e.preventDefault(); /* Abort if invalid form data */ if (!validator.form()) { return; } /* Visual feedback */ $form.find('.subscribe').html('Validating <i class="fa fa-spinner fa-pulse"></i>').prop('disabled', true); var PublishableKey = 'pk_test_6pRNASCoBOKtIshFeQd4XMUh'; // Replace with your API publishable key Stripe.setPublishableKey(PublishableKey); /* Create token */ var expiry = $form.find('[name=cardExpiry]').payment('cardExpiryVal'); var ccData = { number: $form.find('[name=cardNumber]').val().replace(/\s/g,''), cvc: $form.find('[name=cardCVC]').val(), exp_month: expiry.month, exp_year: expiry.year }; Stripe.card.createToken(ccData, function stripeResponseHandler(status, response) { if (response.error) { /* Visual feedback */ $form.find('.subscribe').html('Try again').prop('disabled', false); /* Show Stripe errors on the form */ $form.find('.payment-errors').text(response.error.message); $form.find('.payment-errors').closest('.row').show(); } else { /* Visual feedback */ $form.find('.subscribe').html('Processing <i class="fa fa-spinner fa-pulse"></i>'); /* Hide Stripe errors on the form */ $form.find('.payment-errors').closest('.row').hide(); $form.find('.payment-errors').text(""); // response contains id and card, which contains additional card details console.log(response.id); console.log(response.card); var token = response.id; // AJAX - you would send 'token' to your server here. $.post('/account/stripe_card_token', { token: token }) // Assign handlers immediately after making the request, .done(function(data, textStatus, jqXHR) { $form.find('.subscribe').html('Payment successful <i class="fa fa-check"></i>'); }) .fail(function(jqXHR, textStatus, errorThrown) { $form.find('.subscribe').html('There was a problem').removeClass('success').addClass('error'); /* Show Stripe errors on the form */ $form.find('.payment-errors').text('Try refreshing the page and trying again.'); $form.find('.payment-errors').closest('.row').show(); }); } }); } /* Fancy restrictive input formatting via jQuery.payment library*/ $('input[name=cardNumber]').payment('formatCardNumber'); $('input[name=cardCVC]').payment('formatCardCVC'); $('input[name=cardExpiry').payment('formatCardExpiry'); /* Form validation using Stripe client-side validation helpers */ jQuery.validator.addMethod("cardNumber", function(value, element) { return this.optional(element) || Stripe.card.validateCardNumber(value); }, "Please specify a valid credit card number."); jQuery.validator.addMethod("cardExpiry", function(value, element) { /* Parsing month/year uses jQuery.payment library */ value = $.payment.cardExpiryVal(value); return this.optional(element) || Stripe.card.validateExpiry(value.month, value.year); }, "Invalid expiration date."); jQuery.validator.addMethod("cardCVC", function(value, element) { return this.optional(element) || Stripe.card.validateCVC(value); }, "Invalid CVC."); validator = $form.validate({ rules: { cardNumber: { required: true, cardNumber: true }, cardExpiry: { required: true, cardExpiry: true }, cardCVC: { required: true, cardCVC: true } }, highlight: function(element) { $(element).closest('.form-control').removeClass('success').addClass('error'); }, unhighlight: function(element) { $(element).closest('.form-control').removeClass('error').addClass('success'); }, errorPlacement: function(error, element) { $(element).closest('.form-group').append(error); } }); paymentFormReady = function() { if ($form.find('[name=cardNumber]').hasClass("success") && $form.find('[name=cardExpiry]').hasClass("success") && $form.find('[name=cardCVC]').val().length > 1) { return true; } else { return false; } } $form.find('.subscribe').prop('disabled', true); var readyInterval = setInterval(function() { if (paymentFormReady()) { $form.find('.subscribe').prop('disabled', false); clearInterval(readyInterval); } }, 250);

Related: See More


Questions / Comments:

can you make a video of how to add this to a bootrap studio project. I know thats easy for you. But its the last step in me "committing" to bootstrap. Thanks! I will pay you to make the video. Thanks!

cellurl (1) - 9 months ago - Reply 1


How do l remove the spaces in the credit card number and also remove the Expiry date sign "/" when submitting the form?

flexpeace () - 2 years ago - Reply 0


Hey guys I am sorta new to using these types of things, but my question is how does the form know the amount to charge (if there are multiple plans) and also can we specify for it to be only a 1 time payment OR subscription. Sorry for the lack of knowledge I'm trying to learn all I can. Thank you.

Josh

Joshua C. Herman () - 2 years ago - Reply 0


I have updated the snippet so the form will not accidentally send credit card info to users if JavaScript is disabled (or you accidentally messed up the JavaScript when you copied and pasted it).

William Hilton () - 3 years ago - Reply 0


Warning! This form is a pretty big security risk. Stripe's API clearly discourages using the "name" property of the inputs to collect the values. This form is pretty nice, and I'm going to use it, but it'll need to have the DOM changed to reflect the recommended way here: https://stripe.com/docs/tut...

OP, I'd suggest using the "data-stripe" attribute and let Stripe.js grab the values for the token from there.

Just a heads up!

Christopher Arter () - 3 years ago - Reply 0


I see what you're saying, but disagree that its a big security risk. The reason the Stripe docs do not use the "name" attribute in that example is because they are afraid of accidentally sending the credit card data to the server. This is because they are using the form submit() function, which would normally send all the fields in the form. However, I'm not using the form submit at all (I call e.preventDefault() first thing) and instead use AJAX to send the token to the server.

// AJAX - you would send 'token' to your server here.
$.post('/account/stripe_card_token', { token: token })

William Hilton () - 3 years ago - Reply 0


And a small aside - I don't think there is any security advantage to using data-stripe attributes vs name attributes. And the jQuery validation plugin uses the name attributes so removing them would mess it up.

William Hilton () - 3 years ago - Reply 0


It's because in the instance that a browser has javascript disabled, or a multitude other reasonable issues that causes the javascript to not be executed as expected (e.g., a typo on the ID of the form, a missing closing brace in some other function that causes all execution to fail, etc.) then there is zero chance you accidentally end up with credit card or PII submitted to your server, and in turn accidentally making it's way into log output/exception tracking services/whatever.

glenngillen () - 3 years ago - Reply 0


So what I have done is:
1. changed the subscribe button from type=submit to type=button. Therefore the form is never submitted. (Thus no need to use e.preventDefault() to cancel the default submit action of POSTing.)
2. set the form's action="javascript:void(0);" so the default action is not POSTing. So even if the form IS submitted by manually triggering it with your own custom code it simple does nothing.

I tested the new code with JavaScript turned off, and clicking the button will not submit the form.

For the record, I do not use the data-stripe attributes for two reasons. One, jQuery Validate appears to require "name" attributes. Two, I cannot simply use data-stripe="exp-month" or data-stripe="exp-year" because my date is combined in one field. If anyone has a solution to either of these, I'm all ears.

William Hilton () - 3 years ago - Reply 0


Ahhhhh... that makes sense. So it's not insecure as long as it works as intended. But if JavaScript is disabled, or people copy and paste the HTML into their own project without the JavaScript, then the form submit button becomes a hazard. I will try to update this snippet to be more robust in the case of JavaScript errors.

William Hilton () - 3 years ago - Reply 0


Hi William, will you make any updates based on the discussion here?

Felix Karlsson () - 3 years ago - Reply 0


I did actually, but the disqus comment is out-of-order somehow.
See https://disqus.com/home/dis...

William Hilton () - 3 years ago - Reply 0


Nice.

If I download the code and just run the html-file without any editing, i get an error on row 235 "Can't find variable: validator". Any ideas?

When i click "Start Subscription", nothing happens.

Felix Karlsson () - 3 years ago - Reply 0


if the visitor clicks 2 times on pay accidentally He will be charged twice, here is the fix for that http://bootsnipp.com/user/s.... Kindly review it and merge
Thnx

Mohamed El Hachimi () - 3 years ago - Reply 0


Good catch! Added the fix.

William Hilton () - 3 years ago - Reply 0


I think what imran was trying to say a few months back was the form error validation doesn't work. If you enter a good credit card number with, lets say a bad expiry date for example, and the card is declined the form will still say payment successful. The end user has no idea the card was declined and their subscription is not active.....any insight?

Nick () - 4 years ago - Reply 0


Try opening it in a separate window. The embedded preview doesn't operate properly.

William Hilton () - 3 years ago - Reply 0


How do you pull out the customers stripe id? and send it to a php variable??? :) noob question thanks in advance

Jeff Posth () - 4 years ago - Reply 0


Hopefully you figured this out a while ago, but the relevant part of the code is:
```
// AJAX - you would send 'token' to your server here.
$.post('/account/stripe_card_token', {
token: token
})

```

Then your PHP page would be '/account/stripe_card_token' and have something like:
```
<?php
$card_token= trim($_POST["token"]);
// Do Stripe server-side API stuff here
?>
```

AFAIK the card_token does *not* have a customer id associated with it. What I do is immediately create a Stripe customer object for every user who signs up, and then associate the credit card token to that customer.

William Hilton () - 4 years ago - Reply 0


Hey everybody, I have updated the BootSnipp so that it handles re-sizing better! I also updated it from Bootstrap 3.0.0 to 3.3.0 (which only matters for the visible-xs-inline class that affects whether it displays "EXPIRATION DATE" or "EXP DATE" as far as I know.)

William Hilton () - 4 years ago - Reply 0


I just noticed this snippet has gotten over 17K views and over 70 likes, making it one of the top-rated snippets at the moment! Thanks everyone! I am so humbled, and surprised, and happy that people liked this. Maybe I'll see it on a website someday? :)

William Hilton () - 4 years ago - Reply 0


localhost not complete work and many issue 1: required attribute 2: not check correct card number and all input filed are not correct work.
plz help me.

imran () - 4 years ago - Reply 0


Sounds like you don't know what you're doing... sorry?

William Hilton () - 4 years ago - Reply 0


Yes, resizing this browser window caused the issues Googy pointed out. However, adding an overflow:hidden attribute to the panel-heading class fixed a lot of the issues by itself. Still a few issues between the text "Payment Details" and the card logos, but at least they stay within their container now when resized.

Ben Eckenroed () - 4 years ago - Reply 0


Yeah, sorry about the re-sizing issues. Edit: I've improved resizing, it's much better now.

William Hilton () - 4 years ago - Reply 0


Good work, has a lot of re-sizing issues though.

Googy () - 4 years ago - Reply 0


Thanks! Yeah. It does not resize well. At all. This was for my first bootstrap project, and I didn't think about making it responsive. I started with some else's UI and added the form validation and Stripe integration.

Edit: It resizes better now.

William Hilton () - 4 years ago - Reply 0


Pretty good thanks, some minor usability notes:
- Spaces should be allowed to make number entry easier (they can be stripped on submit)
- The CC type should be auto-selected based on the entry

RagnarDanneskjöld () - 4 years ago - Reply 0


- "Spaces should be allowed"
I'll do one better, and make credit card number input have fancy restrictive formatting via the jQuery.payment library. Also the expiry date!
- "The CC type should be auto-selected"
Well, if I get time that would be cool. But I'd have to a) auto-detect card type and b) have a decent collection of CC images.

William Hilton () - 4 years ago - Reply 0


clean design, like it! (y)

Ikhsan Agustian () - 4 years ago - Reply 0


Thanks!

William Hilton () - 4 years ago - Reply 0