docs: editing and general fixes of medusa's learning resources (#7261)

* docs: editing and general fixes of medusa's learning resources

* fix build script

* update ui dependency

* fix build

* adjust next.js steps
This commit is contained in:
Shahed Nasser
2024-05-13 18:55:11 +03:00
committed by GitHub
parent 803e4aad02
commit 7cb90f8e82
79 changed files with 488 additions and 1707 deletions
@@ -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.