-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy path+page.svelte
92 lines (75 loc) · 2.17 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
<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, PaymentRequestButton } from '$lib'
let stripe = null
let error = null
// define payment details
const paymentRequest = {
country: 'US',
currency: 'usd',
total: { label: 'Demo total', amount: 1099 },
requestPayerName: true,
requestPayerEmail: true
}
onMount(async () => {
stripe = await loadStripe(PUBLIC_STRIPE_KEY)
})
async function createPaymentIntent() {
// create payment intent
const response = await fetch('/examples/payment-request/payment-intent', { method: 'POST' })
const { clientSecret } = await response.json()
return clientSecret
}
async function pay(e) {
const paymentMethod = e.detail.paymentMethod
// create payment intent server side
const clientSecret = await createPaymentIntent()
let result = await stripe.confirmCardPayment(clientSecret, { payment_method: paymentMethod.id })
if (result.error) {
e.detail.complete('fail')
// payment failed, notify user
error = result.error
} else {
e.detail.complete('success')
// payment succeeded, redirect to "thank you" page
goto('/examples/payment-request/thanks')
}
}
</script>
<h1>Payment Request Example</h1>
<p>
If you see a blank screen, it's because this demo will only work if the TLD is <code
>https://localhost</code
> or if you're using production keys.
</p>
<p>
For ApplePay, the production domain must be <a
href="https://support.stripe.com/questions/enable-apple-pay-on-your-stripe-account"
>submitted to Apple</a
>.
</p>
<nav>
<a href="https://github.com/joshnuss/svelte-stripe/tree/main/src/routes/examples/payment-request"
>View code</a
>
</nav>
{#if error}
<p class="error">{error.message} Please try again.</p>
{/if}
<Elements {stripe}>
<div class="wrapper">
<PaymentRequestButton {paymentRequest} on:paymentmethod={pay} />
</div>
</Elements>
<style>
.error {
color: tomato;
}
.wrapper {
margin: 3rem 0;
width: 300px;
}
</style>