Unverified Commit 7dd0b40f authored by Thor's avatar Thor Committed by GitHub

Add Stripe TypeScript Example (#10482)

Co-authored-by: 's avatarLuis Alvarez D. <luis@zeit.co>
parent 4def88c3
# Stripe keys
STRIPE_PUBLISHABLE_KEY=pk_12345
STRIPE_SECRET_KEY=sk_12345
STRIPE_WEBHOOK_SECRET=whsec_1234
.env
.DS_Store
.vscode
# Node files
node_modules/
# Typescript
dist
# Next.js
.next
.now
\ No newline at end of file
# Example using Stripe with TypeScript and react-stripe-js 🔒💸
- Demo: https://nextjs-typescript-react-stripe-js.now.sh/
- CodeSandbox: https://codesandbox.io/s/nextjs-typescript-react-stripe-js-rqrss
- Tutorial: https://dev.to/thorwebdev/type-safe-payments-with-next-js-typescript-and-stripe-2a1o
This is a full-stack TypeScript example using:
- Frontend:
- Next.js and [SWR](https://github.com/zeit/swr)
- [react-stripe-js](https://github.com/stripe/react-stripe-js) for [Checkout](https://stripe.com/checkout) and [Elements](https://stripe.com/elements)
- Backend
- Next.js [API routes](https://nextjs.org/docs/api-routes/introduction)
- [stripe-node with TypeScript](https://github.com/stripe/stripe-node#usage-with-typescript)
### Included functionality
- Making `.env` variables available to next: [next.config.js](next.config.js)
- **_NOTE_**: when deploying with Now you need to [add your secrets](https://zeit.co/docs/v2/serverless-functions/env-and-secrets) and specify a [now.json](/now.json) file.
- Implementation of a Layout component that loads and sets up Stripe.js and Elements for usage with SSR via `loadStripe` helper: [components/Layout.tsx](components/Layout.tsx).
- Stripe Checkout
- Custom Amount Donation with redirect to Stripe Checkout:
- Frontend: [pages/donate-with-checkout.tsx](pages/donate-with-checkout.tsx)
- Backend: [pages/api/checkout_sessions/](pages/api/checkout_sessions/)
- Checkout payment result page that uses [SWR](https://github.com/zeit/swr) hooks to fetch the CheckoutSession status from the API route: [pages/result.tsx](pages/result.tsx).
- Stripe Elements
- Custom Amount Donation with Stripe Elements & PaymentIntents (no redirect):
- Frontend: [pages/donate-with-elements.tsx](pages/donate-with-checkout.tsx)
- Backend: [pages/api/payment_intents/](pages/api/payment_intents/)
- Webhook handling for [post-payment events](https://stripe.com/docs/payments/accept-a-payment#web-fulfillment)
- By default Next.js API routes are same-origin only. To allow Stripe webhook event requests to reach our API route, we need to add `micro-cors` and [verify the webhook signature](https://stripe.com/docs/webhooks/signatures) of the event. All of this happens in [pages/api/webhooks/index.ts](pages/api/webhooks/index.ts).
- Helpers
- [utils/api-helpers.ts](utils/api-helpers.ts)
- helpers for GET and POST requests.
- [utils/stripe-helpers.ts](utils/stripe-helpers.ts)
- Format amount strings properly using `Intl.NumberFormat`.
- Format amount for usage with Stripe, including zero decimal currency detection.
## How to use
### Using `create-next-app`
Execute [`create-next-app`](https://github.com/zeit/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init) or [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/) to bootstrap the example:
```bash
npm init next-app --example with-stripe-typescript with-stripe-typescript-app
# or
yarn create next-app --example with-stripe-typescript with-stripe-typescript-app
```
### Download manually
Download the example:
```bash
curl https://codeload.github.com/zeit/next.js/tar.gz/canary | tar -xz --strip=2 next.js-canary/examples/with-stripe-typescript
cd with-stripe-typescript
```
### Required configuration
Copy the `.env.example` file into a file named `.env` in the root directory of this project:
```bash
cp .env.example .env
```
You will need a Stripe account ([register](https://dashboard.stripe.com/register)) to run this sample. Go to the Stripe [developer dashboard](https://stripe.com/docs/development#api-keys) to find your API keys and replace them in the `.env` file.
```bash
STRIPE_PUBLISHABLE_KEY=<replace-with-your-publishable-key>
STRIPE_SECRET_KEY=<replace-with-your-secret-key>
```
Now install the dependencies and start the development server.
```bash
npm install
npm run dev
# or
yarn
yarn dev
```
### Forward webhooks to your local dev server
First [install the CLI](https://stripe.com/docs/stripe-cli) and [link your Stripe account](https://stripe.com/docs/stripe-cli#link-account).
Next, start the webhook forwarding:
```bash
stripe listen --forward-to localhost:3000/api/webhooks
```
The CLI will print a webhook secret key to the console. Set `STRIPE_WEBHOOK_SECRET` to this value in your `.env` file.
### Deploy it to the cloud with ZEIT Now
Install [Now](https://zeit.co/now) ([download](https://zeit.co/download))
Add your Stripe [secrets to Now](https://zeit.co/docs/v2/serverless-functions/env-and-secrets):
```bash
now secrets add stripe_publishable_key pk_***
now secrets add stripe_secret_key sk_***
now secrets add stripe_webhook_secret whsec_***
```
To start the deploy, run:
```bash
now
```
After the successful deploy, Now will show you the URL for your site. Copy that URL (`https://your-url.now.sh/api/webhooks`) and create a live webhook endpoint [in your Stripe dashboard](https://stripe.com/docs/webhooks/setup#configure-webhook-settings).
**_Note_** that your live webhook will have a different secret. To update it in your deployed application you will need to first remove the existing secret and then add the new secret:
```bash
now secrets rm stripe_webhook_secret
now secrets add stripe_webhook_secret whsec_***
```
As the secrets are set as env vars in the project at deploy time, we will need to redeploy our app after we made changes to the secrets. Run `now` again to redeploy with the new secret value.
import React, { useState } from 'react'
import CustomDonationInput from '../components/CustomDonationInput'
import { fetchPostJSON } from '../utils/api-helpers'
import { formatAmountForDisplay } from '../utils/stripe-helpers'
import * as config from '../config'
import { useStripe } from '@stripe/react-stripe-js'
const CheckoutForm: React.FunctionComponent = () => {
const [input, setInput] = useState({ customDonation: config.MIN_AMOUNT })
const stripe = useStripe()
const handleInputChange: React.ChangeEventHandler<HTMLInputElement> = e =>
setInput({
...input,
[e.currentTarget.name]: e.currentTarget.value,
})
const handleSubmit: React.FormEventHandler<HTMLFormElement> = async e => {
e.preventDefault()
// Create a Checkout Session.
const response = await fetchPostJSON('/api/checkout_sessions', {
amount: input.customDonation,
})
if (response.statusCode === 500) {
console.error(response.message)
return
}
// Redirect to Checkout.
const { error } = await stripe!.redirectToCheckout({
// Make the id field from the Checkout Session creation API response
// available to this file, so you can provide it as parameter here
// instead of the {{CHECKOUT_SESSION_ID}} placeholder.
sessionId: response.id,
})
// If `redirectToCheckout` fails due to a browser or network
// error, display the localized error message to your customer
// using `error.message`.
console.warn(error.message)
}
return (
<form onSubmit={handleSubmit}>
<CustomDonationInput
name={'customDonation'}
value={input.customDonation}
min={config.MIN_AMOUNT}
max={config.MAX_AMOUNT}
step={config.AMOUNT_STEP}
currency={config.CURRENCY}
onChange={handleInputChange}
/>
<button type="submit" disabled={!stripe}>
Donate {formatAmountForDisplay(input.customDonation, config.CURRENCY)}
</button>
</form>
)
}
export default CheckoutForm
import React from 'react'
import { formatAmountForDisplay } from '../utils/stripe-helpers'
type Props = {
name: string
value: number
min: number
max: number
currency: string
step: number
onChange: (e: React.ChangeEvent<HTMLInputElement>) => void
}
const CustomDonationInput: React.FunctionComponent<Props> = ({
name,
value,
min,
max,
currency,
step,
onChange,
}) => (
<label>
Custom donation amount ({formatAmountForDisplay(min, currency)}-
{formatAmountForDisplay(max, currency)}):
<input
type="number"
name={name}
value={value}
min={min}
max={max}
step={step}
onChange={onChange}
></input>
</label>
)
export default CustomDonationInput
import React, { useState } from 'react'
import CustomDonationInput from '../components/CustomDonationInput'
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 ElementsForm: React.FunctionComponent = () => {
const [input, setInput] = useState({
customDonation: config.MIN_AMOUNT,
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>{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()
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
name="customDonation"
value={input.customDonation}
min={config.MIN_AMOUNT}
max={config.MAX_AMOUNT}
step={config.AMOUNT_STEP}
currency={config.CURRENCY}
onChange={handleInputChange}
/>
<fieldset>
<legend>Your payment details:</legend>
<label>
Cardholder name:
<input
type="Text"
name="cardholderName"
onChange={handleInputChange}
required={true}
/>
</label>
<CardElement
options={{
style: {
base: {
fontSize: '16px',
color: '#424770',
'::placeholder': {
color: '#aab7c4',
},
},
invalid: {
color: '#9e2146',
},
},
}}
/>
</fieldset>
<button
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
import React from 'react'
import Link from 'next/link'
import Head from 'next/head'
import { Elements } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
type Props = {
title?: string
}
const stripePromise = loadStripe(process.env.STRIPE_PUBLISHABLE_KEY!)
const Layout: React.FunctionComponent<Props> = ({
children,
title = 'TypeScript Next.js Stripe Example',
}) => (
<Elements stripe={stripePromise}>
<Head>
<title>{title}</title>
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<header>
<nav>
<Link href="/">
<a>Home</a>
</Link>{' '}
|{' '}
<Link href="/donate-with-checkout">
<a>Donate with Checkout</a>
</Link>{' '}
|{' '}
<Link href="/donate-with-elements">
<a>Donate with Elements</a>
</Link>
</nav>
</header>
{children}
<footer>
<hr />
<span>
This is a{' '}
<a
href="https://github.com/stripe-samples"
target="_blank"
rel="noopener noreferrer"
>
Stripe Sample
</a>
.{' '}
<a
href="https://github.com/zeit/next.js/tree/canary/examples/with-stripe-typescript"
target="_blank"
rel="noopener noreferrer"
>
View code on GitHub
</a>
.
</span>
</footer>
</Elements>
)
export default Layout
import React from 'react'
type Props = {
content: object
}
const PrintObject: React.FunctionComponent<Props> = ({ content }) => {
const formattedContent: string = JSON.stringify(content, null, 2)
return <pre>{formattedContent}</pre>
}
export default PrintObject
export const CURRENCY = 'usd'
// Set your amount limits: Use float for decimal currencies and
// Integer for zero-decimal currencies: https://stripe.com/docs/currencies#zero-decimal.
export const MIN_AMOUNT = 10.0
export const MAX_AMOUNT = 5000.0
export const AMOUNT_STEP = 5.0
/// <reference types='next' />
/// <reference types='next/types/global' />
require('dotenv').config()
module.exports = {
env: {
STRIPE_PUBLISHABLE_KEY: process.env.STRIPE_PUBLISHABLE_KEY,
},
}
{
"env": {
"STRIPE_SECRET_KEY": "@stripe_secret_key",
"STRIPE_WEBHOOK_SECRET": "@stripe_webhook_secret"
},
"build": {
"env": {
"STRIPE_PUBLISHABLE_KEY": "@stripe_publishable_key"
}
}
}
{
"name": "with-stripe-typescript",
"version": "1.0.0",
"description": "Full-stack TypeScript example using Next.js, react-stripe-js, and stripe-node.",
"scripts": {
"dev": "next",
"build": "next build",
"start": "next start"
},
"license": "ISC",
"dependencies": {
"@stripe/react-stripe-js": "^1.0.0-beta.5",
"@stripe/stripe-js": "^1.0.0-beta.6",
"dotenv": "latest",
"micro": "^9.3.4",
"micro-cors": "^0.1.1",
"next": "latest",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"stripe": "^8.8.1",
"swr": "^0.1.16"
},
"devDependencies": {
"@types/micro": "^7.3.3",
"@types/micro-cors": "^0.1.0",
"@types/node": "^13.1.2",
"@types/react": "^16.9.17",
"typescript": "^3.7.4"
}
}
import { NextApiRequest, NextApiResponse } from 'next'
import Stripe from 'stripe'
const stripeSecretKey: string = process.env.STRIPE_SECRET_KEY!
const stripe = new Stripe(stripeSecretKey, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2019-12-03',
typescript: true,
telemetry: true,
})
export default async (req: NextApiRequest, res: NextApiResponse) => {
const id: string = req.query.id as string
try {
if (!id.startsWith('cs_')) {
throw Error('Incorrect CheckoutSession ID.')
}
const checkout_session: Stripe.Checkout.Session = await stripe.checkout.sessions.retrieve(
id,
{ expand: ['payment_intent'] }
)
res.status(200).json(checkout_session)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
}
import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripeSecretKey: string = process.env.STRIPE_SECRET_KEY!
const stripe = new Stripe(stripeSecretKey, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2019-12-03',
typescript: true,
telemetry: true,
})
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const amount: number = req.body.amount
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create Checkout Sessions from body params.
const params: Stripe.Checkout.SessionCreateParams = {
submit_type: 'donate',
payment_method_types: ['card'],
line_items: [
{
name: 'Custom amount donation',
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
quantity: 1,
},
],
success_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${req.headers.origin}/result?session_id={CHECKOUT_SESSION_ID}`,
}
const checkoutSession: Stripe.Checkout.Session = await stripe.checkout.sessions.create(
params
)
res.status(200).json(checkoutSession)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
import { NextApiRequest, NextApiResponse } from 'next'
import { CURRENCY, MIN_AMOUNT, MAX_AMOUNT } from '../../../config'
import { formatAmountForStripe } from '../../../utils/stripe-helpers'
import Stripe from 'stripe'
const stripeSecretKey: string = process.env.STRIPE_SECRET_KEY!
const stripe = new Stripe(stripeSecretKey, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2019-12-03',
typescript: true,
telemetry: true,
})
export default async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const { amount }: { amount: number } = req.body
try {
// Validate the amount that was passed from the client.
if (!(amount >= MIN_AMOUNT && amount <= MAX_AMOUNT)) {
throw new Error('Invalid amount.')
}
// Create PaymentIntent from body params.
const params: Stripe.PaymentIntentCreateParams = {
payment_method_types: ['card'],
amount: formatAmountForStripe(amount, CURRENCY),
currency: CURRENCY,
}
const payment_intent: Stripe.PaymentIntent = await stripe.paymentIntents.create(
params
)
res.status(200).json(payment_intent)
} catch (err) {
res.status(500).json({ statusCode: 500, message: err.message })
}
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
import { buffer } from 'micro'
import Cors from 'micro-cors'
import { NextApiRequest, NextApiResponse } from 'next'
import Stripe from 'stripe'
const stripeSecretKey: string = process.env.STRIPE_SECRET_KEY!
const stripe = new Stripe(stripeSecretKey, {
// https://github.com/stripe/stripe-node#configuration
apiVersion: '2019-12-03',
typescript: true,
telemetry: true,
})
const webhookSecret: string = process.env.STRIPE_WEBHOOK_SECRET!
// Stripe requires the raw body to construct the event.
export const config = {
api: {
bodyParser: false,
},
}
const cors = Cors({
allowMethods: ['POST', 'HEAD'],
})
const webhookHandler = async (req: NextApiRequest, res: NextApiResponse) => {
if (req.method === 'POST') {
const buf = await buffer(req)
const sig = req.headers['stripe-signature']!
let event: Stripe.Event
try {
event = stripe.webhooks.constructEvent(buf.toString(), sig, webhookSecret)
} catch (err) {
// On error, log and return the error message.
console.log(`❌ Error message: ${err.message}`)
res.status(400).send(`Webhook Error: ${err.message}`)
return
}
// Successfully constructed event.
console.log('✅ Success:', event.id)
// Cast event data to Stripe object.
if (event.type === 'payment_intent.succeeded') {
const stripeObject: Stripe.PaymentIntent = event.data
.object as Stripe.PaymentIntent
console.log(`💰 PaymentIntent status: ${stripeObject.status}`)
} else if (event.type === 'charge.succeeded') {
const stripeObject = event.data.object as Stripe.Charge
console.log(`💵 Charge id: ${stripeObject.id}`)
} else if (event.type === 'payment_intent.payment_failed') {
const stripeObject: Stripe.PaymentIntent = event.data
.object as Stripe.PaymentIntent
console.log(
`❌ Payment failed: ${stripeObject.last_payment_error?.message}`
)
} else {
console.warn(`🤷‍♀️ Unhandled event type: ${event.type}`)
}
// Return a response to acknowledge receipt of the event.
res.json({ received: true })
} else {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
}
export default cors(webhookHandler as any)
import { NextPage } from 'next'
import Link from 'next/link'
import Layout from '../components/Layout'
import CheckoutForm from '../components/CheckoutForm'
const DonatePage: NextPage = () => {
return (
<Layout title="Donate with Checkout | Next.js + TypeScript Example">
<h1>Donate with Checkout</h1>
<p>Donate to our project 💖</p>
<CheckoutForm />
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
}
export default DonatePage
import { NextPage } from 'next'
import Link from 'next/link'
import Layout from '../components/Layout'
import ElementsForm from '../components/ElementsForm'
const DonatePage: NextPage = () => {
return (
<Layout title="Donate with Elements | Next.js + TypeScript Example">
<h1>Donate with Elements</h1>
<p>Donate to our project 💖</p>
<ElementsForm />
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
}
export default DonatePage
import { NextPage } from 'next'
import Link from 'next/link'
import Layout from '../components/Layout'
const IndexPage: NextPage = () => {
return (
<Layout title="Home | Next.js + TypeScript Example">
<h1>Type-safe Payments with Next.js, TypeScript, and Stripe 🔒💸</h1>
<p>
<Link href="/donate-with-checkout">
<a>Donate with Checkout</a>
</Link>
</p>
<p>
<Link href="/donate-with-elements">
<a>Donate with Elements</a>
</Link>
</p>
</Layout>
)
}
export default IndexPage
import { NextPage } from 'next'
import { useRouter } from 'next/router'
import Link from 'next/link'
import Layout from '../components/Layout'
import PrintObject from '../components/PrintObject'
import { fetchGetJSON } from '../utils/api-helpers'
import useSWR from 'swr'
const ResultPage: NextPage = () => {
const router = useRouter()
// Fetch CheckoutSession from static page via
// https://nextjs.org/docs/basic-features/data-fetching#static-generation
const { data, error } = useSWR(
router.query.session_id
? `/api/checkout_sessions/${router.query.session_id}`
: null,
fetchGetJSON
)
if (error) return <div>failed to load</div>
return (
<Layout title="Checkout Payment Result | Next.js + TypeScript Example">
<h1>Checkout Payment Result</h1>
<h2>Status: {data?.payment_intent?.status ?? 'loading...'}</h2>
<p>
Your Checkout Session ID:{' '}
<code>{router.query.session_id ?? 'loading...'}</code>
</p>
<PrintObject content={data ?? 'loading...'} />
<p>
<Link href="/">
<a>Go home</a>
</Link>
</p>
</Layout>
)
}
export default ResultPage
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
},
"exclude": ["node_modules"],
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"]
}
export async function fetchGetJSON(url: string) {
try {
const data = await fetch(url).then(res => res.json())
return data
} catch (err) {
throw new Error(err.message)
}
}
export async function fetchPostJSON(url: string, data?: {}) {
try {
// Default options are marked with *
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data || {}), // body data type must match "Content-Type" header
})
return await response.json() // parses JSON response into native JavaScript objects
} catch (err) {
throw new Error(err.message)
}
}
export function formatAmountForDisplay(
amount: number,
currency: string
): string {
let numberFormat = new Intl.NumberFormat(['en-US'], {
style: 'currency',
currency: currency,
currencyDisplay: 'symbol',
})
return numberFormat.format(amount)
}
export function formatAmountForStripe(
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