* Fix issue on fixed total amount discount when using includes tax (#3472) The calculation of the fixed discount amount breaks when having includes_tax setting active, due to the line item totals are incorrect and returning everything as 0, thus the totalItemPercentage will be Infinitiy due to the division by a subtotal of 0 * chore: Add missing changeset for @medusajs/medusa * feat(medusa): Improve performance of Products domain (#3417) * feat(medusa): Improve product update performances * fix tests and update * update mock repo * improve repo * cleanup * fix * cleanup + bulk emit + unit test fix * improvements * improve * fix unit tests * fix export * fix product update handler * enhance mock repo * fix import integration * fix end point tests * revert mock repo product variant * fix unit * cleanup * cleanup * address feedback * fix quotes in tests * address feedback * Create new-tips-mate.md * use types * chore: Remove integration-tests from changeset * chore(release): v1.7.14 * chore(docs): Generated Docs Announcement Bar (automated) (#3489) Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com> * fix(medusa): EventBusService.emit using Redis mock (#3491) * Fix eventBusService.emit using redis mock * revert gitignore * enqueuer * unit test add redis_url * fix test * chore(docs): Generated Services Reference (automated) (#3490) Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com> * docs: publish restructure (#3496) * docs: added features and guides overview page * added image * added version 2 * added version 3 * added version 4 * docs: implemented new color scheme * docs: redesigned sidebar (#3193) * docs: redesigned navbar for restructure (#3199) * docs: redesigned footer (#3209) * docs: redesigned cards (#3230) * docs: redesigned admonitions (#3231) * docs: redesign announcement bar (#3236) * docs: redesigned large cards (#3239) * docs: redesigned code blocks (#3253) * docs: redesigned search modal and page (#3264) * docs: redesigned doc footer (#3268) * docs: added new sidebars + refactored css and assets (#3279) * docs: redesigned api reference sidebar * docs: refactored css * docs: added code tabs transition * docs: added new sidebars * removed unused assets * remove unusued assets * Fix deploy errors * fix incorrect link * docs: fixed code responsivity + missing icons (#3283) * docs: changed icons (#3296) * docs: design fixes to the sidebar (#3297) * redesign fixes * docs: small design fixes * docs: several design fixes after restructure (#3299) * docs: bordered icon fixes * docs: desgin fixes * fixes to code blocks and sidebar scroll * design adjustments * docs: restructured homepage (#3305) * docs: restructured homepage * design fixes * fixed core concepts icon * docs: added core concepts page (#3318) * docs: restructured homepage * design fixes * docs: added core concepts page * changed text of different components * docs: added architecture link * added missing prop for user guide * docs: added regions overview page (#3327) * docs: added regions overview * moved region pages to new structure * docs: fixed description of regions architecture page * small changes * small fix * docs: added customers overview page (#3331) * docs: added regions overview * moved region pages to new structure * docs: fixed description of regions architecture page * small changes * small fix * docs: added customers overview page * fix link * resolve link issues * docs: updated regions architecture image * docs: second-iteration fixes (#3347) * docs: redesigned document * design fixes * docs: added products overview page (#3354) * docs: added carts overview page (#3363) * docs: added orders overview (#3364) * docs: added orders overview * added links in overview * docs: added vercel redirects * docs: added soon badge for cards (#3389) * docs: resolved feedback changes + organized troubleshooting pages (#3409) * docs: resolved feedback changes * added extra line * docs: changed icons for restructure (#3421) * docs: added taxes overview page (#3422) * docs: added taxes overview page * docs: fix sidebar label * added link to taxes overview page * fixed link * docs: fixed sidebar scroll (#3429) * docs: added discounts overview (#3432) * docs: added discounts overview * fixed links * docs: added gift cards overview (#3433) * docs: added price lists overview page (#3440) * docs: added price lists overview page * fixed links * docs: added sales channels overview page (#3441) * docs: added sales overview page * fixed links * docs: added users overview (#3443) * docs: fixed sidebar border height (#3444) * docs: fixed sidebar border height * fixed svg markup * docs: added possible solutions to feedback component (#3449) * docs: added several overview pages + restructured files (#3463) * docs: added several overview pages * fixed links * docs: added feature flags + PAK overview pages (#3464) * docs: added feature flags + PAK overview pages * fixed links * fix link * fix link * fixed links colors * docs: added strategies overview page (#3468) * docs: automated upgrade guide (#3470) * docs: automated upgrade guide * fixed vercel redirect * docs: restructured files in docs codebase (#3475) * docs: restructured files * docs: fixed eslint exception * docs: finished restructure loose-ends (#3493) * fixed uses of backend * docs: finished loose ends * eslint fixes * fixed links * merged master * added update instructions for v1.7.12 * docs: fixed discount details (#3499) * docs: fix trailing slash causing 404 (#3508) * docs: fix error during navigation (#3509) * docs: removed the gatsby storefront guide (#3527) * docs: removed the gatsby storefront guide * docs: fixed query value * chore(docs): Removed Docs Announcement Bar (automated) (#3536) Co-authored-by: shahednasser <shahednasser@users.noreply.github.com> * fix(medusa): Variant update should include the id for the listeners to be able to identify the entity (#3539) * fix(medusa): Variant update should include the id for the listeners to be able to identify the entity * fix unit tests * Create brave-seahorses-film.md * docs: fix admin redirects (#3548) * chore(release): v1.7.15 * chore(docs): Generated Docs Announcement Bar (automated) (#3550) Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com> * chore(docs): Generated Services Reference (automated) (#3551) Automated changes by [create-pull-request](https://github.com/peter-evans/create-pull-request) GitHub action Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com> * chore: updated READMEs of plugins (#3546) * chore: updated READMEs of plugins * added notice to plugins * docs: added a deploy guide for next.js storefront (#3558) * docs: added a deploy next.js guide * docs: fix image zoom * docs: fixes to next.js deployment guide to vercel (#3562) * chore(workflows): Enable manual workflow in pre-release mode (#3566) * chore(docs): Removed Docs Announcement Bar (automated) (#3598) Co-authored-by: shahednasser <shahednasser@users.noreply.github.com> * fix(medusa): Rounding issues on line item adjustments (#3446) * chores(medusa): Attempt to fix discount rounding issues * add migration * update entities * apply multipler factor properly * fix discount service * WIP * fix rounding issues in discounts * fix some tests * Exclude raw_discount_total from responses * fix adjustments * cleanup response * fix * fix draft order integration * fix order integration * fix order integration * address feedback * fix test * Create .changeset/polite-llamas-sit.md * remove comment --------- Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com> * chore(workflows): Add release notification (#3629) --------- Co-authored-by: pepijn-vanvlaanderen <pepijn@webbers.com> Co-authored-by: olivermrbl <oliver@mrbltech.com> Co-authored-by: Adrien de Peretti <adrien.deperetti@gmail.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: olivermrbl <olivermrbl@users.noreply.github.com> Co-authored-by: Carlos R. L. Rodrigues <37986729+carlos-r-l-rodrigues@users.noreply.github.com> Co-authored-by: shahednasser <shahednasser@users.noreply.github.com> Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
17 KiB
description, addHowToData
| description | addHowToData |
|---|---|
| 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. | true |
PayPal
This document guides you through setting up PayPal as a payment provider in your Medusa backend, admin, and storefront using the PayPal plugin.
Overview
PayPal is a payment provider 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 PayPal’s 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 provider.
Prerequisites
Before you proceed with this guide, make sure you create a PayPal account. 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 PayPal’s documentation.
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 weren’t created
Additionally, you need a Medusa backend installed and set up. If not, you can follow the quickstart guide to get started.
You also need Medusa Admin installed to enable PayPal as a payment provider. You can alternatively use the REST APIs.
Medusa Backend
Install the PayPal Plugin
In the root of your Medusa backend, run the following command to install the PayPal plugin:
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:
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 section.
Notice that during development it’s highly recommended to set PAYPAL_SANDBOX to true and ensure you have sandbox accounts set up in PayPal.
Then, in medusa-config.js, add the PayPal plugin to the plugins array with the configurations necessary:
const plugins = [
// other plugins...
{
resolve: `medusa-payment-paypal`,
options: {
sandbox: process.env.PAYPAL_SANDBOX,
client_id: process.env.PAYPAL_CLIENT_ID,
client_secret: process.env.PAYPAL_CLIENT_SECRET,
auth_webhook_id: process.env.PAYPAL_AUTH_WEBHOOK_ID,
},
},
]
That’s all you need to install PayPal on your Medusa backend!
Admin Setup
This section will guide you through adding PayPal as a payment provider in a region using your Medusa admin dashboard.
This step is required for you to be able to use PayPal as a payment provider in your storefront.
Admin Prerequisites
If you don’t have a Medusa admin installed, make sure to follow along with the guide on how to install it before continuing with this section.
Add PayPal to Regions
You can refer to this documentation in the user guide to learn how to add a payment provider 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 Medusa’s 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 Storefront, you need to add the implementation with PayPal manually.
:::note
It is recommended to read through the Frontend Checkout Flow 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:
- Show PayPal’s button if the PayPal provider is available for the current cart.
- When the button is clicked, open PayPal’s payment portal and wait for the customer to authorize the payment.
- If the payment is authorized successfully, set PayPal’s 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 PayPal’s payment portal. This data is essential to the backend to verify the authorization and perform additional payment processing later such as capturing payment.
- 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.
:::
Add to Next.js Storefront
Medusa has a Next.js storefront that you can easily use with your Medusa backend. If you don’t have the storefront installed, you can follow this quickstart guide.
In your .env.local file (or the file you’re using for your environment variables), add the following variable:
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 you’ll be able to use PayPal].
You can test out the payment with PayPal using your sandbox account.
Add to Gatsby Storefront
:::note
Medusa's Gatsby storefront is deprecated and it is recommended to use the Next.js storefront or build your own storefront instead.
:::
In your .env.development file (or the file you’re using for your environment variables) add the following variable with its value set to the Client ID:
GATSBY_PAYPAL_CLIENT_ID=<CLIENT_ID>
Then, install PayPal’s React components library:
npm install @paypal/react-paypal-js
Next, create a new file src/components/payment/paypal-payment/index.jsx with the following content:
import {
PayPalButtons,
PayPalScriptProvider,
} from "@paypal/react-paypal-js"
import React, { useMemo, useState } from "react"
import { navigate } from "gatsby"
import { useCart } from "../../../hooks/use-cart"
import { useMedusa } from "../../../hooks/use-medusa"
const paypalClientId = process.env.GATSBY_PAYPAL_CLIENT_ID || ""
const PaypalPayment = () => {
const {
cart,
actions: { completeCart, setPaymentSession },
} = useCart()
const [errorMessage, setErrorMessage] = useState(undefined)
const [processing, setProcessing] = useState(false)
const client = useMedusa()
const paypalSession = useMemo(() => {
if (cart.payment_sessions) {
return cart.payment_sessions.find(
(s) => s.provider_id === "paypal"
)
}
return null
}, [cart.payment_sessions])
if (!paypalSession) {
return null
}
const completeOrder = async (authorizationOrder) => {
const cart = await setPaymentSession("paypal")
if (!cart) {
setProcessing(false)
return
}
await client.carts.updatePaymentSession(cart.id, "paypal", {
data: {
data: {
...authorizationOrder,
},
},
})
const order = await completeCart(cart.id)
if (!order || order.object !== "order") {
setProcessing(false)
return
}
setProcessing(false)
navigate("/order-confirmed", { state: { order } })
}
const handlePayment = (data, actions) => {
actions.order.authorize().then((authorization) => {
if (authorization.status !== "COMPLETED") {
setErrorMessage(
`An error occurred, status: ${authorization.status}`
)
setProcessing(false)
return
}
completeOrder(authorization)
})
}
return (
<PayPalScriptProvider options={{
"client-id": paypalClientId,
"currency": cart.region.currency_code.toUpperCase(),
"intent": "authorize",
}}>
{errorMessage && (
<span className="text-rose-500 mt-4">
{errorMessage}
</span>
)}
<PayPalButtons
style={{ layout: "horizontal" }}
onApprove={handlePayment}
disabled={processing}
/>
</PayPalScriptProvider>
)
}
export default PaypalPayment
Here’s briefly what this code snippet does:
- 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
PayPalScriptProvidercomponent the Client ID. - When the button is clicked, the
handlePaymentfunction is executed. In this method, you initialize the payment authorization usingactions.order.authorize(). It takes the customer to another page to log in with PayPal and authorize the payment. - After the payment is authorized successfully on PayPal’s portal, the fulfillment function passed to
actions.order.authorize().thenwill be executed which calls thecompleteOrderfunction. - In
completeOrder, you first ensure that the payment session for the PayPal payment provider is set as the selected Payment Session in the cart. Then, you send a request to the backend to update the payment session data with the authorization data received from PayPal. - You then complete the cart and place the order. If that is done successfully, you navigate to the
/order-confirmedpage.
The last step is to add this component as the component to render when PayPal is available as a payment provider.
In src/components/payment/index.js you’ll find in the return statement a switch statement that checks the payment provider for each payment session and renders the component based on the ID. Add before the default case a case for paypal:
switch (ps.provider_id) {
case "stripe":
// ...
break
case "manual":
// ...
break
case "paypal":
return <PaypalPayment />
default:
return null
}
Make sure to also import the PayPalPayment component at the top of the file:
import PaypalPayment from "./paypal-payment"
That’s all you need to integrate PayPal into the Gatsby storefront.
Now, start the Medusa backend and the Gatsby storefront backend. Try adding an item into the cart and proceeding to checkout. When you reach the payment step, you should see the PayPal button.
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 and the Medusa JS Client library:
npm install @paypal/react-paypal-js @medusajs/medusa-js
Then, add the Client ID as an environment variable based on the framework you’re using.
Next, create the file that will hold the PayPal component with the following content:
import {
PayPalButtons,
PayPalScriptProvider,
} 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, {
"provider_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 && (
<PayPalScriptProvider 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}
/>
</PayPalScriptProvider>
)}
</div>
)
}
export default Paypal
Here’s briefly what this code snippet does:
- At the beginning of the component, the Medusa client is initialized using the JS Client you installed.
- 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.
- 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
PayPalScriptProvidercomponent the Client ID. Make sure to replace<CLIENT_ID>with the environment variable you added. - When the button is clicked, the
handlePaymentfunction is executed. In this method, you initialize the payment authorization usingactions.order.authorize(). It takes the customer to another page to log in with PayPal and authorize the payment. - After the payment is authorized successfully on PayPal’s portal, the fulfillment function passed to
actions.order.authorize().thenwill be executed. - In the fulfillment function, you first ensure that the payment session for the PayPal payment provider is set as the selected Payment Session in the cart. Then, you send a request to the backend to update the payment session data with the authorization data received from PayPal.
- You then complete the cart and place the order. 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.
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.
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 you can add to your store.



