|
1
|
--- |
|
2
|
tags: |
|
3
|
- cart |
|
4
|
- storefront |
|
5
|
- stripe |
|
6
|
- payment |
|
7
|
products: |
|
8
|
- cart |
|
9
|
- payment |
|
10
|
--- |
|
11
|
|
|
12
|
import { CodeTabs, CodeTab, Prerequisites } from "docs-ui" |
|
13
|
|
|
14
|
export const metadata = { |
|
15
|
title: `Payment with Stripe in React Storefront`, |
|
16
|
} |
|
17
|
|
|
18
|
# {metadata.title} |
|
19
|
|
|
20
|
In this guide, you'll learn how to use Stripe for payment during checkout in a React-based storefront. |
|
21
|
|
|
22
|
<Note title="Tip"> |
|
23
|
|
|
24
|
For other types of frameworks or tech stacks, the steps are similar. Refer to [Stripe's documentation](https://docs.stripe.com/) for available tools for your tech stack. |
|
25
|
|
|
26
|
</Note> |
|
27
|
|
|
28
|
<Prerequisites items={[ |
|
29
|
{ |
|
30
|
text: "Stripe Module Provider installed and configured in your Medusa application.", |
|
31
|
link: "../../../../commerce-modules/payment/payment-provider/stripe/page.mdx" |
|
32
|
}, |
|
33
|
{ |
|
34
|
text: "Stripe publishable API key.", |
|
35
|
link: "https://support.stripe.com/questions/locate-api-keys-in-the-dashboard" |
|
36
|
}, |
|
37
|
{ |
|
38
|
text: "Cart context in your storefront, which is used in a code snippet later.", |
|
39
|
link: "/storefront-development/cart/context" |
|
40
|
}, |
|
41
|
]} /> |
|
42
|
|
|
43
|
## 1. Install Stripe SDK |
|
44
|
|
|
45
|
In your storefront, use the following command to install Stripe's JS and React SDKs: |
|
46
|
|
|
47
|
```bash npm2yarn |
|
48
|
npm install @stripe/react-stripe-js @stripe/stripe-js |
|
49
|
``` |
|
50
|
|
|
51
|
--- |
|
52
|
|
|
53
|
## 2. Add Stripe Environment Variables |
|
54
|
|
|
55
|
Next, add an environment variable holding your Stripe publishable API key. |
|
56
|
|
|
57
|
For example: |
|
58
|
|
|
59
|
```bash |
|
60
|
NEXT_PUBLIC_STRIPE_PK=pk_test_51Kj... |
|
61
|
``` |
|
62
|
|
|
63
|
<Note title="Tip"> |
|
64
|
|
|
65
|
For Next.js storefronts, the environment variable's name must be prefixed with `NEXT_PUBLIC`. If your storefront's framework requires a different prefix, make sure to change it. |
|
66
|
|
|
67
|
</Note> |
|
68
|
|
|
69
|
--- |
|
70
|
|
|
71
|
## 3. Create Stripe Component |
|
72
|
|
|
73
|
You can now create a Stripe component that renders the Stripe UI to accept payment. |
|
74
|
|
|
75
|
For example, you can create a file holding the following Stripe component: |
|
76
|
|
|
77
|
<Note title="Tip"> |
|
78
|
|
|
79
|
- This example uses the `useCart` hook defined in the [Cart React Context guide](../../../cart/context/page.mdx). |
|
80
|
- Learn how to install and configure the JS SDK in the [JS SDK documentation](../../../../js-sdk/page.mdx). |
|
81
|
|
|
82
|
</Note> |
|
83
|
|
|
84
|
export const highlights = [ |
|
85
|
["10", "useCart", "The `useCart` hook was defined in the Cart React Context documentation."], |
|
86
|
["14", "stripe", "Initialize stripe using the environment variable added in the previous step."], |
|
87
|
["20", "clientSecret", "After initializing the payment session of Stripe in the Medusa application,\nthe client secret is available in the payment session's `data`."], |
|
88
|
["34", "StripeForm", "The actual form must be a different component nested inside `Elements`."], |
|
89
|
["45", "handlePayment", "This function is used to show Stripe's UI to accept payment,\nthen send the request to the Medusa application to complete the cart."], |
|
90
|
["62", "confirmCardPayment", "This function shows the UI to the customer to accept the card payment."], |
|
91
|
["79", "then", "Once the customer enters their card details and submits the form,\nthe Promise resolves and executes this function."], |
|
92
|
["86", "complete", "Send a request to the Medusa application\nto complete the cart and place the order."], |
|
93
|
["88", `data.type === "cart"`, "If the `type` returned is `cart`,\nit means an error occurred and the cart wasn't completed."], |
|
94
|
["91", `data.type === "order"`, "If the `type` returned is `order`,\nit means the cart was completed and the order was placed successfully."], |
|
95
|
["95", "refreshCart", "Unset and reset the cart."], |
|
96
|
["105", "button", "This button triggers the `handlePayment` function when clicked."] |
|
97
|
] |
|
98
|
|
|
99
|
```tsx highlights={highlights} |
|
100
|
"use client" |
|
101
|
|
|
102
|
import { |
|
103
|
CardElement, |
|
104
|
Elements, |
|
105
|
useElements, |
|
106
|
useStripe, |
|
107
|
} from "@stripe/react-stripe-js" |
|
108
|
import { loadStripe } from "@stripe/stripe-js" |
|
109
|
import { useCart } from "@/providers/cart" |
|
110
|
import { useState } from "react" |
|
111
|
import { sdk } from "@/lib/sdk" |
|
112
|
|
|
113
|
const stripe = loadStripe( |
|
114
|
process.env.NEXT_PUBLIC_STRIPE_PK || "temp" |
|
115
|
) |
|
116
|
|
|
117
|
export default function StripePayment() { |
|
118
|
const { cart } = useCart() |
|
119
|
const clientSecret = cart?.payment_collection?. |
|
120
|
payment_sessions?.[0].data.client_secret as string |
|
121
|
|
|
122
|
return ( |
|
123
|
<div> |
|
124
|
<Elements stripe={stripe} options={{ |
|
125
|
clientSecret, |
|
126
|
}}> |
|
127
|
<StripeForm clientSecret={clientSecret} /> |
|
128
|
</Elements> |
|
129
|
</div> |
|
130
|
) |
|
131
|
} |
|
132
|
|
|
133
|
const StripeForm = ({ |
|
134
|
clientSecret, |
|
135
|
}: { |
|
136
|
clientSecret: string | undefined |
|
137
|
}) => { |
|
138
|
const { cart, refreshCart } = useCart() |
|
139
|
const [loading, setLoading] = useState(false) |
|
140
|
|
|
141
|
const stripe = useStripe() |
|
142
|
const elements = useElements() |
|
143
|
|
|
144
|
async function handlePayment( |
|
145
|
e: React.MouseEvent<HTMLButtonElement, MouseEvent> |
|
146
|
) { |
|
147
|
e.preventDefault() |
|
148
|
const card = elements?.getElement(CardElement) |
|
149
|
|
|
150
|
if ( |
|
151
|
!stripe || |
|
152
|
!elements || |
|
153
|
!card || |
|
154
|
!cart || |
|
155
|
!clientSecret |
|
156
|
) { |
|
157
|
return |
|
158
|
} |
|
159
|
|
|
160
|
setLoading(true) |
|
161
|
stripe?.confirmCardPayment(clientSecret, { |
|
162
|
payment_method: { |
|
163
|
card, |
|
164
|
billing_details: { |
|
165
|
name: cart.billing_address?.first_name, |
|
166
|
email: cart.email, |
|
167
|
phone: cart.billing_address?.phone, |
|
168
|
address: { |
|
169
|
city: cart.billing_address?.city, |
|
170
|
country: cart.billing_address?.country_code, |
|
171
|
line1: cart.billing_address?.address_1, |
|
172
|
line2: cart.billing_address?.address_2, |
|
173
|
postal_code: cart.billing_address?.postal_code, |
|
174
|
}, |
|
175
|
}, |
|
176
|
}, |
|
177
|
}) |
|
178
|
.then(({ error }) => { |
|
179
|
if (error) { |
|
180
|
// TODO handle errors |
|
181
|
console.error(error) |
|
182
|
return |
|
183
|
} |
|
184
|
|
|
185
|
sdk.store.cart.complete(cart.id) |
|
186
|
.then((data) => { |
|
187
|
if (data.type === "cart" && data.cart) { |
|
188
|
// an error occurred |
|
189
|
console.error(data.error) |
|
190
|
} else if (data.type === "order" && data.order) { |
|
191
|
// TODO redirect to order success page |
|
192
|
alert("Order placed.") |
|
193
|
console.log(data.order) |
|
194
|
refreshCart() |
|
195
|
} |
|
196
|
}) |
|
197
|
}) |
|
198
|
.finally(() => setLoading(false)) |
|
199
|
} |
|
200
|
|
|
201
|
return ( |
|
202
|
<form> |
|
203
|
<CardElement /> |
|
204
|
<button |
|
205
|
onClick={handlePayment} |
|
206
|
disabled={loading} |
|
207
|
> |
|
208
|
Place Order |
|
209
|
</button> |
|
210
|
</form> |
|
211
|
) |
|
212
|
} |
|
213
|
``` |
|
214
|
|
|
215
|
In the code snippet above, you: |
|
216
|
|
|
217
|
1. Create a `StripePayment` component that wraps the actual form with Stripe's `Elements` component. |
|
218
|
- In the `StripePayment` component, you obtain the client secret from the payment session's `data` field. This is set in the Medusa application after you initialize the payment session using the [Initialize Payment Sessions API route](!api!/store/payment-collections/initialize-payment-session). |
|
219
|
2. Create a `StripeForm` component that holds the actual form. In this component, you implement a `handlePayment` function that does the following: |
|
220
|
- Use Stripe's `confirmCardPayment` method to accept the card details from the customer. |
|
221
|
- Once the customer enters their card details and submit their order, the resolution function of the `confirmCardPayment` method is executed. |
|
222
|
- In the resolution function, you send a request to the [Complete Cart API route](!api!/store/carts/complete-cart) to complete the cart and place the order. |
|
223
|
- In the received response of the request, if the `type` is `cart`, it means that the cart completion failed. The error is set in the `error` response field. |
|
224
|
- If the `type` is `order`, it means the card was completed and the order was placed successfully. You can access the order in the `order` response field. |
|
225
|
- When the order is placed, you refresh the cart. You can redirect the customer to an order success page at this point. The redirection logic depends on the storefront framework you're using. |
|
226
|
|
|
227
|
--- |
|
228
|
|
|
229
|
## 4. Use the Stripe Component |
|
230
|
|
|
231
|
Finally, use the Stripe component in the checkout flow. You should render it after the customer chooses Stripe as a payment provider. |
|
232
|
|
|
233
|
For example, you can use it in the `getPaymentUi` function defined in the [Payment Checkout Step guide](../page.mdx): |
|
234
|
|
|
235
|
```tsx highlights={[["10"]]} |
|
236
|
const getPaymentUi = useCallback(() => { |
|
237
|
const activePaymentSession = cart?.payment_collection?. |
|
238
|
payment_sessions?.[0] |
|
239
|
if (!activePaymentSession) { |
|
240
|
return |
|
241
|
} |
|
242
|
|
|
243
|
switch(true) { |
|
244
|
case activePaymentSession.provider_id.startsWith("pp_stripe_"): |
|
245
|
return <StripePayment /> |
|
246
|
// ... |
|
247
|
} |
|
248
|
} , [cart]) |
|
249
|
``` |
|
250
|
|
|
251
|
--- |
|
252
|
|
|
253
|
## Troubleshooting |
|
254
|
|
|
255
|
### Unknown Error for Zero Cart Total |
|
256
|
|
|
257
|
If your cart has a total of `0`, you might encounter an `unknown error` when trying to create a payment session. |
|
258
|
|
|
259
|
Stripe requires a non-zero amount to create a payment session. So, if your cart has a total of `0`, the error will be thrown on Stripe's side. |
|
260
|
|
|
261
|
In those cases, you can either: |
|
262
|
|
|
263
|
- Make sure the payment session is only initialized when the cart has a total greater than `0`. |
|
264
|
- Use payment providers like the Manual System Payment Provider, which doesn't create a payment session with a third-party provider. |
|
265
|
- The Manual System Payment Provider is available by default in Medusa and can be used to handle payments without a third-party provider. It allows you to mark the order as paid without requiring any additional actions from the customer. |
|
266
|
- Make sure to configure the Manual System Payment Provider in your store's region. Learn more in the [Manage Region](!user-guide!/settings/regions#edit-region-details) user guide. |
|
267
|
|
|
268
|
--- |
|
269
|
|
|
270
|
## More Resources |
|
271
|
|
|
272
|
- [Stripe's documentation](https://docs.stripe.com/). |
|
273
|
- [Saved Payment Methods with Stripe](../../../../how-to-tutorials/tutorials/saved-payment-methods/page.mdx). |