๐Ÿ“ฆ payloadcms / template-ecommerce-nextjs

๐Ÿ“„ index.tsx ยท 186 lines
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
177
178
179
180
181
182
183
184
185
186import React, { Fragment, useEffect } from 'react'
import { gql } from '@apollo/client'
import { Elements } from '@stripe/react-stripe-js'
import { loadStripe } from '@stripe/stripe-js'
import { GetStaticProps } from 'next'
import Link from 'next/link'
import { useRouter } from 'next/router'

import { CheckoutForm } from '../../components/CheckoutForm'
import { Gutter } from '../../components/Gutter'
import { Media } from '../../components/Media'
import { Price } from '../../components/Price'
import { getApolloClient } from '../../graphql'
import { FOOTER, HEADER, SETTINGS } from '../../graphql/globals'
import { Settings } from '../../payload-types'
import { useAuth } from '../../providers/Auth'
import { useCart } from '../../providers/Cart'

import classes from './index.module.scss'

const apiKey = `${process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY}`
const stripe = loadStripe(apiKey)

const CheckoutPage: React.FC<{
  settings: Settings
}> = props => {
  const {
    settings: { shopPage },
  } = props

  const { user } = useAuth()
  const router = useRouter()
  const [error, setError] = React.useState(null)
  const [clientSecret, setClientSecret] = React.useState()
  const hasMadePaymentIntent = React.useRef(false)

  const { cart, cartIsEmpty, cartTotal } = useCart()

  useEffect(() => {
    if (user === null) {
      router.push('/account/login?unauthorized=account')
    }
  }, [router, user])

  useEffect(() => {
    if (user !== null && cartIsEmpty) {
      router.push('/cart')
    }
  }, [router, user, cartIsEmpty])

  useEffect(() => {
    if (user && cart && hasMadePaymentIntent.current === false) {
      hasMadePaymentIntent.current = true

      const makeIntent = async () => {
        try {
          const req = await fetch(`${process.env.NEXT_PUBLIC_CMS_URL}/api/checkout`, {
            method: 'POST',
            credentials: 'include',
          })

          const res = await req.json()

          if (res.error) {
            setError(res.error)
          } else if (res.client_secret) {
            setError(null)
            setClientSecret(res.client_secret)
          }
        } catch (e) {
          setError('Something went wrong.')
        }
      }

      makeIntent()
    }
  }, [cart, user])

  if (!user || !stripe) return null

  return (
    <Gutter className={classes.checkoutPage}>
      {!clientSecret && !error && <div className={classes.loading}>Loading...</div>}
      {!clientSecret && error && (
        <div className={classes.error}>
          <p>Error:</p>
          {error}
        </div>
      )}
      {clientSecret && (
        <Elements
          stripe={stripe}
          options={{
            clientSecret,
          }}
        >
          <h1>Checkout</h1>
          <p>
            This is a self-hosted, secure checkout using Stripe&apos;s Payment Element component.
            Use credit card number <b>4242 4242 4242 4242</b> with any future date and CVC to create
            a mock purchase. An order will be generated in the CMS and will appear in your account.
          </p>
          {error && <p>{error}</p>}
          {cartIsEmpty && (
            <div>
              {'Your '}
              <Link href="/cart">cart</Link>
              {' is empty.'}
              {typeof shopPage === 'object' && shopPage?.slug && (
                <Fragment>
                  {' '}
                  <Link href={`/${shopPage.slug}`}>Continue shopping?</Link>
                </Fragment>
              )}
            </div>
          )}
          {!cartIsEmpty && (
            <div className={classes.items}>
              {cart.items.map((item, index) => {
                if (typeof item.product === 'object') {
                  const {
                    quantity,
                    product,
                    product: {
                      title,
                      meta: { image: metaImage },
                    },
                  } = item

                  const isLast = index === cart.items.length - 1

                  return (
                    <Fragment key={index}>
                      <div className={classes.row}>
                        <div className={classes.mediaWrapper}>
                          {!metaImage && <span className={classes.placeholder}>No image</span>}
                          {metaImage && typeof metaImage !== 'string' && (
                            <Media imgClassName={classes.image} resource={metaImage} fill />
                          )}
                        </div>
                        <div className={classes.rowContent}>
                          <h6 className={classes.title}>{title}</h6>
                          {`Quantity: ${quantity}`}
                          <Price product={product} button={false} />
                        </div>
                      </div>
                      {!isLast && <hr className={classes.rowHR} />}
                    </Fragment>
                  )
                }
                return null
              })}
              <div className={classes.orderTotal}>{`Order total: ${cartTotal.formatted}`}</div>
            </div>
          )}
          <CheckoutForm />
        </Elements>
      )}
    </Gutter>
  )
}

export const getStaticProps: GetStaticProps = async () => {
  const apolloClient = getApolloClient()

  const { data } = await apolloClient.query({
    query: gql(`
      query {
        ${HEADER}
        ${FOOTER}
        ${SETTINGS}
      }
    `),
  })

  return {
    props: {
      header: data?.Header || null,
      footer: data?.Footer || null,
      settings: data?.Settings || null,
    },
  }
}

export default CheckoutPage