This repository was archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 66
/
Copy pathElementsForm.tsx
176 lines (157 loc) · 4.9 KB
/
ElementsForm.tsx
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import React, { useState } from 'react';
import CustomDonationInput from '../components/CustomDonationInput';
import StripeTestCards from '../components/StripeTestCards';
import PrintObject from '../components/PrintObject';
import { fetchPostJSON } from '../utils/api-helpers';
import { formatAmountForDisplay } from '../utils/stripe-helpers';
import * as config from '../config';
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
const CARD_OPTIONS = {
iconStyle: 'solid' as const,
style: {
base: {
iconColor: '#6772e5',
color: '#6772e5',
fontWeight: '500',
fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
fontSize: '16px',
fontSmoothing: 'antialiased',
':-webkit-autofill': {
color: '#fce883',
},
'::placeholder': {
color: '#6772e5',
},
},
invalid: {
iconColor: '#ef2961',
color: '#ef2961',
},
},
};
const ElementsForm = () => {
const [input, setInput] = useState({
customDonation: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP),
cardholderName: '',
});
const [payment, setPayment] = useState({ status: 'initial' });
const [errorMessage, setErrorMessage] = useState('');
const stripe = useStripe();
const elements = useElements();
const PaymentStatus = ({ status }: { status: string }) => {
switch (status) {
case 'processing':
case 'requires_payment_method':
case 'requires_confirmation':
return <h2>Processing...</h2>;
case 'requires_action':
return <h2>Authenticating...</h2>;
case 'succeeded':
return <h2>Payment Succeeded 🥳</h2>;
case 'error':
return (
<>
<h2>Error 😭</h2>
<p className="error-message">{errorMessage}</p>
</>
);
default:
return null;
}
};
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = (e) =>
setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value,
});
const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
// Abort if form isn't valid
if (!e.currentTarget.reportValidity()) return;
setPayment({ status: 'processing' });
// Create a PaymentIntent with the specified amount.
const response = await fetchPostJSON('/api/payment_intents', {
amount: input.customDonation,
});
setPayment(response);
if (response.statusCode === 500) {
setPayment({ status: 'error' });
setErrorMessage(response.message);
return;
}
// Get a reference to a mounted CardElement. Elements knows how
// to find your CardElement because there can only ever be one of
// each type of element.
const cardElement = elements!.getElement(CardElement);
// Use your card Element with other Stripe.js APIs
const { error, paymentIntent } = await stripe!.confirmCardPayment(
response.client_secret,
{
payment_method: {
card: cardElement!,
billing_details: { name: input.cardholderName },
},
}
);
if (error) {
setPayment({ status: 'error' });
setErrorMessage(error.message ?? 'An unknown error occured');
} else if (paymentIntent) {
setPayment(paymentIntent);
}
};
return (
<>
<form onSubmit={handleSubmit}>
<CustomDonationInput
className="elements-style"
name="customDonation"
value={input.customDonation}
min={config.MIN_AMOUNT}
max={config.MAX_AMOUNT}
step={config.AMOUNT_STEP}
currency={config.CURRENCY}
onChange={handleInputChange}
/>
<StripeTestCards />
<fieldset className="elements-style">
<legend>Your payment details:</legend>
<input
placeholder="Cardholder name"
className="elements-style"
type="Text"
name="cardholderName"
onChange={handleInputChange}
required
/>
<div className="FormRow elements-style">
<CardElement
options={CARD_OPTIONS}
onChange={(e) => {
if (e.error) {
setPayment({ status: 'error' });
setErrorMessage(
e.error.message ?? 'An unknown error occured'
);
}
}}
/>
</div>
</fieldset>
<button
className="elements-style-background"
type="submit"
disabled={
!['initial', 'succeeded', 'error'].includes(payment.status) ||
!stripe
}
>
Donate {formatAmountForDisplay(input.customDonation, config.CURRENCY)}
</button>
</form>
<PaymentStatus status={payment.status} />
<PrintObject content={payment} />
</>
);
};
export default ElementsForm;