Unverified Commit 2ec2becb authored by Hidetaka Okamoto's avatar Hidetaka Okamoto Committed by GitHub

[example] Upgrade the with-stripe-typescript example app (#33761)


Hi team!
I found in the `with-stripe-typescript` example that I need to update these things.

- `use-shopping-cart` is launched a new major version
- Stripe launched a new useful payment element named Stripe Payment Element

So I've updated the example app to support these updates.

## Documentation / Examples

- [ ] Make sure the linting passes by running `yarn lint`

## How to test it

Please check the README.md of the example.
https://github.com/vercel/next.js/blob/canary/examples/with-stripe-typescript/README.md

Thanks!
parent f104e910
import React, { ReactNode } from 'react' import React, { ReactNode } from 'react'
import { CartProvider } from 'use-shopping-cart' import { CartProvider } from 'use-shopping-cart/react'
import getStripe from '../utils/get-stripejs'
import * as config from '../config' import * as config from '../config'
const Cart = ({ children }: { children: ReactNode }) => ( const Cart = ({ children }: { children: ReactNode }) => (
<CartProvider <CartProvider
mode="checkout-session" cartMode="checkout-session"
stripe={getStripe()} stripe={process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY as string}
currency={config.CURRENCY} currency={config.CURRENCY}
> >
<>{children}</> <>{children}</>
......
...@@ -2,12 +2,13 @@ import React, { useState, useEffect } from 'react' ...@@ -2,12 +2,13 @@ import React, { useState, useEffect } from 'react'
import StripeTestCards from '../components/StripeTestCards' import StripeTestCards from '../components/StripeTestCards'
import { useShoppingCart } from 'use-shopping-cart' import { useShoppingCart } from 'use-shopping-cart/react'
import { fetchPostJSON } from '../utils/api-helpers' import { fetchPostJSON } from '../utils/api-helpers'
const CartSummary = () => { const CartSummary = () => {
const [loading, setLoading] = useState(false) const [loading, setLoading] = useState(false)
const [cartEmpty, setCartEmpty] = useState(true) const [cartEmpty, setCartEmpty] = useState(true)
const [errorMessage, setErrorMessage] = useState('')
const { const {
formattedTotalPrice, formattedTotalPrice,
cartCount, cartCount,
...@@ -23,14 +24,17 @@ const CartSummary = () => { ...@@ -23,14 +24,17 @@ const CartSummary = () => {
) => { ) => {
event.preventDefault() event.preventDefault()
setLoading(true) setLoading(true)
setErrorMessage('')
const response = await fetchPostJSON( const response = await fetchPostJSON(
'/api/checkout_sessions/cart', '/api/checkout_sessions/cart',
cartDetails cartDetails
) )
if (response.statusCode === 500) { if (response.statusCode > 399) {
console.error(response.message) console.error(response.message)
setErrorMessage(response.message)
setLoading(false)
return return
} }
...@@ -40,6 +44,9 @@ const CartSummary = () => { ...@@ -40,6 +44,9 @@ const CartSummary = () => {
return ( return (
<form onSubmit={handleCheckout}> <form onSubmit={handleCheckout}>
<h2>Cart summary</h2> <h2>Cart summary</h2>
{errorMessage ? (
<p style={{ color: 'red' }}>Error: {errorMessage}</p>
) : null}
{/* This is where we'll render our cart */} {/* This is where we'll render our cart */}
<p suppressHydrationWarning> <p suppressHydrationWarning>
<strong>Number of Items:</strong> {cartCount} <strong>Number of Items:</strong> {cartCount}
......
import { useEffect } from 'react' import { useEffect } from 'react'
import { useShoppingCart } from 'use-shopping-cart' import { useShoppingCart } from 'use-shopping-cart/react'
export default function ClearCart() { export default function ClearCart() {
const { clearCart } = useShoppingCart() const { clearCart } = useShoppingCart()
......
import React, { useState } from 'react' import React, { useState, FC } from 'react'
import CustomDonationInput from '../components/CustomDonationInput' import CustomDonationInput from '../components/CustomDonationInput'
import StripeTestCards from '../components/StripeTestCards' import StripeTestCards from '../components/StripeTestCards'
import PrintObject from '../components/PrintObject' import PrintObject from '../components/PrintObject'
import { fetchPostJSON } from '../utils/api-helpers' import { fetchPostJSON } from '../utils/api-helpers'
import { formatAmountForDisplay } from '../utils/stripe-helpers' import {
formatAmountForDisplay,
formatAmountFromStripe,
} from '../utils/stripe-helpers'
import * as config from '../config' import * as config from '../config'
import { CardElement, useStripe, useElements } from '@stripe/react-stripe-js' import { useStripe, useElements, PaymentElement } from '@stripe/react-stripe-js'
import { PaymentIntent } from '@stripe/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 ElementsForm: FC<{
paymentIntent?: PaymentIntent | null
}> = ({ paymentIntent = null }) => {
const defaultAmout = paymentIntent
? formatAmountFromStripe(paymentIntent.amount, paymentIntent.currency)
: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP)
const [input, setInput] = useState({ const [input, setInput] = useState({
customDonation: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP), customDonation: defaultAmout,
cardholderName: '', cardholderName: '',
}) })
const [paymentType, setPaymentType] = useState('')
const [payment, setPayment] = useState({ status: 'initial' }) const [payment, setPayment] = useState({ status: 'initial' })
const [errorMessage, setErrorMessage] = useState('') const [errorMessage, setErrorMessage] = useState('')
const stripe = useStripe() const stripe = useStripe()
...@@ -80,11 +66,13 @@ const ElementsForm = () => { ...@@ -80,11 +66,13 @@ const ElementsForm = () => {
e.preventDefault() e.preventDefault()
// Abort if form isn't valid // Abort if form isn't valid
if (!e.currentTarget.reportValidity()) return if (!e.currentTarget.reportValidity()) return
if (!elements) return
setPayment({ status: 'processing' }) setPayment({ status: 'processing' })
// Create a PaymentIntent with the specified amount. // Create a PaymentIntent with the specified amount.
const response = await fetchPostJSON('/api/payment_intents', { const response = await fetchPostJSON('/api/payment_intents', {
amount: input.customDonation, amount: input.customDonation,
payment_intent_id: paymentIntent?.id,
}) })
setPayment(response) setPayment(response)
...@@ -94,21 +82,18 @@ const ElementsForm = () => { ...@@ -94,21 +82,18 @@ const ElementsForm = () => {
return 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 // Use your card Element with other Stripe.js APIs
const { error, paymentIntent } = await stripe!.confirmCardPayment( const { error } = await stripe!.confirmPayment({
response.client_secret, elements,
{ confirmParams: {
payment_method: { return_url: 'http://localhost:3000/donate-with-elements',
card: cardElement!, payment_method_data: {
billing_details: { name: input.cardholderName }, billing_details: {
name: input.cardholderName,
}, },
} },
) },
})
if (error) { if (error) {
setPayment({ status: 'error' }) setPayment({ status: 'error' })
...@@ -134,6 +119,7 @@ const ElementsForm = () => { ...@@ -134,6 +119,7 @@ const ElementsForm = () => {
<StripeTestCards /> <StripeTestCards />
<fieldset className="elements-style"> <fieldset className="elements-style">
<legend>Your payment details:</legend> <legend>Your payment details:</legend>
{paymentType === 'card' ? (
<input <input
placeholder="Cardholder name" placeholder="Cardholder name"
className="elements-style" className="elements-style"
...@@ -142,16 +128,11 @@ const ElementsForm = () => { ...@@ -142,16 +128,11 @@ const ElementsForm = () => {
onChange={handleInputChange} onChange={handleInputChange}
required required
/> />
) : null}
<div className="FormRow elements-style"> <div className="FormRow elements-style">
<CardElement <PaymentElement
options={CARD_OPTIONS}
onChange={(e) => { onChange={(e) => {
if (e.error) { setPaymentType(e.value.type)
setPayment({ status: 'error' })
setErrorMessage(
e.error.message ?? 'An unknown error occurred'
)
}
}} }}
/> />
</div> </div>
......
import products from '../data/products.json' import products from '../data/products'
import { useShoppingCart, formatCurrencyString } from 'use-shopping-cart' import { formatCurrencyString } from 'use-shopping-cart'
import { useShoppingCart } from 'use-shopping-cart/react'
const Products = () => { const Products = () => {
const { addItem, removeItem } = useShoppingCart() const { addItem, removeItem } = useShoppingCart()
...@@ -7,7 +8,7 @@ const Products = () => { ...@@ -7,7 +8,7 @@ const Products = () => {
return ( return (
<section className="products"> <section className="products">
{products.map((product) => ( {products.map((product) => (
<div key={product.sku} className="product"> <div key={product.id} className="product">
<img src={product.image} alt={product.name} /> <img src={product.image} alt={product.name} />
<h2>{product.name}</h2> <h2>{product.name}</h2>
<p className="price"> <p className="price">
...@@ -18,13 +19,16 @@ const Products = () => { ...@@ -18,13 +19,16 @@ const Products = () => {
</p> </p>
<button <button
className="cart-style-background" className="cart-style-background"
onClick={() => addItem(product)} onClick={() => {
console.log(product)
addItem(product)
}}
> >
Add to cart Add to cart
</button> </button>
<button <button
className="cart-style-background" className="cart-style-background"
onClick={() => removeItem(product.sku)} onClick={() => removeItem(product.id)}
> >
Remove Remove
</button> </button>
......
[
{
"name": "Bananas",
"description": "Yummy yellow fruit",
"sku": "sku_GBJ2Ep8246qeeT",
"price": 400,
"image": "https://images.unsplash.com/photo-1574226516831-e1dff420e562?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80",
"attribution": "Photo by Priscilla Du Preez on Unsplash",
"currency": "USD"
},
{
"name": "Tangerines",
"sku": "sku_GBJ2WWfMaGNC2Z",
"price": 100,
"image": "https://images.unsplash.com/photo-1482012792084-a0c3725f289f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80",
"attribution": "Photo by Jonathan Pielmayer on Unsplash",
"currency": "USD"
}
]
const product = [
{
name: 'Bananas',
description: 'Yummy yellow fruit',
id: 'sku_GBJ2Ep8246qeeT',
price: 400,
image:
'https://images.unsplash.com/photo-1574226516831-e1dff420e562?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80',
attribution: 'Photo by Priscilla Du Preez on Unsplash',
currency: 'USD',
},
{
name: 'Tangerines',
id: 'sku_GBJ2WWfMaGNC2Z',
price: 100,
image:
'https://images.unsplash.com/photo-1482012792084-a0c3725f289f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=225&q=80',
attribution: 'Photo by Jonathan Pielmayer on Unsplash',
currency: 'USD',
},
]
export default product
...@@ -6,22 +6,22 @@ ...@@ -6,22 +6,22 @@
"start": "next start" "start": "next start"
}, },
"dependencies": { "dependencies": {
"@stripe/react-stripe-js": "1.1.2", "@stripe/react-stripe-js": "1.7.0",
"@stripe/stripe-js": "1.5.0", "@stripe/stripe-js": "1.22.0",
"micro": "^9.3.4", "micro": "^9.3.4",
"micro-cors": "^0.1.1", "micro-cors": "^0.1.1",
"next": "latest", "next": "latest",
"react": "^17.0.2", "react": "^17.0.2",
"react-dom": "^17.0.2", "react-dom": "^17.0.2",
"stripe": "8.56.0", "stripe": "8.200.0",
"swr": "^0.1.16", "swr": "^0.1.16",
"use-shopping-cart": "2.1.0" "use-shopping-cart": "3.0.5"
}, },
"devDependencies": { "devDependencies": {
"@types/micro": "^7.3.3", "@types/micro": "^7.3.3",
"@types/micro-cors": "^0.1.0", "@types/micro-cors": "^0.1.0",
"@types/node": "^13.1.2", "@types/node": "^13.1.2",
"@types/react": "^16.9.17", "@types/react": "^16.9.17",
"typescript": "^3.7.4" "typescript": "4.5.5"
} }
} }
...@@ -3,7 +3,7 @@ import { NextApiRequest, NextApiResponse } from 'next' ...@@ -3,7 +3,7 @@ import { NextApiRequest, NextApiResponse } from 'next'
import Stripe from 'stripe' import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration // https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02', apiVersion: '2020-08-27',
}) })
export default async function handler( export default async function handler(
...@@ -22,6 +22,8 @@ export default async function handler( ...@@ -22,6 +22,8 @@ export default async function handler(
res.status(200).json(checkout_session) res.status(200).json(checkout_session)
} catch (err) { } catch (err) {
res.status(500).json({ statusCode: 500, message: err.message }) const errorMessage =
err instanceof Error ? err.message : 'Internal server error'
res.status(500).json({ statusCode: 500, message: errorMessage })
} }
} }
...@@ -8,13 +8,13 @@ import { NextApiRequest, NextApiResponse } from 'next' ...@@ -8,13 +8,13 @@ import { NextApiRequest, NextApiResponse } from 'next'
* The important thing is that the product info is loaded from somewhere trusted * The important thing is that the product info is loaded from somewhere trusted
* so you know the pricing information is accurate. * so you know the pricing information is accurate.
*/ */
import { validateCartItems } from 'use-shopping-cart/src/serverUtil' import { validateCartItems } from 'use-shopping-cart/utilities/serverless'
import inventory from '../../../data/products.json' import inventory from '../../../data/products'
import Stripe from 'stripe' import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration // https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02', apiVersion: '2020-08-27',
}) })
export default async function handler( export default async function handler(
...@@ -24,8 +24,10 @@ export default async function handler( ...@@ -24,8 +24,10 @@ export default async function handler(
if (req.method === 'POST') { if (req.method === 'POST') {
try { try {
// Validate the cart details that were sent from the client. // Validate the cart details that were sent from the client.
const cartItems = req.body const line_items = validateCartItems(inventory as any, req.body)
const line_items = validateCartItems(inventory, cartItems) const hasSubscription = line_items.find((item) => {
return !!item.price_data.recurring
})
// Create Checkout Sessions from body params. // Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = { const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'pay', submit_type: 'pay',
...@@ -37,13 +39,18 @@ export default async function handler( ...@@ -37,13 +39,18 @@ export default async function handler(
line_items, line_items,
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`, success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/use-shopping-cart`, cancel_url: `${req.headers.origin}/use-shopping-cart`,
mode: hasSubscription ? 'subscription' : 'payment',
} }
const checkoutSession: Stripe.Checkout.Session = const checkoutSession: Stripe.Checkout.Session =
await stripe.checkout.sessions.create(params) await stripe.checkout.sessions.create(params)
res.status(200).json(checkoutSession) res.status(200).json(checkoutSession)
} catch (err) { } catch (err) {
res.status(500).json({ statusCode: 500, message: err.message }) console.log(err)
const errorMessage =
err instanceof Error ? err.message : 'Internal server error'
res.status(500).json({ statusCode: 500, message: errorMessage })
} }
} else { } else {
res.setHeader('Allow', 'POST') res.setHeader('Allow', 'POST')
......
...@@ -6,7 +6,7 @@ import { formatAmountForStripe } from '../../../utils/stripe-helpers' ...@@ -6,7 +6,7 @@ import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe' import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration // https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02', apiVersion: '2020-08-27',
}) })
export default async function handler( export default async function handler(
...@@ -40,7 +40,9 @@ export default async function handler( ...@@ -40,7 +40,9 @@ export default async function handler(
res.status(200).json(checkoutSession) res.status(200).json(checkoutSession)
} catch (err) { } catch (err) {
res.status(500).json({ statusCode: 500, message: err.message }) const errorMessage =
err instanceof Error ? err.message : 'Internal server error'
res.status(500).json({ statusCode: 500, message: errorMessage })
} }
} else { } else {
res.setHeader('Allow', 'POST') res.setHeader('Allow', 'POST')
......
...@@ -6,36 +6,69 @@ import { formatAmountForStripe } from '../../../utils/stripe-helpers' ...@@ -6,36 +6,69 @@ import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe' import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration // https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02', apiVersion: '2020-08-27',
}) })
export default async function handler( export default async function handler(
req: NextApiRequest, req: NextApiRequest,
res: NextApiResponse res: NextApiResponse
) { ) {
if (req.method === 'POST') { if (req.method !== 'POST') {
const { amount }: { amount: number } = req.body res.setHeader('Allow', 'POST')
try { res.status(405).end('Method Not Allowed')
return
}
const {
amount,
payment_intent_id,
}: { amount: number; payment_intent_id?: string } = req.body
// Validate the amount that was passed from the client. // Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) { if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.') res.status(500).json({ statusCode: 400, message: 'Invalid amount.' })
return
}
if (payment_intent_id) {
try {
const current_intent = await stripe.paymentIntents.retrieve(
payment_intent_id
)
// If PaymentIntent has been created, just update the amount.
if (current_intent) {
const updated_intent = await stripe.paymentIntents.update(
payment_intent_id,
{
amount: formatAmountForStripe(amount, CURRENCY),
}
)
res.status(200).json(updated_intent)
return
} }
} catch (e) {
if ((e as any).code !== 'resource_missing') {
const errorMessage =
e instanceof Error ? e.message : 'Internal server error'
res.status(500).json({ statusCode: 500, message: errorMessage })
return
}
}
}
try {
// Create PaymentIntent from body params. // Create PaymentIntent from body params.
const params: Stripe.PaymentIntentCreateParams = { const params: Stripe.PaymentIntentCreateParams = {
payment_method_types: ['card'],
amount: formatAmountForStripe(amount, CURRENCY), amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY, currency: CURRENCY,
description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? '', description: process.env.STRIPE_PAYMENT_DESCRIPTION ?? '',
automatic_payment_methods: {
enabled: true,
},
} }
const payment_intent: Stripe.PaymentIntent = const payment_intent: Stripe.PaymentIntent =
await stripe.paymentIntents.create(params) await stripe.paymentIntents.create(params)
res.status(200).json(payment_intent) res.status(200).json(payment_intent)
} catch (err) { } catch (err) {
res.status(500).json({ statusCode: 500, message: err.message }) const errorMessage =
} err instanceof Error ? err.message : 'Internal server error'
} else { res.status(500).json({ statusCode: 500, message: errorMessage })
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
} }
} }
...@@ -5,7 +5,7 @@ import { NextApiRequest, NextApiResponse } from 'next' ...@@ -5,7 +5,7 @@ import { NextApiRequest, NextApiResponse } from 'next'
import Stripe from 'stripe' import Stripe from 'stripe'
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, { const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!, {
// https://github.com/stripe/stripe-node#configuration // https://github.com/stripe/stripe-node#configuration
apiVersion: '2020-03-02', apiVersion: '2020-08-27',
}) })
const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET! const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET!
...@@ -31,9 +31,11 @@ const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => { ...@@ -31,9 +31,11 @@ const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
try { try {
event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret) event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret)
} catch (err) { } catch (err) {
const errorMessage = err instanceof Error ? err.message : 'Unknown error'
// On error, log and return the error message. // On error, log and return the error message.
console.log(`❌ Error message: ${err.message}`) if (err! instanceof Error) console.log(err)
res.status(400).send(`Webhook Error: ${err.message}`) console.log(`❌ Error message: ${errorMessage}`)
res.status(400).send(`Webhook Error: ${errorMessage}`)
return return
} }
......
import { NextPage } from 'next' import { NextPage } from 'next'
import { useState, useEffect } from 'react'
import { Elements } from '@stripe/react-stripe-js' import { Elements } from '@stripe/react-stripe-js'
import { PaymentIntent } from '@stripe/stripe-js'
import getStripe from '../utils/get-stripejs' import getStripe from '../utils/get-stripejs'
import { fetchPostJSON } from '../utils/api-helpers'
import Layout from '../components/Layout' import Layout from '../components/Layout'
import * as config from '../config'
import ElementsForm from '../components/ElementsForm' import ElementsForm from '../components/ElementsForm'
const DonatePage: NextPage = () => { const DonatePage: NextPage = () => {
const [paymentIntent, setPaymentIntent] = useState<PaymentIntent | null>(null)
useEffect(() => {
fetchPostJSON('/api/payment_intents', {
amount: Math.round(config.MAX_AMOUNT / config.AMOUNT_STEP),
}).then((data) => {
setPaymentIntent(data)
})
}, [setPaymentIntent])
return ( return (
<Layout title="Donate with Elements | Next.js + TypeScript Example"> <Layout title="Donate with Elements | Next.js + TypeScript Example">
<div className="page-container"> <div className="page-container">
<h1>Donate with Elements</h1> <h1>Donate with Elements</h1>
<p>Donate to our project 💖</p> <p>Donate to our project 💖</p>
<Elements stripe={getStripe()}> {paymentIntent && paymentIntent.client_secret ? (
<ElementsForm /> <Elements
stripe={getStripe()}
options={{
appearance: {
variables: {
colorIcon: '#6772e5',
fontFamily: 'Roboto, Open Sans, Segoe UI, sans-serif',
},
},
clientSecret: paymentIntent.client_secret,
}}
>
<ElementsForm paymentIntent={paymentIntent} />
</Elements> </Elements>
) : (
<p>Loading...</p>
)}
</div> </div>
</Layout> </Layout>
) )
......
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5", "target": "ES2019",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
...@@ -11,7 +11,9 @@ ...@@ -11,7 +11,9 @@
"module": "esnext", "module": "esnext",
"moduleResolution": "node", "moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"allowSyntheticDefaultImports": true,
"isolatedModules": true, "isolatedModules": true,
"incremental": true,
"jsx": "preserve" "jsx": "preserve"
}, },
"exclude": ["node_modules"], "exclude": ["node_modules"],
......
...@@ -3,8 +3,11 @@ export async function fetchGetJSON(url: string) { ...@@ -3,8 +3,11 @@ export async function fetchGetJSON(url: string) {
const data = await fetch(url).then((res) => res.json()) const data = await fetch(url).then((res) => res.json())
return data return data
} catch (err) { } catch (err) {
if (err instanceof Error) {
throw new Error(err.message) throw new Error(err.message)
} }
throw err
}
} }
export async function fetchPostJSON(url: string, data?: {}) { export async function fetchPostJSON(url: string, data?: {}) {
...@@ -25,6 +28,9 @@ export async function fetchPostJSON(url: string, data?: {}) { ...@@ -25,6 +28,9 @@ export async function fetchPostJSON(url: string, data?: {}) {
}) })
return await response.json() // parses JSON response into native JavaScript objects return await response.json() // parses JSON response into native JavaScript objects
} catch (err) { } catch (err) {
if (err instanceof Error) {
throw new Error(err.message) throw new Error(err.message)
} }
throw err
}
} }
...@@ -28,3 +28,22 @@ export function formatAmountForStripe( ...@@ -28,3 +28,22 @@ export function formatAmountForStripe(
} }
return zeroDecimalCurrency ? amount : Math.round(amount * 100) return zeroDecimalCurrency ? amount : Math.round(amount * 100)
} }
export function formatAmountFromStripe(
amount: number,
currency: string
): number {
let numberFormat = new Intl.NumberFormat(['en-US'], {
style: 'currency',
currency: currency,
currencyDisplay: 'symbol',
})
const parts = numberFormat.formatToParts(amount)
let zeroDecimalCurrency: boolean = true
for (let part of parts) {
if (part.type === 'decimal') {
zeroDecimalCurrency = false
}
}
return zeroDecimalCurrency ? amount : Math.round(amount / 100)
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment