docs: create docs workspace (#5174)

* docs: migrate ui docs to docs universe

* created yarn workspace

* added eslint and tsconfig configurations

* fix eslint configurations

* fixed eslint configurations

* shared tailwind configurations

* added shared ui package

* added more shared components

* migrating more components

* made details components shared

* move InlineCode component

* moved InputText

* moved Loading component

* Moved Modal component

* moved Select components

* Moved Tooltip component

* moved Search components

* moved ColorMode provider

* Moved Notification components and providers

* used icons package

* use UI colors in api-reference

* moved Navbar component

* used Navbar and Search in UI docs

* added Feedback to UI docs

* general enhancements

* fix color mode

* added copy colors file from ui-preset

* added features and enhancements to UI docs

* move Sidebar component and provider

* general fixes and preparations for deployment

* update docusaurus version

* adjusted versions

* fix output directory

* remove rootDirectory property

* fix yarn.lock

* moved code component

* added vale for all docs MD and MDX

* fix tests

* fix vale error

* fix deployment errors

* change ignore commands

* add output directory

* fix docs test

* general fixes

* content fixes

* fix announcement script

* added changeset

* fix vale checks

* added nofilter option

* fix vale error
This commit is contained in:
Shahed Nasser
2023-09-21 20:57:15 +03:00
committed by GitHub
parent 19c5d5ba36
commit fa7c94b4cc
3209 changed files with 32188 additions and 31018 deletions

View File

@@ -0,0 +1,7 @@
import DocCardList from '@theme/DocCardList';
# Payment Plugins
If you can't find your payment provider, try checking the [Community Plugins Library](https://medusajs.com/plugins/?filters=Payment&categories=Payment). You can also [create your own fulfillment provider](../../modules/carts-and-checkout/backend/add-payment-provider.md).
<DocCardList />

View File

@@ -0,0 +1,99 @@
---
description: 'Learn how to integrate Klarna as a payment provider with the Medusa backend. Learn how to install Klarna and enable the payment provider in a region.'
addHowToData: true
---
# Klarna
In this document, youll learn how to integrate Klarna as a payment provider in Medusa.
:::tip
Following the release of v1.8 of the core Medusa package, the naming of payment providers have changed to payment processors with the introduction of the Payment Processor API. However, plugins or implementation that still don't implement the Payment Processor API are still called payment providers.
:::
## Introduction
[Klarna](https://www.klarna.com/) is a payment provider that allows customers to pay in different ways including direct payment, installment payments, payment after delivery, and more.
You can integrate Klarna into Medusa using the [official plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-klarna).
---
## Prerequisites
### Medusa Components
It is assumed that you already have a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../development/backend/install.mdx).
In addition, youll need to use the [Medusa Admin](../../admin/quickstart.mdx) to enable the payment provider in later steps. You can alternatively use the [REST APIs](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders).
### Needed Accounts
- A [Klarna business account](https://portal.klarna.com/)
---
## Install Plugin
On your Medusa backend, run the following command to install the plugin:
```bash
npm install medusa-payment-klarna
```
Then, add the following environment variables:
```bash
KLARNA_BACKEND_URL=<YOUR_KLARNA_BACKEND_URL>
KLARNA_URL=<YOUR_KLARNA_URL>
KLARNA_USER=<YOUR_KLARNA_USER>
KLARNA_PASSWORD=<YOUR_KLARNA_PASSWORD>
KLARNA_TERMS_URL=<YOUR_KLARNA_TERMS_URL>
KLARNA_CHECKOUT_URL=<YOUR_KLARNA_CHECKOUT_URL>
KLARNA_CONFIRMATION_URL=<YOUR_KLARNA_CONFIRMATION_URL>
```
Where:
- `<YOUR_KLARNA_BACKEND_URL>` is your Klarna URL.
- `<YOUR_KLARNA_URL>` is the [base Klarna URL based on your environment](https://docs.klarna.com/api/api-urls/).
- `<YOUR_KLARNA_USER>` and `<YOUR_KLARNA_PASSWORD>` are your [API credentials](https://docs.klarna.com/api/authentication/).
- `<YOUR_KLARNA_TERMS_URL>`, `<YOUR_KLARNA_CHECKOUT_URL>`, and `<YOUR_KLARNA_CONFIRMATION_URL>` are the terms, checkout, and confirmation URL of your Klarna account.
Finally, in `medusa-config.js`, add the Klarna plugin to the `plugins` array with the necessary configurations:
```jsx title=medusa-config.js
const plugins = [
// other plugins...
{
resolve: `medusa-payment-klarna`,
options: {
backend_url: process.env.KLARNA_BACKEND_URL,
url: process.env.KLARNA_URL,
user: process.env.KLARNA_USER,
password: process.env.KLARNA_PASSWORD,
merchant_urls: {
terms: process.env.KLARNA_TERMS_URL,
checkout: process.env.KLARNA_CHECKOUT_URL,
confirmation: process.env.KLARNA_CONFIRMATION_URL,
},
},
},
]
```
---
## Enable Klarna in Regions
To use Klarna in your store, you must enable it in at least one region.
You can follow [this user guide to learn how to enable a payment provider in a region](../../user-guide/regions/providers#manage-payment-providers). You can alternatively use the [REST APIs](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders).
---
## See Also
- Check out [more plugins](../overview.mdx) you can add to your store.

View File

@@ -0,0 +1,284 @@
---
description: 'Learn how to integrate PayPal with the Medusa backend. Learn how to install the PayPal plugin on the Medusa backend and integrate into a storefront.'
addHowToData: true
---
# PayPal
This document guides you through setting up PayPal as a payment processor in your Medusa backend, admin, and storefront using the [PayPal plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-paypal).
## Overview
[PayPal](https://www.paypal.com) is a payment processor used by millions around the world. It allows customers to purchase orders from your website using their PayPal account rather than the need to enter their card details.
As a developer, you can use PayPals SDKs and APIs to integrate PayPal as a payment method into your ecommerce store. You can test out the payment method in sandbox mode before going live with it as a payment method.
Using the `medusa-payment-paypal` plugin, this guide shows you how to set up your Medusa backend with PayPal as a payment processor.
---
## Prerequisites
Before you proceed with this guide, make sure you create a [PayPal account](https://www.paypal.com). You also need a PayPal Developer account and retrieve the Client ID and Client Secret. You can learn more about how to do that in [PayPals documentation](https://developer.paypal.com/api/rest/).
In addition, you need to configure a webhook listener on your PayPal Developer Dashboard and obtain the webhook ID. This is necessary for Webhooks to work.
Webhooks are used in scenarios where the customer might leave the page during the authorization and before the checkout flow is fully complete. It will then create the order or swap after the payment is authorized if they werent created.
The endpoint for PayPal webhook integration with your Medusa backend should be set to `{BACKEND_URL}/paypal/hooks`. Make sure to replace `{BACKEND_URL}` with the URL to your backend.
Additionally, you need a Medusa backend installed and set up. If not, you can follow the [quickstart guide](../../development/backend/install.mdx) to get started.
You also need [Medusa Admin](../../admin/quickstart.mdx) installed to enable PayPal as a payment processor. You can alternatively use the [REST APIs](https://docs.medusajs.com/api/admin).
---
## Medusa Backend
### Install the PayPal Plugin
In the root of your Medusa backend, run the following command to install the PayPal plugin:
```bash npm2yarn
npm install medusa-payment-paypal
```
### Configure the PayPal Plugin
Next, you need to add configurations for your PayPal plugin.
In the `.env` file add the following new environment variables:
```bash
PAYPAL_SANDBOX=true
PAYPAL_CLIENT_ID=<CLIENT_ID>
PAYPAL_CLIENT_SECRET=<CLIENT_SECRET>
PAYPAL_AUTH_WEBHOOK_ID=<WEBHOOK_ID>
```
Where `<CLIENT_ID>`, `<CLIENT_SECRET>`, and `<WEBHOOK_ID>` are the keys you retrieved from the PayPal Developer dashboard as explained in the [Prerequisites](#prerequisites) section.
Notice that during development its highly recommended to set `PAYPAL_SANDBOX` to `true` and ensure you have [sandbox accounts set up in PayPal](https://developer.paypal.com/api/rest/sandbox/).
Then, in `medusa-config.js`, add the PayPal plugin to the `plugins` array with the configurations necessary:
```jsx title=medusa-config.js
const plugins = [
// other plugins...
{
resolve: `medusa-payment-paypal`,
options: {
sandbox: process.env.PAYPAL_SANDBOX,
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
authWebhookId: process.env.PAYPAL_AUTH_WEBHOOK_ID,
},
},
]
```
Thats all you need to install PayPal on your Medusa backend!
The PayPal plugin also accepts the following optional configurations:
- `capture`: : a boolean value that indicates whether payment should be captured manually or automatically. By default, it will be false, leading admins to capture the payment manually.
---
## Admin Setup
This section will guide you through adding PayPal as a payment processor in a region using your Medusa admin dashboard.
This step is required for you to be able to use PayPal as a payment processor in your storefront.
### Admin Prerequisites
If you dont have a Medusa admin installed, make sure to follow along with [the guide on how to install it](../../admin/quickstart.mdx) before continuing with this section.
### Add PayPal to Regions
You can refer to [this documentation in the user guide](../../user-guide/regions/providers.mdx#manage-payment-providers) to learn how to add a payment processor like PayPal to a region.
---
## Storefront Setup
This section will take you through the steps to add PayPal as a payment method on the storefront. It includes the steps necessary when using one of Medusas official storefronts as well as your own custom React-based storefront.
### Storefront Prerequisites
All storefronts require that you obtain your PayPal Client ID. You can retrieve it from your PayPal developer dashboard.
### Process Overview
Aside from the Next.js Starter Template, you need to add the implementation with PayPal manually.
:::note
It is recommended to read through the [Frontend Checkout Flow](../../modules/carts-and-checkout/storefront/implement-checkout-flow.mdx) first to fully understand how payment is implemented on the storefront.
:::
Although the next sections have different implementations to add PayPal into your storefront, they essentially follow the same process:
1. Show PayPals button if the PayPal processor is available for the current cart.
2. When the button is clicked, open PayPals payment portal and wait for the customer to authorize the payment.
3. If the payment is authorized successfully, set PayPals [Payment Session](../../modules/carts-and-checkout/payment.md#payment-session) as the session used to perform the payment for the current cart, then update the Payment Session on the backend with the data received from PayPals payment portal. This data is essential to the backend to verify the authorization and perform additional payment processing later such as capturing payment.
4. Complete the cart to create the order.
:::info
In Medusa, by default, payments are authorized during checkout, but the payment is not captured right away. The payment should be manually [captured from the Medusa Admin](#capture-payment).
:::
### Add to Next.js Starter Template
Medusa has a Next.js Starter Template that you can easily use with your Medusa backend. If you dont have the storefront installed, you can follow [this quickstart guide](../../starters/nextjs-medusa-starter.mdx).
In your `.env.local` file (or the file youre using for your environment variables), add the following variable:
```bash title=.env.local
NEXT_PUBLIC_PAYPAL_CLIENT_ID=<YOUR_CLIENT_ID>
```
Make sure to replace `<YOUR_CLIENT_ID>` with your PayPal Client ID.
Now, if you run your Medusa backend and your storefront, on checkout youll be able to use PayPal].
![PayPal Button](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000463/Medusa%20Docs/PayPal/F8OvsOJ_v3ctol.png)
You can test out the payment with PayPal using your sandbox account.
### Add to Custom Storefront
This section guides you to add PayPal into a React-based framework. The instructions are general instructions that you can use in your storefront.
In your storefront, you need to install the [PayPal React components library](https://www.npmjs.com/package/@paypal/react-paypal-js) and the [Medusa JS Client library](https://www.npmjs.com/package/@medusajs/medusa-js):
```bash npm2yarn
npm install @paypal/react-paypal-js @medusajs/medusa-js
```
Then, add the Client ID as an environment variable based on the framework youre using.
Next, create the file that will hold the PayPal component with the following content:
```jsx
import {
PayPalButtons,
PayPalScriptProcessor,
} from "@paypal/react-paypal-js"
import { useEffect, useState } from "react"
import Medusa from "@medusajs/medusa-js"
function Paypal() {
const client = new Medusa()
const [errorMessage, setErrorMessage] = useState(undefined)
const [processing, setProcessing] = useState(false)
const cart = "..." // TODO retrieve the cart here
const handlePayment = (data, actions) => {
actions.order.authorize().then(async (authorization) => {
if (authorization.status !== "COMPLETED") {
setErrorMessage(
`An error occurred, status: ${authorization.status}`
)
setProcessing(false)
return
}
const response = await client
.carts
.setPaymentSession(cart.id, {
"processor_id": "paypal",
})
if (!response.cart) {
setProcessing(false)
return
}
await client
.carts
.updatePaymentSession(cart.id, "paypal", {
data: {
data: {
...authorization,
},
},
})
const { data } = await client.carts.complete(cart.id)
if (!data || data.object !== "order") {
setProcessing(false)
return
}
// order successful
alert("success")
})
}
return (
<div style={{ marginTop: "10px", marginLeft: "10px" }}>
{cart !== undefined && (
<PayPalScriptProcessor options={{
"client-id": "<CLIENT_ID>",
"currency": "EUR",
"intent": "authorize",
}}>
{errorMessage && (
<span className="text-rose-500 mt-4">
{errorMessage}
</span>
)}
<PayPalButtons
style={{ layout: "horizontal" }}
onApprove={handlePayment}
disabled={processing}
/>
</PayPalScriptProcessor>
)}
</div>
)
}
export default Paypal
```
Heres briefly what this code snippet does:
1. At the beginning of the component, the Medusa client is initialized using the JS Client you installed.
2. You also need to retrieve the cart. Ideally, the cart should be managed through a context. So, every time the cart has been updated the cart should be updated in the context to be accessed from all components.
3. This component renders a PayPal button to initialize the payment using PayPal. You use the components from the PayPal React components library to render the button and you pass the `PayPalScriptProcessor` component the Client ID. Make sure to replace `<CLIENT_ID>` with the environment variable you added.
4. When the button is clicked, the `handlePayment` function is executed. In this method, you initialize the payment authorization using `actions.order.authorize()`. It takes the customer to another page to log in with PayPal and authorize the payment.
5. After the payment is authorized successfully on PayPals portal, the fulfillment function passed to `actions.order.authorize().then` will be executed.
6. In the fulfillment function, you first ensure that the payment session for the PayPal payment processor is set as the [selected Payment Session in the cart](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession). Then, you send a request to the backend to [update the payment session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate) data with the authorization data received from PayPal.
7. You then [complete the cart and place the order](https://docs.medusajs.com/api/store#carts_postcartscartcomplete). If that is done successfully, you just show a success alert. You can change this based on the behavior you want in your storefront.
You can then import this component where you want to show it in your storefront.
If you run the Medusa backend and the storefront backend, you should see the PayPal button on checkout.
![PayPal Button](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000492/Medusa%20Docs/PayPal/PsibgPY_xtqdli.png)
---
## Capture Payments
After the customer places an order, you can see the order on the admin panel. In the payment information under the “Payment” section, you should see a “Capture” button.
![Capture Payment](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000502/Medusa%20Docs/PayPal/Mx357yY_xsandw.png)
Clicking this button lets you capture the payment for an order. You can also refund payments if an order has captured payments.
Refunding or Capturing payments is reflected in your PayPal dashboard as well.
---
## See Also
- Check out [more plugins](../overview.mdx) you can add to your store.

View File

@@ -0,0 +1,400 @@
---
description: 'Learn how to integrate Stripe with the Medusa backend. Learn how to install the Stripe plugin on the Medusa backend and integrate it into a storefront.'
addHowToData: true
---
import Troubleshooting from '@site/src/components/Troubleshooting'
import MissingPaymentProvider from '../../troubleshooting/missing-payment-providers.md'
# Stripe
This document guides you through setting up Stripe payments in your Medusa backend, admin, and storefront using the [Stripe Plugin](https://github.com/medusajs/medusa/tree/master/packages/medusa-payment-stripe).
## Video Guide
You can also follow this video guide to learn how the setup works:
<div>
<video width="100%" height="100%" playsinline autoplay muted controls>
<source src="https://user-images.githubusercontent.com/59018053/154807206-6fbda0a6-bf3e-4e39-9fc2-f11710afe0b9.mp4" type="video/mp4" />
</video>
</div>
## Overview
[Stripe](https://stripe.com/) is a battle-tested and unified platform for transaction handling. Stripe supplies you with the technical components needed to handle transactions safely and all the analytical features necessary to gain insight into your sales. These features are also available in a safe test environment which allows for a concern-free development process.
Using the `medusa-payment-stripe` plugin, this guide shows you how to set up your Medusa project with Stripe as a payment processor.
---
## Prerequisites
Before you proceed with this guide, make sure you create a [Stripe account](https://stripe.com). Youll later retrieve the API Keys and secrets from your account to connect Medusa to your Stripe account.
---
## Medusa Backend
This section guides you over the steps necessary to add Stripe as a payment processor to your Medusa backend.
If you dont have a Medusa backend installed yet, you must follow the [quickstart guide](../../development/backend/install.mdx) first.
### Install the Stripe Plugin
In the root of your Medusa backend, run the following command to install the stripe plugin:
```bash npm2yarn
npm install medusa-payment-stripe
```
### Configure the Stripe Plugin
Next, you need to add configurations for your stripe plugin.
In `medusa-config.js` add the following at the end of the `plugins` array:
```jsx title=medusa-config.js
const plugins = [
// ...
{
resolve: `medusa-payment-stripe`,
options: {
api_key: process.env.STRIPE_API_KEY,
webhook_secret: process.env.STRIPE_WEBHOOK_SECRET,
},
},
]
```
The Stripe plugin uses two configuration options. The `api_key` is essential to both your development and production environments. As for the `webhook_secret`, its essential for your production environment. So, if youre only using Stripe for development you can skip adding the value for this option at the moment.
:::note
You can learn more about the events that the plugin monitors in [this section](#handled-webhook-events).
:::
Other optional options include:
- `payment_description`: a string that is used as the default description of a payment if none is provided.
- `capture`: a boolean value that indicates whether payment should be captured manually or automatically. By default, it will be `false`, leading admins to capture the payment manually.
- `automatic_payment_methods`: a boolean value that enables Stripe's automatic payment methods. This is useful if you're integrating services like Apple pay or Google pay.
### Retrieve Stripe's Keys
On the [dashboard](https://dashboard.stripe.com) of your Stripe account click on the Developers link at the top right. This will take you to the developer dashboard.
Youll first retrieve the API key. You can find it by choosing API Keys from the sidebar and copying the Secret key.
Next, you need to add the key to your environment variables. In your Medusa backend, create `.env` if it doesnt already exist and add the Stripe key:
```bash
STRIPE_API_KEY=sk_...
```
:::note
If you store environment variables differently on your backend, for example, using the hosting processors UI, then you dont need to add it in `.env`. Add the environment variables in a way relevant to your backend.
:::
Next, if youre installing this plugin for production use, you need to retrieve the Webhook secret. Webhooks allows you to track different events on your Medusa backend, such as failed payments.
Go to Webhooks on Stripes developer dashboard. Then, choose the Add an Endpoint button.
The endpoint for Stripes webhook on your Medusa backend is `{BACKEND_URL}/stripe/hooks`. So, add that endpoint in its field. Make sure to replace `{BACKEND_URL}` with the URL to your backend.
Then, you can add a description. You must select at least one event to listen to. Once youre done, click “Add endpoint”.
After the Webhook is created, youll see "Signing secret" in the Webhook details. Click on "Reveal" to reveal the secret key. Copy that key and in your Medusa backend add the Webhook secret environment variable:
```bash
STRIPE_WEBHOOK_SECRET=whsec_...
```
---
## Admin Setup
This section will guide you through adding Stripe as a payment processor in a region using your Medusa admin dashboard.
This step is required for you to be able to use Stripe as a payment processor in your storefront.
### Admin Prerequisites
If you dont have a Medusa admin installed, make sure to follow along with [the guide on how to install it](https://github.com/medusajs/admin#-quickstart) before continuing with this section.
### Add Stripe to Regions
You can refer to [this documentation in the user guide](../../user-guide/regions/providers.mdx#manage-payment-providers) to learn how to add a payment processor like Stripe to a region.
---
## Storefront Setup
This guide will take you through how to set up Stripe payments in your Medusa storefront. It includes the steps necessary when using one of Medusas official storefronts as well as your own custom React-based storefront.
### Storefront Prerequisites
All storefronts require that you obtain your Stripes Publishable Key. You can retrieve it from your Stripes developer dashboard by choosing API Keys and then copying the Publishable Key.
### Add to Next.js Starter Template
Medusa has a Next.js Starter Template that you can easily use with your Medusa backend. If you dont have the storefront installed, you can follow [this quickstart guide](../../starters/nextjs-medusa-starter).
In your `.env.local` file (or the file youre using for your environment variables), add the following variable:
```bash title=.env.local
NEXT_PUBLIC_STRIPE_KEY=<YOUR_PUBLISHABLE_KEY>
```
Make sure to replace `<YOUR_PUBLISHABLE_KEY>` with your Stripe Publishable Key.
Now, if you run your Medusa backend and your storefront, on checkout youll be able to use Stripe.
![Next.js Stripe Form](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001145/Medusa%20Docs/Stripe/h5mWdJT_n1bktt.png)
### Add to Custom Storefront
This section will go over how to add Stripe into a React-based framework. The instructions are general instructions that you can use in your storefront.
#### Workflow Overview
The integration with stripe must have the following workflow:
1. During checkout when the user reaches the payment section, you should [create payment sessions](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessions). This will initialize the `payment_sessions` array in the `cart` object received. The `payment_sessions` is an array of available payment processors.
2. If Stripe is available as a payment processor, you should select Stripe as [the payment session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession) for the current cart. This will initialize the `payment_session` object in the `cart` object to include data related to Stripe and the current payment session. This includes the payment intent and client secret.
3. After the user enters their card details and submits the form, confirm the payment with Stripe.
4. If the payment is confirmed successfully, [complete the cart](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) in Medusa. Otherwise show an error.
#### Install Dependencies
Before you start the implementations you need to install the necessary dependencies. Youll be using Stripes React libraries to show the UI and handle the payment confirmation:
```bash npm2yarn
npm install --save @stripe/react-stripe-js @stripe/stripe-js
```
Youll also use Medusas JS Client to easily call Medusas REST APIs:
```bash npm2yarn
npm install @medusajs/medusa-js
```
#### Initialize Stripe
In this section, youll initialize Stripe without Medusas checkout workflow. Please note that this is one approach to add Stripe into your React project. You can check out [Stripes React documentation](https://stripe.com/docs/stripe-js/react) for other methods or components.
Create a container component that will hold the payment card component:
```jsx
import { useState } from "react"
import { Elements } from "@stripe/react-stripe-js"
import Form from "./Form"
import { loadStripe } from "@stripe/stripe-js"
const stripePromise = loadStripe("pk_...")
export default function Container() {
const [clientSecret, setClientSecret] = useState()
// TODO set clientSecret
return (
<div>
{clientSecret && (
<Elements stripe={stripePromise} options={{
clientSecret,
}}>
<Form clientSecret={clientSecret} cartId={cartId} />
</Elements>
)}
</div>
)
};
```
In this component, you need to use Stripes `loadStripe` function outside of the components implementation to ensure that Stripe doesnt re-load with every change. The function accepts the Publishable Key.
:::note
Youll probably store this Publishable Key in an environment variable depending on your framework. Its hard-coded here for simplicity.
:::
Then, inside the components implementation, you add a state variable `clientSecret` which youll retrieve in the next section.
Once the clientSecret is set, the `Elements` Stripe component will wrap a `Form` component youll create next. This is necessary because the `Elements` component allows child elements to get access to the cards inputs and their data using Stripes `useElements` hook.
Create a new file for the `Form` component with the following content:
```jsx
import {
CardElement,
useElements,
useStripe,
} from "@stripe/react-stripe-js"
export default function Form({ clientSecret, cartId }) {
const stripe = useStripe()
const elements = useElements()
async function handlePayment(e) {
e.preventDefault()
// TODO handle payment
}
return (
<form>
<CardElement />
<button onClick={handlePayment}>Submit</button>
</form>
)
};
```
This component shows a CardElement component from Stripes React library. You can use `stripe` to be able to confirm the payment later. The `elements` variable will be used to retrieve the entered card details safely.
#### Implement the Workflow
Youll now implement the workflow explained earlier. Youll use Medusas JS Client, so make sure to import it and initialize it in your `Container` component:
```jsx
import Medusa from "@medusajs/medusa-js"
export default function Container() {
const client = new Medusa()
// ...
}
```
:::note
In your storefront, youll probably be managing the Medusa client through a context for better performance.
:::
Then, in the place of the `//TODO` inside the `Container` element, initialize the payment sessions and create a payment session if Stripe is available:
```tsx
client.carts.createPaymentSessions(cart.id)
.then(({ cart }) => {
// check if stripe is selected
const isStripeAvailable = cart.payment_sessions?.some(
(session) => (
session.processor_id === "stripe"
)
)
if (!isStripeAvailable) {
return
}
// select stripe payment session
client.carts.setPaymentSession(cart.id, {
processor_id: "stripe",
}).then(({ cart }) => {
setClientSecret(cart.payment_session.data.client_secret)
})
})
```
:::note
Notice that here its assumed you have access to the `cart` object throughout your storefront. Ideally, the `cart` should be managed through a context. So, every time the cart is updated, for example, when the `createPaymentSessions` or `setPaymentSession` are called, the cart should be updated in the context to be accessed from other elements. In this case, you probably wouldnt need a `clientSecret` state variable as you can use the client secret directly from the `cart` object.
:::
Once the client secret is set, the form will be shown to the user.
The last step in the workflow is confirming the payment with Stripe and if its done successfully, completing the users order. This part is done in the `Form` component.
As youll use Medusas client again make sure to import it and initialize it:
```jsx
import Medusa from "@medusajs/medusa-js"
export default function Form() {
const client = new Medusa()
// ...
}
```
Then, replace the `//TODO` in the `handlePayment` function with the following content:
```jsx
return stripe.confirmCardPayment(clientSecret, {
payment_method: {
card: elements.getElement(CardElement),
billing_details: {
name,
email,
phone,
address: {
city,
country,
line1,
line2,
postal_code,
},
},
},
}).then(({ error, paymentIntent }) => {
// TODO handle errors
client.carts.complete(cartId).then(
(resp) => console.log(resp)
)
})
```
You use the `confirmCardPayment` method in the `stripe` object. Youll need to pass it the client secret, which you can have access to from the cart object if its available through the context.
This method also requires the customers information like `name`, `email`, and their address. Make sure to place the values for each based on your implementation.
Once the promise resolves you can handle the errors, if there are any. If not, you can complete the customers order using `complete` from Medusas client. This request expects the cart ID which you should have access to as well.
If you run your backend and storefront now, youll see the Stripe UI element and youll be able to make orders.
![Stripe Form](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001190/Medusa%20Docs/Stripe/NOi8THw_xv3zsx.png)
---
## Capture Payments
After the customer places an order, youll be able to see the order on the admin panel. In the payment information under the “Payment” section, you should see a “Capture” button.
![Capture Payment](https://res.cloudinary.com/dza7lstvk/image/upload/v1668001205/Medusa%20Docs/Stripe/Iz55PVZ_p6hiz6.png)
Clicking this button allows you to capture the payment for an order. You can also refund payments if an order has captured payments.
Refunding or Capturing payments is reflected in your Stripes dashboard as well. This gives you access to all of Stripes analytical capabilities.
---
## Handled Webhook Events
This plugin handles the following Stripe webhook events:
- `payment_intent.succeeded`: If the payment is associated with a payment collection, the plugin will capture the payments within it. Otherwise, it checks first if an order is created and, if not, completes the cart which creates the order. It will also capture the payment of the order associated with the cart if it's not captured already.
- `payment_intent.amount_capturable_updated`: If no order is created for the cart associated with the payment, the cart is completed which creates the order.
- `payment_intent.payment_failed`: prints the error message received from Stripe into the logs.
---
## Troubleshooting
<Troubleshooting
sections={[
{
title: 'Stripe not showing in checkout',
content: <MissingPaymentProvider />
}
]}
/>
---
## See Also
- Check out [more plugins](../overview.mdx) you can add to your store.