-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy path+page.svelte
119 lines (98 loc) · 2.54 KB
/
+page.svelte
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
<script>
import { goto } from '$app/navigation'
import { onMount } from 'svelte'
import { loadStripe } from '@stripe/stripe-js'
import { PUBLIC_STRIPE_KEY } from '$env/static/public'
import { Elements, ExpressCheckout } from '$lib'
let stripe = null
let error = null
let elements
let processing = false
onMount(async () => {
stripe = await loadStripe(PUBLIC_STRIPE_KEY)
})
async function createPaymentIntent() {
const response = await fetch('/examples/express-checkout/payment-intent', {
method: 'POST',
headers: {
'content-type': 'application/json'
},
body: JSON.stringify({})
})
const { clientSecret } = await response.json()
return clientSecret
}
async function click(event) {
const options = {
emailRequired: true,
phoneNumberRequired: true,
lineItems: [
{
name: 'Rad T-Shirt',
amount: 1099
}
]
}
event.detail.resolve(options)
}
async function confirm() {
// avoid processing duplicates
if (processing) return
processing = true
let result = await elements.submit()
if (result.error) {
// validation failed, notify user
error = result.error
processing = false
return
}
// create payment intent server side
const clientSecret = await createPaymentIntent()
const return_url = new URL('/examples/express-checkout/thanks', window.location.origin).toString()
// confirm payment with stripe
result = await stripe.confirmPayment({
elements,
clientSecret,
confirmParams: {
return_url
}
})
// log results, for debugging
console.log({ result })
if (result.error) {
// payment failed, notify user
error = result.error
processing = false
} else {
// payment succeeded, redirect to "thank you" page
goto('/examples/express-checkout/thanks')
}
}
</script>
<h1>Express Checkout Example</h1>
<nav>
<a href="https://github.com/joshnuss/svelte-stripe/tree/main/src/routes/examples/express-checkout">View code</a>
</nav>
{#if error}
<p class="error">{error.message} Please try again.</p>
{/if}
<Elements
{stripe}
mode="payment"
currency="usd"
amount={1099}
bind:elements>
<ExpressCheckout
on:confirm={confirm}
on:click={click}
buttonHeight={50}
buttonTheme={{googlePay: 'white'}}
buttonType={{googlePay: 'donate'}}
paymentMethodOrder={['googlePay', 'link']}/>
</Elements>
<style>
.error {
color: tomato;
margin: 2rem 0 0;
}
</style>