chore: reorganize docs apps (#7228)

* reorganize docs apps

* add README

* fix directory

* add condition for old docs
This commit is contained in:
Shahed Nasser
2024-05-03 17:36:38 +03:00
committed by GitHub
parent 224ebb2154
commit 4fe28f5a95
6187 changed files with 601447 additions and 598226 deletions
@@ -0,0 +1,271 @@
import { Table } from "docs-ui"
export const metadata = {
title: `Klarna Plugin`,
}
# {metadata.title}
## Features
[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.
---
## Install the Klarna Plugin
<Note type="check">
- [Klarna business account](https://slack.com)
</Note>
To install the Klarna plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-payment-klarna
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "backend_url", "The Klarna URL."],
["7", "url", "The base Klarna URL based on your environment."],
["8", "user", "The Klarna Merchant ID (MID)."],
["9", "password", "The string associated with the Klarna Merchant ID (MID) used for authorization."],
["10", "merchant_urls", "The merchant URLs to use for orders."],
["15", "payment_collection_urls", "The merchant URLs to use for payment collections."],
]
```js title="medusa-config.js" highlights={highlights}
const 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_MERCHANT_TERMS_URL,
checkout: process.env.KLARNA_MERCHANT_CHECKOUT_URL,
confirmation: process.env.KLARNA_MERCHANT_CONFIRMATION_URL,
},
payment_collection_urls: {
terms: process.env.KLARNA_PAYCOL_TERMS_URL,
checkout: process.env.KLARNA_PAYCOL_CHECKOUT_URL,
confirmation: process.env.KLARNA_PAYCOL_CONFIRMATION_URL,
},
},
},
]
```
### Klarna Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell>Required</Table.HeaderCell>
<Table.HeaderCell>Default</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`backend_url`
</Table.Cell>
<Table.Cell>
A string indicating the Klarna URL.
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`url`
</Table.Cell>
<Table.Cell>
A string indicating the [base Klarna URL based on your environment](https://docs.klarna.com/api/api-urls/).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`user`
</Table.Cell>
<Table.Cell>
The [Klarna Merchant ID (MID)](https://www.klarna.com/us/business/merchant-support/what-is-a-merchant-id/).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`password`
</Table.Cell>
<Table.Cell>
The string associated with the Klarna Merchant ID (MID) used for [API authorization](https://docs.klarna.com/api/authentication/).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`merchant_urls`
</Table.Cell>
<Table.Cell>
An object of merchant URLs passed to [Klarna's APIs](https://docs.klarna.com/api/payments/#operation/createCreditSession) for orders. It accepts the following keys:
- `terms`: The terms URL.
- `checkout`: The checkout URL.
- `confirmation`: The confirmation URL.
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`payment_collection_urls`
</Table.Cell>
<Table.Cell>
An object of merchant URLs passed to [Klarna's APIs](https://docs.klarna.com/api/payments/#operation/createCreditSession) for payment collections. It accepts the following keys:
- `terms`: The terms URL.
- `checkout`: The checkout URL.
- `confirmation`: The confirmation URL.
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`language`
</Table.Cell>
<Table.Cell>
A string indicating [Klarna's locale](https://docs.klarna.com/klarna-payments/in-depth-knowledge/puchase-countries-currencies-locales/#data-mapping).
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`en-US`
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
KLARNA_BACKEND_URL=<YOUR_KLARNA_BACKEND_URL>
KLARNA_URL=<YOUR_KLARNA_URL>
KLARNA_USER=<YOUR_KLARNA_USER>
KLARNA_PASSWORD=<YOUR_KLARNA_PASSWORD>
KLARNA_MERCHANT_TERMS_URL=<YOUR_KLARNA_MERCHANT_TERMS_URL>
KLARNA_MERCHANT_CHECKOUT_URL=<YOUR_KLARNA_MERCHANT_CHECKOUT_URL>
KLARNA_MERCHANT_CONFIRMATION_URL=<YOUR_KLARNA_MERCHANT_CONFIRMATION_URL>
KLARNA_PAYCOL_TERMS_URL=<YOUR_KLARNA_PAYCOL_TERMS_URL>
KLARNA_PAYCOL_CHECKOUT_URL=<YOUR_KLARNA_PAYCOL_CHECKOUT_URL>
KLARNA_PAYCOL_CONFIRMATION_URL=<YOUR_KLARNA_PAYCOL_CONFIRMATION_URL>
```
---
## Test the Plugin
To test the plugin, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, you must enable the Klarna Payment Provider in at least one region to use it. You can do that using either the [Medusa Admin](!user-guide!/settings/regions/providers), or the [Admin API Routes](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders).
Finally, try to place an order using either a [storefront](../../../nextjs-starter/page.mdx) or the [Store API Routes](https://docs.medusajs.com/api/store). You can use Klarna during checkout and to process the order's payment.
@@ -0,0 +1,354 @@
import { Table } from "docs-ui"
export const metadata = {
title: `PayPal Plugin`,
}
# {metadata.title}
## Features
[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.
---
## Install the PayPal Plugin
<Note type="check">
- [PayPal account](https://www.paypal.com).
- [PayPal developer account](https://developer.paypal.com).
- [PayPal client ID and secret](https://developer.paypal.com/api/rest/).
- For deployed Medusa applications, a [PayPal webhook ID](https://developer.paypal.com/api/rest/webhooks/rest/). When creating the Webhook, set the value to `{medusa_url}/paypal/hooks`, where `{medusa_url}` with the URL to your deployed Medusa application.
</Note>
To install the PayPal plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-payment-paypal
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "clientId", "The PayPal client ID."],
["7", "clientSecret", "The PayPal client secret."],
["8", "sandbox", "Whether to use sandbox mode."],
]
```js title="medusa-config.js" highlights={highlights}
const plugins = [
// ...
{
resolve: `medusa-payment-paypal`,
options: {
clientId: process.env.PAYPAL_CLIENT_ID,
clientSecret: process.env.PAYPAL_CLIENT_SECRET,
sandbox: process.env.PAYPAL_SANDBOX,
},
},
]
```
### Klarna Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell>Required</Table.HeaderCell>
<Table.HeaderCell>Default</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`clientId`
</Table.Cell>
<Table.Cell>
A string indicating the [PayPal client ID](https://developer.paypal.com/api/rest/).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`clientSecret`
</Table.Cell>
<Table.Cell>
A string indicating the [PayPal client secret](https://developer.paypal.com/api/rest/).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`sandbox`
</Table.Cell>
<Table.Cell>
A boolean indicating whether to use sandbox mode. Enabling this is useful for testing.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`false`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`authWebhookId`
</Table.Cell>
<Table.Cell>
A string indicating the PayPal webhook ID. This is only useful for deployed Medusa applications.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`capture`
</Table.Cell>
<Table.Cell>
A boolean indicating whether to automatically capture payments when an order is placed.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`false`. Payments are authorized when an order is placed and the admin user captures the payment manually.
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
PAYPAL_SANDBOX=true
PAYPAL_CLIENT_ID=<CLIENT_ID>
PAYPAL_CLIENT_SECRET=<CLIENT_SECRET>
```
---
## Test the PayPal Plugin
To test the plugin, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, you must enable the PayPal Payment Provider in at least one region to use it. You can do that using either the [Medusa Admin](!user-guide!/settings/regions/providers), or the [Admin API Routes](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders).
Finally, try to place an order using either a [storefront](../../../nextjs-starter/page.mdx) or the [Store API Routes](https://docs.medusajs.com/api/store). You can use PayPal during checkout and to process the order's payment.
---
## Storefront Setup
This section provides an example of how to add PayPal as a payment method in custom storefronts. For the Next.js storefront, refer to [this guide](../../../nextjs-starter/page.mdx#paypal-integration)
### Integration Steps Overview
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 Sessionas 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.
### Add to Custom Storefront
<Note>
This example assumes your storefront uses React. If not, the steps generally clarify how to implement it in your storefront.
</Note>
In your storefront, 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 holds the PayPal component with the following content:
export const storefrontHighlights = [
["10", "", "Initialize the Medusa JS Client."],
["16", "", "Retrieve the cart."],
["18", "handlePayment", "Initialize the payment authorization using `actions.order.authorize()` and takes the customer to authorize the payment with PayPal in another page."],
["28", "setPaymentSession", "Select the PayPal provider's payment session for the cart."],
["40", "updatePaymentSession", "Update the payment session's data with the authorization data from PayPal."],
["52", "complete", "Complete the cart and place the order."],
["71", `"<CLIENT_ID>"`, "The PayPal client ID."],
["81", "PayPalButtons", "Render a PayPal button that, when clicked, initializes the payment using PayPal."]
]
```tsx highlights={storefrontHighlights}
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({
baseUrl: "http://localhost:9000",
maxRetries: 3,
})
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,
{
provider_id: "paypal",
}
)
if (!response.cart) {
setProcessing(false)
return
}
await client.carts.updatePaymentSession(
cart.id,
"paypal",
{
data: {
data: {
...authorization,
},
},
}
)
const { data, type } = await client.carts.complete(
cart.id
)
if (!data || type !== "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
```
A brief overview of what this component does:
1. You initialize the Medusa JS Client.
2. You 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. You render a PayPal button that, when clicked, initializes 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` is executed.
6. In the fulfillment function, you select the PayPal provider's [payment session in the cart](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession). Then, you [update the payment session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessionupdate)'s data in the Medusa application with the authorization data received from PayPal.
7. You [complete the cart and place the order](https://docs.medusajs.com/api/store#carts_postcartscartcomplete). If successful, you just show a success alert.
You can then import this component where you want to show it in your storefront.
If you run the Medusa application and the storefront, you can use the PayPal button during checkout.
@@ -0,0 +1,447 @@
import { Table } from "docs-ui"
export const metadata = {
title: `Stripe Plugin`,
}
# {metadata.title}
## Features
[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.
---
## Install the PayPal Plugin
<Note type="check">
- [Stripe account](https://stripe.com).
- [Stripe API Key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard)
- For deployed Medusa applications, a [Stripe webhook secret](https://docs.stripe.com/webhooks#add-a-webhook-endpoint). When creating the Webhook, set the endpoint URL to `{medusa_url}/stripe/hooks`, where `{medusa_url}` with the URL to your deployed Medusa application.
</Note>
To install the Stripe plugin, run the following command in the directory of your Medusa application:
```bash npm2yarn
npm install medusa-payment-stripe
```
Next, add the plugin into the `plugins` array in `medusa-config.js`:
export const highlights = [
["6", "api_key", "The Stripe API key."],
]
```js title="medusa-config.js" highlights={highlights}
const plugins = [
// ...
{
resolve: `medusa-payment-stripe`,
options: {
api_key: process.env.STRIPE_API_KEY,
},
},
]
```
### Stripe Plugin Options
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Option</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
<Table.HeaderCell>Required</Table.HeaderCell>
<Table.HeaderCell>Default</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>
`api_key`
</Table.Cell>
<Table.Cell>
A string indicating the [Stripe API key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard).
</Table.Cell>
<Table.Cell>
Yes
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`webhook_secret`
</Table.Cell>
<Table.Cell>
A string indicating the [Stripe webhook secret](https://docs.stripe.com/webhooks#add-a-webhook-endpoint). This is only useful for deployed Medusa applications.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`capture`
</Table.Cell>
<Table.Cell>
A boolean indicating whether to automatically capture payments when an order is placed.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`false`. Payments are authorized when an order is placed and the admin user captures the payment manually.
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`automatic_payment_methods`
</Table.Cell>
<Table.Cell>
A boolean value indicating whether to enable Stripe's automatic payment methods. This is useful if you're integrating services like Apple pay or Google pay.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`false`
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`payment_description`
</Table.Cell>
<Table.Cell>
A string used as the default description of a payment if none is available in `cart.context.payment_description`.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
\-
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`webhook_delay`
</Table.Cell>
<Table.Cell>
A number indicating the delay in milliseconds before processing the webhook event.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`5000` (five seconds)
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>
`webhook_retries`
</Table.Cell>
<Table.Cell>
A number of times to retry the webhook event processing in case of an error.
</Table.Cell>
<Table.Cell>
No
</Table.Cell>
<Table.Cell>
`3`
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
### Environment Variables
Make sure to add the necessary environment variables for the above options in `.env`:
```bash
STRIPE_API_KEY=<YOUR_STRIPE_API_KEY>
```
---
## Test the Stripe Plugin
To test the plugin, start the Medusa application:
```bash npm2yarn
npm run dev
```
Then, you must enable the Stripe Payment Provider in at least one region to use it. You can do that using either the [Medusa Admin](!user-guide!/settings/regions/providers), or the [Admin API Routes](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders).
Finally, try to place an order using either a [storefront](../../../nextjs-starter/page.mdx) or the [Store API Routes](https://docs.medusajs.com/api/store). You can use Stripe during checkout and to process the order's payment.
---
## Webhook Events
This plugin handles the following Stripe webhook events:
- `payment_intent.succeeded`: If the payment is associated with a payment collection, the plugin captures the payments within the webhook listener of this event. Otherwise, it checks first if an order is created and, if not, completes the cart which creates the order. It also captures 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 webhook listener completes the cart and creates the order.
- `payment_intent.payment_failed`: the webhook listener prints the error message received from Stripe into the logs.
---
## Storefront Setup
This section provides an example of how to add Stripe as a payment method in custom storefronts. For the Next.js storefront, refer to [this guide](../../../nextjs-starter/page.mdx#stripe-integration)
### Integration Steps Overview
1. When the user reaches the payment section during checkout, [create payment sessions](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsessions).
2. If the user chooses Stripe, select the Stripe provider's [the payment session](https://docs.medusajs.com/api/store#carts_postcartscartpaymentsession) in the cart.
3. After the user enters their card details and submits the form, confirm the payment with Stripe.
4. If successful, [complete the cart](https://docs.medusajs.com/api/store#carts_postcartscartcomplete) in Medusa.
### Add to Custom Storefront
<Note>
This example assumes your storefront uses React. If not, the steps generally clarify how to implement it in your storefront.
</Note>
In your storefront, install [Stripe's React and JavaScript libraries](https://docs.stripe.com/stripe-js/react) and the [Medusa JS Client library](https://www.npmjs.com/package/@medusajs/medusa-js):
```bash npm2yarn
npm install --save @stripe/react-stripe-js @stripe/stripe-js @medusajs/medusa-js
```
Then, add [Stripe's publishable key](https://support.stripe.com/questions/locate-api-keys-in-the-dashboard) as an environment variable based on the framework youre using.
After that, create a container component that holds the payment card component:
export const containerHighlights = [
["6", `"<STRIPE_PUB_KEY>"`, "Stripe's publishable key."]
]
```tsx
import { useState } from "react"
import { Elements } from "@stripe/react-stripe-js"
import Form from "./Form"
import { loadStripe } from "@stripe/stripe-js"
const stripePromise = loadStripe("<STRIPE_PUB_KEY>")
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 use Stripes `loadStripe` function outside of the components implementation to ensure that Stripe doesnt re-load with every change. The function accepts Stripe's publishable key.
Then, inside the components implementation, you add a state variable `clientSecret` which youll retrieve in the next section.
The `Elements` Stripe component wraps a `Form` component that youll create next. The `Elements` component allows child elements to get access to the cards inputs and their data using Stripes `useElements` hook.
Next, create a new file for the `Form` component with the following content:
```tsx
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>
)
}
```
The `useStripe` hook gives you access to the stripe instance to confirm the payment later. The `useElements` hook gives you access to the card element to retrieve the entered card details safely.
Youll now implement the integration steps explained earlier in the `Container` component.
Start by initializing the Medusa client:
```tsx
import Medusa from "@medusajs/medusa-js"
export default function Container() {
const client = new Medusa({
baseUrl: "http://localhost:9000",
maxRetries: 3,
})
// ...
}
```
Then, in the place of the `//TODO`, 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.provider_id === "stripe"
)
if (!isStripeAvailable) {
return
}
// select stripe payment session
client.carts
.setPaymentSession(cart.id, {
provider_id: "stripe",
})
.then(({ cart }) => {
setClientSecret(cart.payment_session.data.client_secret)
})
})
```
<Note>
Its assumed you have access to the `cart` object throughout your storefront. Ideally, the `cart` should be managed through a context. In that case, you probably wouldnt need a `clientSecret` state variable as you can use the client secret directly from the `cart` object.
</Note>
Once the client secret is set, the form is shown to the user.
The last step in the integration step is confirming the payment with Stripe and if its done successfully, completing the customer's order.
In the `Form` component, initialize the Medusa client or re-use the same client in the `Container` element
```tsx
import Medusa from "@medusajs/medusa-js"
export default function Form() {
const client = new Medusa({
baseUrl: "http://localhost:9000",
maxRetries: 3,
})
// ...
}
```
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 passing it the client secret, which you can access in the cart object if its available through a context.
This method also requires as a second parameter an object of the customers information including `name`, `email`, and their address.
Once the promise resolves you handle any errors that could've occurred. If no errors occurred, you complete the customers order.
If you run the Medusa application and the storefront, you can use Stripe during checkout.