forked from matthewmueller/stripe-checkout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
77 lines (63 loc) · 1.48 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Module Dependencies
*/
var Deferred = require('deferral')
/**
* Async loader on the browser-side
*/
var isBrowser = typeof window !== 'undefined'
var Load = isBrowser ? require('./load') : function() {}
/**
* Export `Stripe`
*/
module.exports = Stripe
/**
* Initialize `Stripe`
*/
function Stripe(setup, script) {
setup = setup || {}
script = script || 'https://checkout.stripe.com/checkout.js'
const loading = tryLoading(script, new Deferred(), 5)
return function stripe(params) {
if (!isBrowser)
return loading.reject('stripe-checkout only works in the browser')
const complete = new Deferred()
const config = Object.assign(
{
token: function(token) {
complete.resolve(token)
},
closed: function() {
complete.resolve(false)
}
},
setup,
params
)
return loading.then(function() {
const handler = window.StripeCheckout.configure(config)
handler.open(config)
return complete
})
}
}
function tryLoading(script, deferred, retry) {
if (!isBrowser) {
return deferred
} else if (retry <= 0) {
return deferred.reject('timeout expired')
}
var loaded = false
Load(script, function(err) {
if (err) {
return tryLoading(script, deferred, retry - 1)
}
loaded = true
return deferred.resolve()
})
setTimeout(function() {
if (loaded) return deferred
tryLoading(script, deferred, retry - 1)
}, 10000)
return deferred
}