Last active
August 29, 2015 14:06
-
-
Save simenbrekken/6dfe628d6a1904ff7f2e to your computer and use it in GitHub Desktop.
Stripe.js promise based async client loader
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var Promise = require('bluebird'); | |
| var CLIENT_URL = 'https://js.stripe.com/v2/'; | |
| var PUBLISHABLE_KEY = '...'; | |
| var _promise; | |
| function loadClient() { | |
| // If we haven't started loading yet, create a promise | |
| if (!_promise) { | |
| _promise = new Promise(function(resolve) { | |
| var script = document.createElement('script'); | |
| script.async = true; | |
| script.type = 'text/javascript'; | |
| script.onload = function() { | |
| var client = window.Stripe; | |
| client.setPublishableKey(PUBLISHABLE_KEY); | |
| resolve(client); | |
| }; | |
| script.src = CLIENT_URL; | |
| document.getElementsByTagName('head')[0].appendChild(script); | |
| }); | |
| } | |
| return _promise; | |
| } | |
| function createToken(cardNumber, expirationMonth, expirationYear, verificationCode) { | |
| return loadClient().then(function(client) { | |
| return new Promise(function(resolve, reject) { | |
| client.createToken({ | |
| number: cardNumber, | |
| exp_month: expirationMonth, | |
| exp_year: expirationYear, | |
| cvc: verificationCode | |
| }, function(status, response) { | |
| if (response.error) { | |
| return reject(response.error); | |
| } | |
| resolve(response.id); | |
| }); | |
| }); | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment