1 ---
2 sidebar_label: "Integrate PayPal"
3 products:
4 - payment
5 ---
6
7 import { Github, EllipsisHorizontal } from "@medusajs/icons"
8 import { Card, Prerequisites, WorkflowDiagram, InlineIcon } from "docs-ui"
9
10 export const metadata = {
11 title: `Integrate PayPal (Payment) with Medusa`,
12 }
13
14 # {metadata.title}
15
16 In this tutorial, you'll learn how to integrate PayPal with Medusa for payment processing.
17
18 When you install a Medusa application, you get a fully-fledged commerce platform with a Framework for customization. Medusa's architecture facilitates integrating third-party services to handle various functionalities, including payment processing.
19
20 [PayPal](https://www.paypal.com/) is a widely used payment gateway that allows businesses to accept payments online securely. By integrating PayPal with Medusa, you can offer your customers a convenient and trusted payment option.
21
22 ## Summary
23
24 By following this tutorial, you'll learn how to:
25
26 - Install and set up Medusa.
27 - Integrate PayPal as a Payment Module Provider in Medusa.
28 - Customize the Next.js Starter Storefront to include PayPal as a payment option.
29
30 You can follow this tutorial whether you're new to Medusa or an advanced Medusa developer.
31
32 ![Diagram showing the checkout flow between customer, Medusa, and PayPal](https://res.cloudinary.com/dza7lstvk/image/upload/v1765268705/Medusa%20Resources/paypal-overview_rsqisb.jpg)
33
34 <Card
35 href="https://github.com/medusajs/examples/tree/main/paypal-integration"
36 title="Full Code"
37 text="Find the complete code for this integration on GitHub."
38 icon={Github}
39 />
40
41 ---
42
43 ## Step 1: Install a Medusa Application
44
45 <Prerequisites items={[
46 {
47 text: "Node.js v20.19.0+ or v22.12.0+",
48 link: "https://nodejs.org/en/download"
49 },
50 {
51 text: "Git CLI tool",
52 link: "https://git-scm.com/downloads"
53 },
54 {
55 text: "PostgreSQL",
56 link: "https://www.postgresql.org/download/"
57 }
58 ]} />
59
60 Start by installing the Medusa application on your machine with the following command:
61
62 ```bash
63 npx create-medusa-app@latest
64 ```
65
66 You'll first be asked for the project's name. Then, when asked whether you want to install the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx), choose "Yes."
67
68 Afterwards, the installation process will start, which will install the Medusa application as a monorepository in a directory with your project's name. The backend is installed in the `apps/backend` directory, and the Next.js Starter Storefront is installed in the `apps/storefront` directory.
69
70 Once the installation finishes successfully, the Medusa Admin dashboard will open with a form to create a new user. Enter the user's credentials and submit the form. Afterwards, you can log in with the new user and explore the dashboard.
71
72 <Note title="Ran into Errors">
73
74 Check out the [troubleshooting guides](../../../troubleshooting/create-medusa-app-errors/page.mdx) for help.
75
76 </Note>
77
78 <Note>
79
80 In this guide, all file paths of backend customizations are relative to the `apps/backend` directory of your Medusa project.
81
82 </Note>
83
84 ---
85
86 ## Step 2: Create PayPal Module Provider
87
88 To integrate third-party services into Medusa, you create a custom module. A module is a reusable package with functionalities related to a single feature or domain.
89
90 Medusa's [Payment Module](../../../commerce-modules/payment/page.mdx) provides an interface to process payments in your Medusa application. It delegates the actual payment processing to the underlying providers.
91
92 In this step, you'll integrate PayPal as a Payment Module Provider and configure it in your Medusa application. Later, you'll use it to process payments.
93
94 <Note>
95
96 Refer to the [Modules](!docs!/learn/fundamentals/modules) documentation to learn more about modules in Medusa.
97
98 </Note>
99
100 ### a. Install PayPal SDK
101
102 To interact with PayPal's APIs, run the following command in your Medusa application to install the PayPal server SDK:
103
104 ```bash npm2yarn
105 npm install @paypal/paypal-server-sdk
106 ```
107
108 You'll use the SDK in the Payment Module Provider's service.
109
110 ### b. Create Module Directory
111
112 A module is created under the `src/modules` directory of your Medusa application. So, create the directory `src/modules/paypal`.
113
114 ### c. Create PayPal Module's Service
115
116 A module has a service that contains its logic. For Payment Module Providers, the service implements the logic to process payments with third-party services.
117
118 To create the service of the PayPal Payment Module Provider, create the file `src/modules/paypal/service.ts` with the following content:
119
120 ```ts title="src/modules/paypal/service.ts"
121 import { AbstractPaymentProvider } from "@medusajs/framework/utils"
122 import { Logger } from "@medusajs/framework/types"
123 import {
124 Client,
125 Environment,
126 OrdersController,
127 PaymentsController,
128 } from "@paypal/paypal-server-sdk"
129
130 type Options = {
131 client_id: string
132 client_secret: string
133 environment?: "sandbox" | "production"
134 autoCapture?: boolean
135 webhook_id?: string
136 }
137
138 type InjectedDependencies = {
139 logger: Logger
140 }
141
142 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
143 static identifier = "paypal"
144
145 protected logger_: Logger
146 protected options_: Options
147 protected client_: Client
148 protected ordersController_: OrdersController
149 protected paymentsController_: PaymentsController
150
151 constructor(container: InjectedDependencies, options: Options) {
152 super(container, options)
153
154 this.logger_ = container.logger
155 this.options_ = {
156 environment: "sandbox",
157 autoCapture: false,
158 ...options,
159 }
160
161 // Initialize PayPal client
162 this.client_ = new Client({
163 environment:
164 this.options_.environment === "production"
165 ? Environment.Production
166 : Environment.Sandbox,
167 clientCredentialsAuthCredentials: {
168 oAuthClientId: this.options_.client_id,
169 oAuthClientSecret: this.options_.client_secret,
170 },
171 })
172
173 this.ordersController_ = new OrdersController(this.client_)
174 this.paymentsController_ = new PaymentsController(this.client_)
175 }
176
177 // TODO: Add methods
178 }
179
180 export default PayPalPaymentProviderService
181 ```
182
183 A Payment Module Provider service must extend the `AbstractPaymentProvider` class. It must also have a static `identifier` property that uniquely identifies the provider.
184
185 The module provider's constructor receives two parameters:
186
187 - `container`: The [module's container](!docs!/learn/fundamentals/modules/container) that contains Framework resources available to the module.
188 - `options`: Options that are passed to the module provider when it's registered in Medusa's configurations. You define the following option:
189 - `client_id`: The PayPal Client ID.
190 - `client_secret`: The PayPal Client Secret.
191 - `environment`: The PayPal environment to use, either `sandbox` or `production`.
192 - `autoCapture`: Whether to capture payments immediately or authorize them for later capture.
193 - `webhook_id`: The PayPal Webhook ID for validating webhooks.
194
195 In the constructor, you initialize the PayPal SDK client and controllers using the provided credentials.
196
197 In the next sections, you'll implement the methods required by the `AbstractPaymentProvider` class to process payments with PayPal.
198
199 <Note>
200
201 Refer to the [Create Payment Module Provider](/references/payment/provider) guide for detailed information about the methods.
202
203 </Note>
204
205 #### validateOptions Method
206
207 The [validateOptions](/references/payment/provider#validateoptions) method validates that the module has received the required options.
208
209 Add the following method to the `PayPalPaymentProviderService` class:
210
211 ```ts title="src/modules/paypal/service.ts"
212 import {
213 MedusaError,
214 } from "@medusajs/framework/utils"
215
216 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
217 // ...
218 static validateOptions(options: Record<any, any>): void | never {
219 if (!options.client_id) {
220 throw new MedusaError(
221 MedusaError.Types.INVALID_DATA,
222 "Client ID is required"
223 )
224 }
225 if (!options.client_secret) {
226 throw new MedusaError(
227 MedusaError.Types.INVALID_DATA,
228 "Client secret is required"
229 )
230 }
231 }
232 }
233 ```
234
235 The `validateOptions` method receives the options passed to the module provider as a parameter.
236
237 In the method, you throw an error if the `client_id` or `client_secret` options are missing. This will stop the application from starting.
238
239 #### initiatePayment Method
240
241 The [initiatePayment](/references/payment/provider#initiatepayment) method initializes a payment session with the third-party service. It's called when the customer selects a payment method during checkout.
242
243 You'll create a PayPal order in this method.
244
245 Add the following method to the `PayPalPaymentProviderService` class:
246
247 ```ts title="src/modules/paypal/service.ts"
248 import type {
249 InitiatePaymentInput,
250 InitiatePaymentOutput,
251 } from "@medusajs/framework/types"
252 import {
253 CheckoutPaymentIntent,
254 OrderApplicationContextLandingPage,
255 OrderApplicationContextUserAction,
256 OrderRequest,
257 } from "@paypal/paypal-server-sdk"
258
259 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
260 // ...
261 async initiatePayment(
262 input: InitiatePaymentInput
263 ): Promise<InitiatePaymentOutput> {
264 try {
265 const { amount, currency_code } = input
266
267 // Determine intent based on autoCapture option
268 const intent = this.options_.autoCapture
269 ? CheckoutPaymentIntent.Capture
270 : CheckoutPaymentIntent.Authorize
271
272 // Create PayPal order request
273 const orderRequest: OrderRequest = {
274 intent: intent,
275 purchaseUnits: [
276 {
277 amount: {
278 currencyCode: currency_code.toUpperCase(),
279 value: amount.toString(),
280 },
281 description: "Order payment",
282 customId: input.data?.session_id as string | undefined,
283 },
284 ],
285 applicationContext: {
286 // TODO: Customize as needed
287 brandName: "Store",
288 landingPage: OrderApplicationContextLandingPage.NoPreference,
289 userAction: OrderApplicationContextUserAction.PayNow,
290 },
291 }
292
293 const response = await this.ordersController_.createOrder({
294 body: orderRequest,
295 prefer: "return=representation",
296 })
297
298 const order = response.result
299
300 if (!order?.id) {
301 throw new MedusaError(
302 MedusaError.Types.UNEXPECTED_STATE,
303 "Failed to create PayPal order"
304 )
305 }
306
307 // Extract approval URL from links
308 const approvalUrl = order.links?.find(
309 (link) => link.rel === "approve"
310 )?.href
311
312 return {
313 id: order.id,
314 data: {
315 order_id: order.id,
316 intent: intent,
317 status: order.status,
318 approval_url: approvalUrl,
319 session_id: input.data?.session_id,
320 currency_code,
321 },
322 }
323 } catch (error: any) {
324 throw new MedusaError(
325 MedusaError.Types.UNEXPECTED_STATE,
326 `Failed to initiate PayPal payment: ${error.result?.message || error}`
327 )
328 }
329 }
330 }
331 ```
332
333 The `initiatePayment` method receives an object with the payment details, such as the amount and currency code.
334
335 In the method, you:
336
337 1. Determine the payment intent based on the `autoCapture` option. By default, payments are authorized for later capture.
338 2. Create a PayPal order request with the payment details.
339 - You can customize the `applicationContext` as needed. For example, you can set your store's name and the PayPal landing page type.
340
341 You return an object with the PayPal order ID and a `data` object with additional information, such as the intent and approval URL. Medusa stores the `data` object in the payment session's `data` field, allowing you to access it for later processing.
342
343 <Note>
344
345 Refer to the [Create Payment Module Provider](/references/payment/provider#initiatepayment) guide for detailed information about this method.
346
347 </Note>
348
349 #### authorizePayment Method
350
351 The [authorizePayment](/references/payment/provider#authorizepayment) method authorizes a payment with the third-party service. It's called when the customer places their order to authorize the payment with the selected payment method.
352
353 You'll authorize or capture the PayPal order in this method, based on the `autoCapture` option.
354
355 Add the following method to the `PayPalPaymentProviderService` class:
356
357 ```ts title="src/modules/paypal/service.ts"
358 import type {
359 AuthorizePaymentInput,
360 AuthorizePaymentOutput,
361 PaymentSessionStatus,
362 } from "@medusajs/framework/types"
363
364 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
365 // ...
366 async authorizePayment(
367 input: AuthorizePaymentInput
368 ): Promise<AuthorizePaymentOutput> {
369 try {
370 const orderId = input.data?.order_id as string | undefined
371
372 if (!orderId || typeof orderId !== "string") {
373 throw new MedusaError(
374 MedusaError.Types.INVALID_DATA,
375 "PayPal order ID is required"
376 )
377 }
378
379 // If autoCapture is enabled, authorize and capture in one step
380 if (this.options_.autoCapture) {
381 const response = await this.ordersController_.captureOrder({
382 id: orderId,
383 prefer: "return=representation",
384 })
385
386 const capture = response.result
387
388 if (!capture?.id) {
389 throw new MedusaError(
390 MedusaError.Types.UNEXPECTED_STATE,
391 "Failed to capture PayPal payment"
392 )
393 }
394
395 // Extract capture ID from purchase units
396 const captureId =
397 capture.purchaseUnits?.[0]?.payments?.captures?.[0]?.id
398
399 return {
400 data: {
401 ...input.data,
402 capture_id: captureId,
403 intent: "CAPTURE",
404 },
405 status: "captured" as PaymentSessionStatus,
406 }
407 }
408
409 // Otherwise, just authorize
410 const response = await this.ordersController_.authorizeOrder({
411 id: orderId,
412 prefer: "return=representation",
413 })
414
415 const authorization = response.result
416
417 if (!authorization?.id) {
418 throw new MedusaError(
419 MedusaError.Types.UNEXPECTED_STATE,
420 "Failed to authorize PayPal payment"
421 )
422 }
423
424 // Extract authorization ID from purchase units
425 const authId =
426 authorization.purchaseUnits?.[0]?.payments?.authorizations?.[0]?.id
427
428 return {
429 data: {
430 order_id: orderId,
431 authorization_id: authId,
432 intent: "AUTHORIZE",
433 currency_code: input.data?.currency_code,
434 },
435 status: "authorized" as PaymentSessionStatus,
436 }
437 } catch (error: any) {
438 throw new MedusaError(
439 MedusaError.Types.UNEXPECTED_STATE,
440 `Failed to authorize PayPal payment: ${error.message || error}`
441 )
442 }
443 }
444 }
445 ```
446
447 The `authorizePayment` method receives an object with the payment session's `data` field.
448
449 In the method, you:
450
451 1. Extract the PayPal order ID from the `data` field. This is the same `data.order_id` you returned in the `initiatePayment` method.
452 2. If the `autoCapture` option is enabled, you capture the PayPal order.
453 3. Otherwise, you authorize the PayPal order.
454
455 You return an object with a `data` field containing additional information, such as the authorization or capture ID. Medusa will store the `data` object in the newly created payment record for later processing.
456
457 <Note>
458
459 Refer to the [Create Payment Module Provider](/references/payment/provider#authorizepayment) guide for detailed information about this method.
460
461 </Note>
462
463 #### capturePayment Method
464
465 The [capturePayment](/references/payment/provider#capturepayment) method captures a previously authorized payment with the third-party service. It's called either when:
466
467 - An admin user captures the payment from the Medusa Admin dashboard.
468 - PayPal webhook notifies Medusa that the payment has been captured.
469
470 You'll captured the authorized PayPal order in this method.
471
472 Add the following method to the `PayPalPaymentProviderService` class:
473
474 ```ts title="src/modules/paypal/service.ts"
475 import type {
476 CapturePaymentInput,
477 CapturePaymentOutput,
478 } from "@medusajs/framework/types"
479
480 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
481 // ...
482 async capturePayment(
483 input: CapturePaymentInput
484 ): Promise<CapturePaymentOutput> {
485 try {
486 const authorizationId = input.data?.authorization_id as string | undefined
487
488 if (!authorizationId || typeof authorizationId !== "string") {
489 throw new MedusaError(
490 MedusaError.Types.INVALID_DATA,
491 "PayPal authorization ID is required for capture"
492 )
493 }
494
495 const response = await this.paymentsController_.captureAuthorizedPayment({
496 authorizationId: authorizationId,
497 prefer: "return=representation",
498 })
499
500 const capture = response.result
501
502 if (!capture?.id) {
503 throw new MedusaError(
504 MedusaError.Types.UNEXPECTED_STATE,
505 "Failed to capture PayPal payment"
506 )
507 }
508
509 return {
510 data: {
511 ...input.data,
512 capture_id: capture.id,
513 },
514 }
515 } catch (error: any) {
516 throw new MedusaError(
517 MedusaError.Types.UNEXPECTED_STATE,
518 `Failed to capture PayPal payment: ${error.result?.message || error}`
519 )
520 }
521 }
522 }
523 ```
524
525 The `capturePayment` method receives an object with the payment record's `data` field.
526
527 In the method, you:
528
529 1. Extract the PayPal authorization ID from the `data` field. This is the same `data.authorization_id` you returned in the `authorizePayment` method.
530 2. Capture the authorized PayPal payment.
531
532 You return an object with a `data` field containing additional information, such as the capture ID. Medusa updates the payment record's `data` field with the returned `data` object.
533
534 <Note>
535
536 Refer to the [Create Payment Module Provider](/references/payment/provider#capturepayment) guide for detailed information about this method.
537
538 </Note>
539
540 #### refundPayment Method
541
542 The [refundPayment](/references/payment/provider#refundpayment) method refunds a previously captured payment with the third-party service. It's called when an admin user issues a refund from the Medusa Admin dashboard.
543
544 You'll refund the captured PayPal payment in this method.
545
546 Add the following method to the `PayPalPaymentProviderService` class:
547
548 ```ts title="src/modules/paypal/service.ts"
549 import type {
550 RefundPaymentInput,
551 RefundPaymentOutput,
552 } from "@medusajs/framework/types"
553 import { BigNumber } from "@medusajs/framework/utils"
554
555 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
556 // ...
557 async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
558 try {
559 const captureId = input.data?.capture_id as string | undefined
560
561 if (!captureId || typeof captureId !== "string") {
562 throw new MedusaError(
563 MedusaError.Types.INVALID_DATA,
564 "PayPal capture ID is required for refund"
565 )
566 }
567
568 const refundRequest = {
569 amount: {
570 currencyCode: (input.data?.currency_code as string | undefined)
571 ?.toUpperCase() || "",
572 value: new BigNumber(input.amount).numeric.toString(),
573 },
574 }
575
576 const response = await this.paymentsController_.refundCapturedPayment({
577 captureId: captureId,
578 body: Object.keys(refundRequest).length > 0 ? refundRequest : undefined,
579 prefer: "return=representation",
580 })
581
582 const refund = response.result
583
584 if (!refund?.id) {
585 throw new MedusaError(
586 MedusaError.Types.UNEXPECTED_STATE,
587 "Failed to refund PayPal payment"
588 )
589 }
590
591 return {
592 data: {
593 ...input.data,
594 refund_id: refund.id,
595 },
596 }
597 } catch (error: any) {
598 throw new MedusaError(
599 MedusaError.Types.UNEXPECTED_STATE,
600 `Failed to refund PayPal payment: ${error.result?.message || error}`
601 )
602 }
603 }
604 }
605 ```
606
607 The `refundPayment` method receives an object with the payment record's `data` field.
608
609 In the method, you:
610
611 1. Extract the PayPal capture ID from the `data` field. This is the same `data.capture_id` you returned in the `capturePayment` method.
612 2. Extract the amount and currency code from the input.
613 3. Refund the captured PayPal payment.
614
615 You return an object with a `data` field containing additional information, such as the refund ID. Medusa updates the payment record's `data` field with the returned `data` object.
616
617 <Note>
618
619 Refer to the [Create Payment Module Provider](/references/payment/provider#refundpayment) guide for detailed information about this method.
620
621 </Note>
622
623 #### updatePayment Method
624
625 The [updatePayment](/references/payment/provider#updatepayment) method updates the payment session in the third-party service. It's called when the payment session needs to be updated, such as when the order amount changes.
626
627 You'll update the PayPal order amount in this method.
628
629 Add the following method to the `PayPalPaymentProviderService` class:
630
631 ```ts title="src/modules/paypal/service.ts"
632 import type {
633 UpdatePaymentInput,
634 UpdatePaymentOutput,
635 } from "@medusajs/framework/types"
636 import {
637 PatchOp,
638 } from "@paypal/paypal-server-sdk"
639
640 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
641 // ...
642 async updatePayment(
643 input: UpdatePaymentInput
644 ): Promise<UpdatePaymentOutput> {
645 try {
646 const orderId = input.data?.order_id as string | undefined
647
648 if (!orderId) {
649 throw new MedusaError(
650 MedusaError.Types.INVALID_DATA,
651 "PayPal order ID is required"
652 )
653 }
654
655 await this.ordersController_.patchOrder({
656 id: orderId as string,
657 body: [
658 {
659 op: PatchOp.Replace,
660 path: "/purchase_units/@reference_id=='default'/amount/value",
661 value: new BigNumber(input.amount).numeric.toString(),
662 },
663 ],
664 })
665
666 return {
667 data: {
668 ...input.data,
669 currency_code: input.currency_code,
670 },
671 }
672 } catch (error: any) {
673 throw new MedusaError(
674 MedusaError.Types.UNEXPECTED_STATE,
675 `Failed to update PayPal payment: ${error.result?.message || error}`
676 )
677 }
678 }
679 }
680 ```
681
682 The `updatePayment` method receives an object with the payment session's `data` field.
683
684 In the method, you:
685
686 1. Extract the PayPal order ID from the `data` field. This is the same `data.order_id` you returned in the `initiatePayment` method.
687 2. Update the PayPal order amount.
688
689 You return an object with a `data` field containing the updated payment information. Medusa updates the payment session's `data` field with the returned `data` object.
690
691 <Note>
692
693 Refer to the [Create Payment Module Provider](/references/payment/provider#updatepayment) guide for detailed information about this method.
694
695 </Note>
696
697 #### deletePayment Method
698
699 The [deletePayment](/references/payment/provider#deletepayment) method deletes the payment session in the third-party service. It's called when the customer changes the payment method during checkout.
700
701 PayPal orders cannot be deleted, so you can leave this method empty. PayPal will automatically cancel orders that are not approved within a certain timeframe.
702
703 Add the following method to the `PayPalPaymentProviderService` class:
704
705 ```ts title="src/modules/paypal/service.ts"
706 import type {
707 DeletePaymentInput,
708 DeletePaymentOutput,
709 } from "@medusajs/framework/types"
710
711 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
712 // ...
713 async deletePayment(
714 input: DeletePaymentInput
715 ): Promise<DeletePaymentOutput> {
716 // Note: PayPal doesn't have a cancelOrder API endpoint
717 // Orders can only be voided if they're authorized, which is handled in cancelPayment
718 // For orders that haven't been authorized yet, they will expire automatically
719
720 return {
721 data: input.data,
722 }
723 }
724 }
725 ```
726
727 The `deletePayment` method receives an object with the payment session's `data` field.
728
729 In the method, you simply return the existing `data` object without making any changes.
730
731 <Note>
732
733 Refer to the [Create Payment Module Provider](/references/payment/provider#deletepayment) guide for detailed information about this method.
734
735 </Note>
736
737 #### retrievePayment Method
738
739 The [retrievePayment](/references/payment/provider#retrievepayment) method retrieves the payment details from the third-party service. You'll retrieve the order details from PayPal in this method.
740
741 Add the following method to the `PayPalPaymentProviderService` class:
742
743 ```ts title="src/modules/paypal/service.ts"
744 import type {
745 RetrievePaymentInput,
746 RetrievePaymentOutput,
747 } from "@medusajs/framework/types"
748
749 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
750 // ...
751 async retrievePayment(
752 input: RetrievePaymentInput
753 ): Promise<RetrievePaymentOutput> {
754 try {
755 const orderId = input.data?.order_id as string | undefined
756
757 if (!orderId || typeof orderId !== "string") {
758 throw new MedusaError(
759 MedusaError.Types.INVALID_DATA,
760 "PayPal order ID is required"
761 )
762 }
763
764 const response = await this.ordersController_.getOrder({
765 id: orderId,
766 })
767
768 const order = response.result
769
770 if (!order?.id) {
771 throw new MedusaError(
772 MedusaError.Types.NOT_FOUND,
773 "PayPal order not found"
774 )
775 }
776
777 return {
778 data: {
779 order_id: order.id,
780 status: order.status,
781 intent: order.intent,
782 },
783 }
784 } catch (error: any) {
785 throw new MedusaError(
786 MedusaError.Types.UNEXPECTED_STATE,
787 `Failed to retrieve PayPal payment: ${error.result?.message || error}`
788 )
789 }
790 }
791 }
792 ```
793
794 The `retrievePayment` method receives an object with the payment record's `data` field.
795
796 In the method, you:
797
798 1. Extract the PayPal order ID from the `data` field. This is the same `data.order_id` you returned in the `initiatePayment` method.
799 2. Retrieve the PayPal order details.
800
801 You return an object with a `data` field containing the retrieved payment information.
802
803 <Note>
804
805 Refer to the [Create Payment Module Provider](/references/payment/provider#retrievepayment) guide for detailed information about this method.
806
807 </Note>
808
809 #### cancelPayment Method
810
811 The [cancelPayment](/references/payment/provider#cancelpayment) method cancels a previously authorized payment with the third-party service. It's called when an admin user cancels an order from the Medusa Admin dashboard.
812
813 You'll void the authorized PayPal payment in this method.
814
815 Add the following method to the `PayPalPaymentProviderService` class:
816
817 ```ts title="src/modules/paypal/service.ts"
818 import type {
819 CancelPaymentInput,
820 CancelPaymentOutput,
821 } from "@medusajs/framework/types"
822
823 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
824 // ...
825 async cancelPayment(
826 input: CancelPaymentInput
827 ): Promise<CancelPaymentOutput> {
828 try {
829 const authorizationId = input.data?.authorization_id as string | undefined
830
831 if (!authorizationId || typeof authorizationId !== "string") {
832 throw new MedusaError(
833 MedusaError.Types.INVALID_DATA,
834 "PayPal authorization ID is required for cancellation"
835 )
836 }
837
838 await this.paymentsController_.voidPayment({
839 authorizationId: authorizationId,
840 })
841
842 return {
843 data: input.data,
844 }
845 } catch (error: any) {
846 throw new MedusaError(
847 MedusaError.Types.UNEXPECTED_STATE,
848 `Failed to cancel PayPal payment: ${error.result?.message || error}`
849 )
850 }
851 }
852 }
853 ```
854
855 The `cancelPayment` method receives an object with the payment record's `data` field.
856
857 In the method, you:
858
859 1. Extract the PayPal authorization ID from the `data` field. This is the same `data.authorization_id` you returned in the `authorizePayment` method.
860 2. Void the authorized PayPal payment.
861
862 You return an object with the existing `data` field without making any changes. Medusa updates the payment record's `data` field with the returned `data` object.
863
864 #### getPaymentStatus Method
865
866 The [getPaymentStatus](/references/payment/provider#getpaymentstatus) method retrieves the current status of the payment from the third-party service. You'll retrieve the order status from PayPal in this method.
867
868 Add the following method to the `PayPalPaymentProviderService` class:
869
870 ```ts title="src/modules/paypal/service.ts"
871 import type {
872 GetPaymentStatusInput,
873 GetPaymentStatusOutput,
874 } from "@medusajs/framework/types"
875 import { OrderStatus } from "@paypal/paypal-server-sdk"
876
877 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
878 // ...
879 async getPaymentStatus(
880 input: GetPaymentStatusInput
881 ): Promise<GetPaymentStatusOutput> {
882 try {
883 const orderId = input.data?.order_id as string | undefined
884
885 if (!orderId || typeof orderId !== "string") {
886 return { status: "pending" as PaymentSessionStatus }
887 }
888
889 const response = await this.ordersController_.getOrder({
890 id: orderId,
891 })
892
893 const order = response.result
894
895 if (!order) {
896 return { status: "pending" as PaymentSessionStatus }
897 }
898
899 const status = order.status
900
901 switch (status) {
902 case OrderStatus.Created:
903 case OrderStatus.Saved:
904 return { status: "pending" as PaymentSessionStatus }
905 case OrderStatus.Approved:
906 return { status: "authorized" as PaymentSessionStatus }
907 case OrderStatus.Completed:
908 return { status: "authorized" as PaymentSessionStatus }
909 case OrderStatus.Voided:
910 return { status: "canceled" as PaymentSessionStatus }
911 default:
912 return { status: "pending" as PaymentSessionStatus }
913 }
914 } catch (error: any) {
915 return { status: "pending" as PaymentSessionStatus }
916 }
917 }
918 }
919 ```
920
921 The `getPaymentStatus` method receives an object with the payment record's `data` field.
922
923 In the method, you:
924
925 1. Extract the PayPal order ID from the `data` field. This is the same `data.order_id` you returned in the `initiatePayment` method.
926 2. Retrieve the PayPal order details.
927 3. Map the PayPal order status to Medusa's `PaymentSessionStatus`.
928
929 You return an object with the mapped payment status.
930
931 <Note>
932
933 Refer to the [Create Payment Module Provider](/references/payment/provider#getpaymentstatus) guide for detailed information about this method.
934
935 </Note>
936
937 #### verifyWebhookSignature Method
938
939 The `verifyWebhookSignature` method is not required by the `AbstractPaymentProvider` class. You'll create this method to verify PayPal webhook signatures, and use it in the next method that handles webhooks.
940
941 Add the following method to the `PayPalPaymentProviderService` class:
942
943 ```ts title="src/modules/paypal/service.ts"
944 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
945 // ...
946 private async verifyWebhookSignature(
947 headers: Record<string, any>,
948 body: any,
949 rawBody: string | Buffer | undefined
950 ): Promise<boolean> {
951 try {
952 if (!this.options_.webhook_id) {
953 throw new MedusaError(
954 MedusaError.Types.INVALID_DATA,
955 "PayPal webhook ID is required for webhook signature verification"
956 )
957 }
958
959 const transmissionId =
960 headers["paypal-transmission-id"]
961 const transmissionTime =
962 headers["paypal-transmission-time"]
963 const certUrl =
964 headers["paypal-cert-url"]
965 const authAlgo =
966 headers["paypal-auth-algo"]
967 const transmissionSig =
968 headers["paypal-transmission-sig"]
969
970 if (
971 !transmissionId ||
972 !transmissionTime ||
973 !certUrl ||
974 !authAlgo ||
975 !transmissionSig
976 ) {
977 throw new MedusaError(
978 MedusaError.Types.INVALID_DATA,
979 "Missing required PayPal webhook headers"
980 )
981 }
982
983 // PayPal's API endpoint for webhook verification
984 const baseUrl =
985 this.options_.environment === "production"
986 ? "https://api.paypal.com"
987 : "https://api.sandbox.paypal.com"
988
989 const verifyUrl = `${baseUrl}/v1/notifications/verify-webhook-signature`
990
991 // Get access token for verification API call
992 const authResponse = await fetch(`${baseUrl}/v1/oauth2/token`, {
993 method: "POST",
994 headers: {
995 "Content-Type": "application/x-www-form-urlencoded",
996 Authorization: `Basic ${Buffer.from(
997 `${this.options_.client_id}:${this.options_.client_secret}`
998 ).toString("base64")}`,
999 },
1000 body: "grant_type=client_credentials",
1001 })
1002
1003 if (!authResponse.ok) {
1004 throw new MedusaError(
1005 MedusaError.Types.UNEXPECTED_STATE,
1006 "Failed to get access token for webhook verification"
1007 )
1008 }
1009
1010 const authData = await authResponse.json()
1011 const accessToken = authData.access_token
1012
1013 if (!accessToken) {
1014 throw new MedusaError(
1015 MedusaError.Types.UNEXPECTED_STATE,
1016 "Access token not received from PayPal"
1017 )
1018 }
1019
1020 let webhookEvent: any
1021 if (rawBody) {
1022 const rawBodyString =
1023 typeof rawBody === "string" ? rawBody : rawBody.toString("utf8")
1024 try {
1025 webhookEvent = JSON.parse(rawBodyString)
1026 } catch (e) {
1027 this.logger_.warn("Raw body is not valid JSON, using parsed body")
1028 webhookEvent = body
1029 }
1030 } else {
1031 this.logger_.warn(
1032 "Raw body not available, using parsed body. Verification may fail if formatting differs."
1033 )
1034 webhookEvent = body
1035 }
1036
1037 const verifyPayload = {
1038 transmission_id: transmissionId,
1039 transmission_time: transmissionTime,
1040 cert_url: certUrl,
1041 auth_algo: authAlgo,
1042 transmission_sig: transmissionSig,
1043 webhook_id: this.options_.webhook_id,
1044 webhook_event: webhookEvent,
1045 }
1046
1047 const verifyResponse = await fetch(verifyUrl, {
1048 method: "POST",
1049 headers: {
1050 "Content-Type": "application/json",
1051 Authorization: `Bearer ${accessToken}`,
1052 },
1053 body: JSON.stringify(verifyPayload),
1054 })
1055
1056 if (!verifyResponse.ok) {
1057 throw new MedusaError(
1058 MedusaError.Types.UNEXPECTED_STATE,
1059 "Webhook verification API call failed"
1060 )
1061 }
1062
1063 const verifyData = await verifyResponse.json()
1064
1065 // PayPal returns verification_status: "SUCCESS" if verification passes
1066 const isValid = verifyData.verification_status === "SUCCESS"
1067
1068 if (!isValid) {
1069 throw new MedusaError(
1070 MedusaError.Types.UNEXPECTED_STATE,
1071 "Webhook signature verification failed"
1072 )
1073 }
1074
1075 return isValid
1076 } catch (e) {
1077 this.logger_.error("PayPal verifyWebhookSignature error:", e)
1078 return false
1079 }
1080 }
1081 }
1082 ```
1083
1084 The `verifyWebhookSignature` method receives the following parameters:
1085
1086 1. `headers`: The HTTP headers from the webhook request.
1087 2. `body`: The parsed JSON body from the webhook request.
1088 3. `rawBody`: The raw body from the webhook request as a string or buffer.
1089
1090 In the method, you:
1091
1092 1. Extract the required PayPal webhook headers.
1093 2. Get an [access token](https://developer.paypal.com/api/rest/authentication/) for the PayPal webhook verification API.
1094 3. Construct the verification payload with the extracted headers and webhook event data.
1095 4. Call the PayPal [webhook verification API](https://developer.paypal.com/api/rest/webhooks/rest/#link-postbackmethod) to verify the webhook signature.
1096
1097 You return `true` if the webhook signature is valid (based on the API's response), or `false` otherwise.
1098
1099 #### getWebhookActionAndData Method
1100
1101 The [getWebhookActionAndData](/references/payment/provider#getwebhookactionanddata) method processes incoming webhook events from the third-party service. Medusa provides a webhook endpoint at `/hooks/payment/{provider_id}` that you can use to receive PayPal webhooks. This endpoint calls the `getWebhookActionAndData` method to process the webhook event.
1102
1103 Add the following method to the `PayPalPaymentProviderService` class:
1104
1105 ```ts title="src/modules/paypal/service.ts"
1106 import { PaymentActions } from "@medusajs/framework/utils"
1107 import type {
1108 ProviderWebhookPayload,
1109 WebhookActionResult,
1110 } from "@medusajs/framework/types"
1111
1112 class PayPalPaymentProviderService extends AbstractPaymentProvider<Options> {
1113 // ...
1114 async getWebhookActionAndData(
1115 payload: ProviderWebhookPayload["payload"]
1116 ): Promise<WebhookActionResult> {
1117 try {
1118 const { data, rawData, headers } = payload
1119
1120 // Verify webhook signature
1121 const isValid = await this.verifyWebhookSignature(
1122 headers || {},
1123 data,
1124 rawData || ""
1125 )
1126
1127 if (!isValid) {
1128 this.logger_.error("Invalid PayPal webhook signature")
1129 return {
1130 action: "failed",
1131 data: {
1132 session_id: "",
1133 amount: new BigNumber(0),
1134 },
1135 }
1136 }
1137
1138 // PayPal webhook events have event_type
1139 const eventType = (data as any)?.event_type
1140
1141 if (!eventType) {
1142 this.logger_.warn("PayPal webhook event missing event_type")
1143 return {
1144 action: "not_supported",
1145 data: {
1146 session_id: "",
1147 amount: new BigNumber(0),
1148 },
1149 }
1150 }
1151
1152 // Extract order ID and amount from webhook payload
1153 const resource = (data as any)?.resource
1154 const sessionId: string | undefined = (data as any)?.resource?.custom_id
1155
1156 if (!sessionId) {
1157 this.logger_.warn("Session ID not found in PayPal webhook resource")
1158 return {
1159 action: "not_supported",
1160 data: {
1161 session_id: "",
1162 amount: new BigNumber(0),
1163 },
1164 }
1165 }
1166
1167 const amountValue =
1168 resource?.amount?.value ||
1169 resource?.purchase_units?.[0]?.payments?.captures?.[0]?.amount
1170 ?.value ||
1171 resource?.purchase_units?.[0]?.payments?.authorizations?.[0]
1172 ?.amount?.value ||
1173 0
1174
1175 const amount = new BigNumber(amountValue)
1176 const payloadData = {
1177 session_id: sessionId,
1178 amount,
1179 }
1180
1181 // Map PayPal webhook events to Medusa actions
1182 switch (eventType) {
1183 case "PAYMENT.AUTHORIZATION.CREATED":
1184 return {
1185 action: PaymentActions.AUTHORIZED,
1186 data: payloadData,
1187 }
1188
1189 case "PAYMENT.CAPTURE.DENIED":
1190 return {
1191 action: PaymentActions.FAILED,
1192 data: payloadData,
1193 }
1194
1195 case "PAYMENT.AUTHORIZATION.VOIDED":
1196 return {
1197 action: PaymentActions.CANCELED,
1198 data: payloadData,
1199 }
1200
1201 case "PAYMENT.CAPTURE.COMPLETED":
1202 return {
1203 action: PaymentActions.SUCCESSFUL,
1204 data: payloadData,
1205 }
1206
1207 default:
1208 this.logger_.info(`Unhandled PayPal webhook event: ${eventType}`)
1209 return {
1210 action: PaymentActions.NOT_SUPPORTED,
1211 data: payloadData,
1212 }
1213 }
1214 } catch (error: any) {
1215 this.logger_.error("PayPal getWebhookActionAndData error:", error.result?.message || error)
1216 return {
1217 action: "failed",
1218 data: {
1219 session_id: "",
1220 amount: new BigNumber(0),
1221 },
1222 }
1223 }
1224 }
1225 }
1226 ```
1227
1228 The `getWebhookActionAndData` method receives a `payload` object containing the webhook request data.
1229
1230 In the method, you:
1231
1232 1. Verify the webhook signature using the `verifyWebhookSignature` method.
1233 2. Extract the `event_type` from the webhook payload to determine the type of event.
1234 3. Extract the session ID and amount from the webhook resource.
1235 4. Map the PayPal webhook event types to Medusa actions.
1236
1237 You return an object containing the action Medusa should take (such as `authorized`), along with the payment session ID and amount. Based on the returned action, Medusa uses the methods you implemented earlier to perform the necessary operations.
1238
1239 ### d. Export Module Definition
1240
1241 You've now finished implementing the necessary methods for the PayPal Payment Module Provider.
1242
1243 The final piece to a module is its definition, which you export in an `index.ts` file at the module's root directory. This definition tells Medusa the module's details, including its service.
1244
1245 To create the module's definition, create the file `src/modules/paypal/index.ts` with the following content:
1246
1247 ```ts title="src/modules/paypal/index.ts"
1248 import PayPalPaymentProviderService from "./service"
1249 import { ModuleProvider, Modules } from "@medusajs/framework/utils"
1250
1251 export default ModuleProvider(Modules.PAYMENT, {
1252 services: [PayPalPaymentProviderService],
1253 })
1254 ```
1255
1256 You use `ModuleProvider` from the Modules SDK to create the module provider's definition. It accepts two parameters:
1257
1258 1. The name of the module that this provider belongs to, which is `Modules.PAYMENT` in this case.
1259 2. An object with a required property `services` indicating the Module Provider's services.
1260
1261 ### e. Add Module Provider to Medusa's Configuration
1262
1263 Once you finish building the module, add it to Medusa's configurations to start using it.
1264
1265 In `medusa-config.ts`, add a `modules` property:
1266
1267 ```ts title="medusa-config.ts"
1268 module.exports = defineConfig({
1269 // ...
1270 modules: [
1271 // ...
1272 {
1273 resolve: "@medusajs/medusa/payment",
1274 options: {
1275 providers: [
1276 {
1277 resolve: "./src/modules/paypal",
1278 id: "paypal",
1279 options: {
1280 client_id: process.env.PAYPAL_CLIENT_ID!,
1281 client_secret: process.env.PAYPAL_CLIENT_SECRET!,
1282 environment: process.env.PAYPAL_ENVIRONMENT || "sandbox",
1283 autoCapture: process.env.PAYPAL_AUTO_CAPTURE === "true",
1284 webhook_id: process.env.PAYPAL_WEBHOOK_ID,
1285 },
1286 },
1287 ],
1288 },
1289 },
1290 ],
1291 })
1292 ```
1293
1294 To pass Payment Module Providers to the Payment Module, add the `modules` property to the Medusa configuration and pass the Payment Module in its value.
1295
1296 The Payment Module accepts a `providers` option, which is an array of Payment Module Providers to register.
1297
1298 To register the PayPal Payment Module Provider, you add an object to the `providers` array with the following properties:
1299
1300 - `resolve`: The NPM package or path to the module provider. In this case, it's the path to the `src/modules/paypal` directory.
1301 - `id`: The ID of the module provider. The Payment Module Provider is then registered with the ID `pp_{identifier}_{id}`, where:
1302 - `{identifier}`: The identifier static property defined in the Module Provider's service, which is `paypal` in this case.
1303 - `{id}`: The ID set in this configuration, which is also `paypal` in this case.
1304 - `options`: The options to pass to the module provider. These are the options you defined in the `Options` interface of the module provider's service.
1305
1306 ### f. Set Options as Environment Variables
1307
1308 Next, you'll set the necessary options as environment variables. You'll retrieve their values from the [PayPal Developer Dashboard](https://developer.paypal.com/dashboard/).
1309
1310 #### PayPal Client ID and Secret
1311
1312 To get your PayPal Client ID and Secret:
1313
1314 1. [Log in to the PayPal Developer Dashboard](https://developer.paypal.com/dashboard/).
1315 2. Make sure you're in the correct environment (Sandbox or Live) using the environment toggle at the top left. It's recommended to use Sandbox for development and testing.
1316
1317 ![PayPal environment toggle highlighted with Sandbox selected](https://res.cloudinary.com/dza7lstvk/image/upload/v1765207135/Medusa%20Resources/CleanShot_2025-12-08_at_17.18.06_2x_sbm8bv.png)
1318
1319 2. Go to **Apps & Credentials**.
1320 3. If you don't have a default app, create one by clicking **Create App**.
1321 - Enter app name, set type to "Merchant", and select the sandbox business account.
1322 4. Click on your app to view its details.
1323 5. Copy the **Client ID** and **Secret** values.
1324
1325 ![PayPal app details showing Client ID and Secret](https://res.cloudinary.com/dza7lstvk/image/upload/v1765207279/Medusa%20Resources/CleanShot_2025-12-08_at_17.20.49_2x_zu9muk.png)
1326
1327 Then, set these values as environment variables in your `.env` file:
1328
1329 ```shell title=".env"
1330 PAYPAL_CLIENT_ID=your_paypal_client_id
1331 PAYPAL_CLIENT_SECRET=your_paypal_client_secret
1332 ```
1333
1334 #### PayPal Environment and Auto-Capture Option
1335
1336 Next, you can set the following optional environment variables in your `.env` file:
1337
1338 ```shell title=".env"
1339 PAYPAL_ENVIRONMENT=sandbox # or "production" for live
1340 PAYPAL_AUTO_CAPTURE=true # or "false" to authorize only
1341 ```
1342
1343 Where:
1344
1345 - `PAYPAL_ENVIRONMENT`: The PayPal environment to use, either `sandbox` for testing or `production` for live transactions. Default is `sandbox`.
1346 - `PAYPAL_AUTO_CAPTURE`: Whether to capture payments immediately (`true`) or authorize only (`false`). Default is `false`.
1347
1348 #### PayPal Webhook ID
1349
1350 Finally, you'll set up a webhook in the PayPal Developer Dashboard to receive payment events. Webhooks require a publicly accessible URL. In this section, you'll use [ngrok](https://ngrok.com/) to create a temporary public URL for testing webhooks locally.
1351
1352 <Note title="Tip">
1353
1354 Deploy your Medusa application with [Cloud](!cloud!/sign-up) in minutes. Benefit from features like zero-configuration deployments, automatic scaling, GitHub integration, and more.
1355
1356 </Note>
1357
1358 To set up ngrok and create a public URL, run the following command in your terminal:
1359
1360 ```shell
1361 npx ngrok http 9000
1362 ```
1363
1364 This will create a public URL that tunnels to your local Medusa server running on port `9000`. Copy the generated URL (for example, `https://abcd1234.ngrok.io`).
1365
1366 Then, on the [PayPal Developer Dashboard](https://developer.paypal.com/dashboard/):
1367
1368 1. Go to **Apps & Credentials**.
1369 2. Click on your app to view its details.
1370 3. Scroll down to the **Webhooks** (or **Sandbox Webhooks**) section and click **Add Webhook**.
1371 4. In the **Webhook URL** field, enter your ngrok URL followed by `/hooks/payment/paypal_paypal`. For example: `https://abcd1234.ngrok.io/hooks/payment/paypal_paypal`.
1372 - The URL format is `{base_url}/hooks/payment/{provider_id}`, where `provider_id` is `paypal_paypal` (the combination of the `identifier` and `id` from your configuration).
1373 5. In the **Event Types** section, select the following events:
1374 - Payment authorization created
1375 - Payment authorization voided
1376 - Payment capture completed
1377 - Payment capture denied
1378 6. Click **Save** to create the webhook.
1379
1380 Then, copy the **Webhook ID** from the webhook details. Set it as an environment variable in your `.env` file:
1381
1382 ```shell title=".env"
1383 PAYPAL_WEBHOOK_ID=your_paypal_webhook_id
1384 ```
1385
1386 Make sure the ngrok command remains running while you test PayPal webhooks locally. If you restart ngrok, you'll get a new public URL, and you'll need to update the webhook URL in the PayPal Developer Dashboard accordingly.
1387
1388 In the next steps, you'll customize the Next.js Starter Storefront to support paying with PayPal, then test out the integration.
1389
1390 ---
1391
1392 ## Step 3: Enable PayPal Module Provider
1393
1394 In this step, you'll enable the PayPal Payment Module Provider in a region of your Medusa store. A region is a geographical area where you sell products, and each region has its own settings, such as currency and payment providers.
1395
1396 You must enable the PayPal Payment Module Provider in at least one region. To do this:
1397
1398 1. Run the following command to start your Medusa application:
1399
1400 ```bash npm2yarn
1401 npm run dev
1402 ```
1403
1404 2. Open the Medusa Admin dashboard in your browser at `http://localhost:9000/app` and log in.
1405 3. Go to Settings -> Regions.
1406 4. Click on the <InlineIcon Icon={EllipsisHorizontal} alt="three-dots" /> icon next to the region you want to enable PayPal for, then click **Edit**.
1407 5. In the **Payment Providers** dropdown, select **PayPal (PAYPAL)** to add it to the region.
1408 6. Click **Save** to update the region.
1409
1410 Repeat these steps for every region where you want to enable the PayPal Payment Module Provider.
1411
1412 ![Medusa Admin dashboard showing region edit screen with PayPal selected as payment provider](https://res.cloudinary.com/dza7lstvk/image/upload/v1765265899/Medusa%20Resources/CleanShot_2025-12-09_at_09.36.54_2x_g4guz6.png)
1413
1414 ---
1415
1416 ## Step 4: Add PayPal to Storefront
1417
1418 In this step, you'll customize the [Next.js Starter Storefront](../../../nextjs-starter/page.mdx) that you set up with the Medusa application to support paying with PayPal. You'll add a PayPal button to the checkout page that allows customers to pay using PayPal.
1419
1420 <Note title="Reminder" forceMultiline>
1421
1422 The Next.js Starter Storefront is available in the `apps/storefront` directory of your project:
1423
1424 ```bash
1425 cd apps/storefront
1426 ```
1427
1428 </Note>
1429
1430 ### a. Install PayPal SDK
1431
1432 To add the PayPal button, you'll use the [PayPal React SDK](https://www.npmjs.com/package/@paypal/react-paypal-js). This SDK provides React components that make it easy to integrate PayPal into your React application.
1433
1434 In the storefront directory, run the following command to install the PayPal React SDK:
1435
1436 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
1437 npm install @paypal/react-paypal-js
1438 ```
1439
1440 ### b. Add Client ID Environment Variable
1441
1442 Next, add the PayPal Client ID as an environment variable in the storefront.
1443
1444 Copy the same PayPal Client ID you used in the Medusa application, then add it to the `.env.local` file in the storefront directory:
1445
1446 ```shell title=".env.local" badgeLabel="Storefront" badgeColor="blue"
1447 NEXT_PUBLIC_PAYPAL_CLIENT_ID=your_paypal_client_id
1448 ```
1449
1450 ### c. Add PayPal Wrapper Component
1451
1452 Next, you'll add a PayPal wrapper component that initializes the PayPal SDK and provides the PayPal context to its child components.
1453
1454 Create the file `src/modules/checkout/components/payment-wrapper/paypal-wrapper.tsx` with the following content:
1455
1456 ```tsx title="src/modules/checkout/components/payment-wrapper/paypal-wrapper.tsx" badgeLabel="Storefront" badgeColor="blue"
1457 "use client"
1458
1459 import { PayPalScriptProvider } from "@paypal/react-paypal-js"
1460 import { HttpTypes } from "@medusajs/types"
1461 import { createContext } from "react"
1462
1463 type PayPalWrapperProps = {
1464 paymentSession: HttpTypes.StorePaymentSession
1465 children: React.ReactNode
1466 }
1467
1468 export const PayPalContext = createContext(false)
1469
1470 const PayPalWrapper: React.FC<PayPalWrapperProps> = ({
1471 paymentSession,
1472 children,
1473 }) => {
1474 const clientId = process.env.NEXT_PUBLIC_PAYPAL_CLIENT_ID
1475
1476 if (!clientId) {
1477 throw new Error(
1478 "PayPal client ID is missing. Set NEXT_PUBLIC_PAYPAL_CLIENT_ID environment variable or ensure payment session has client_id."
1479 )
1480 }
1481
1482 const initialOptions = {
1483 clientId,
1484 currency: paymentSession.currency_code.toUpperCase() || "USD",
1485 intent: paymentSession.data?.intent === "CAPTURE" ? "capture" : "authorize",
1486 }
1487
1488 return (
1489 <PayPalContext.Provider value={true}>
1490 <PayPalScriptProvider options={initialOptions}>
1491 {children}
1492 </PayPalScriptProvider>
1493 </PayPalContext.Provider>
1494 )
1495 }
1496
1497 export default PayPalWrapper
1498 ```
1499
1500 You create a `PayPalWrapper` component that accepts a Medusa payment session and children components as props.
1501
1502 In the component, you:
1503
1504 1. Retrieve the PayPal Client ID from the environment variable `NEXT_PUBLIC_PAYPAL_CLIENT_ID`.
1505 2. Set the initial options for the PayPal SDK, including the client ID, currency, and intent (capture or authorize).
1506 - You set the intent based on the `data.intent` field in the payment session. You set this field in the `initiatePayment` method of the PayPal Payment Module Provider's service. Its value depends on the `autoCapture` option.
1507 3. Wrap the children components with the `PayPalScriptProvider` component from the PayPal React SDK, passing the initial options.
1508
1509 Next, you'll use this wrapper component in the checkout page to provide the PayPal context to the PayPal button component you'll add later.
1510
1511 In `src/modules/checkout/components/payment-wrapper/index.tsx`, add the following imports at the top of the file:
1512
1513 ```tsx title="src/modules/checkout/components/payment-wrapper/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1514 import PayPalWrapper from "./paypal-wrapper"
1515 import { isPaypal } from "@lib/constants"
1516 ```
1517
1518 Then, in the `PaymentWrapper` component, add the following before the last `return` statement:
1519
1520 ```tsx title="src/modules/checkout/components/payment-wrapper/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1521 if (isPaypal(paymentSession?.provider_id) && paymentSession) {
1522 return (
1523 <PayPalWrapper
1524 paymentSession={paymentSession}
1525 >
1526 {children}
1527 </PayPalWrapper>
1528 )
1529 }
1530 ```
1531
1532 If the customer has selected PayPal as the payment method, you wrap the children components with the `PayPalWrapper` component, passing the payment session as a prop.
1533
1534 ### d. Add PayPal Button Component
1535
1536 Next, you'll add a PayPal button component that renders the PayPal button and handles the payment process.
1537
1538 Create the file `src/modules/checkout/components/payment-button/paypal-payment-button.tsx` with the following content:
1539
1540 ```tsx title="src/modules/checkout/components/payment-button/paypal-payment-button.tsx" badgeLabel="Storefront" badgeColor="blue"
1541 "use client"
1542
1543 import { PayPalButtons, usePayPalScriptReducer } from "@paypal/react-paypal-js"
1544 import { placeOrder } from "@lib/data/cart"
1545 import { HttpTypes } from "@medusajs/types"
1546 import { Button } from "@medusajs/ui"
1547 import React, { useState } from "react"
1548 import ErrorMessage from "../error-message"
1549
1550 type PayPalPaymentButtonProps = {
1551 cart: HttpTypes.StoreCart
1552 notReady: boolean
1553 "data-testid"?: string
1554 }
1555
1556 const PayPalPaymentButton: React.FC<PayPalPaymentButtonProps> = ({
1557 cart,
1558 notReady,
1559 "data-testid": dataTestId,
1560 }) => {
1561 const [submitting, setSubmitting] = useState(false)
1562 const [errorMessage, setErrorMessage] = useState<string | null>(null)
1563 const [{ isResolved }] = usePayPalScriptReducer()
1564
1565 const paymentSession = cart.payment_collection?.payment_sessions?.find(
1566 (s) => s.status === "pending"
1567 )
1568
1569 // TODO: add function handlers
1570 }
1571
1572 export default PayPalPaymentButton
1573 ```
1574
1575 You create a `PayPalPaymentButton` component that accepts the cart, a `notReady` flag, and an optional `data-testid` prop for testing.
1576
1577 In the component, you initialize the following variables:
1578
1579 - `submitting`: A state variable to track if the payment is being submitted.
1580 - `errorMessage`: A state variable to store any error messages.
1581 - `isResolved`: A variable from the PayPal SDK that indicates whether the PayPal SDK script has loaded.
1582 - `paymentSession`: The pending PayPal payment session from the cart's payment collection.
1583
1584 Next, you'll add the function handlers for creating PayPal orders and placing the Medusa order.
1585
1586 Replace the `// TODO: add function handlers` comment with the following:
1587
1588 export const functionHandlerHighlights = [
1589 ["1", "onPaymentCompleted", "Place the Medusa order after PayPal payment approval."],
1590 ["14", "getPayPalOrderId", "Retrieve the PayPal order ID from the payment session data."],
1591 ["28", "createOrder", "Return the PayPal order ID created by the Medusa server."],
1592 ["59", "onApprove", "Handle PayPal payment approval and place the Medusa order."],
1593 ["73", "onError", "Handle errors during the PayPal payment process."],
1594 ["80", "onCancel", "Handle PayPal payment cancellation by the customer."]
1595 ]
1596
1597 ```tsx title="src/modules/checkout/components/payment-button/paypal-payment-button.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={functionHandlerHighlights}
1598 const onPaymentCompleted = async () => {
1599 await placeOrder()
1600 .catch((err) => {
1601 setErrorMessage(err.message)
1602 })
1603 .finally(() => {
1604 setSubmitting(false)
1605 })
1606 }
1607
1608 // Get PayPal order ID from payment session data
1609 // The Medusa PayPal provider should create a PayPal order during initialization
1610 // and store the order ID in the payment session data
1611 const getPayPalOrderId = (): string | null => {
1612 if (!paymentSession?.data) {
1613 return null
1614 }
1615
1616 // Try different possible keys where the order ID might be stored
1617 return (
1618 (paymentSession.data.order_id as string) ||
1619 (paymentSession.data.orderId as string) ||
1620 (paymentSession.data.id as string) ||
1621 null
1622 )
1623 }
1624
1625 const createOrder = async () => {
1626 setSubmitting(true)
1627 setErrorMessage(null)
1628
1629 try {
1630 if (!paymentSession) {
1631 throw new Error("Payment session not found")
1632 }
1633
1634 // Check if Medusa server already created a PayPal order
1635 const existingOrderId = getPayPalOrderId()
1636
1637 if (existingOrderId) {
1638 // Medusa already created the order, use that order ID
1639 return existingOrderId
1640 }
1641
1642 // If no order ID exists, we need to create one
1643 // This might happen if the PayPal provider doesn't create orders during initialization
1644 // In this case, we'll need to create the order via PayPal API
1645 // For now, throw an error - the backend should handle order creation
1646 throw new Error(
1647 "PayPal order not found. Please ensure the payment session is properly initialized."
1648 )
1649 } catch (error: any) {
1650 setErrorMessage(error.message || "Failed to create PayPal order")
1651 setSubmitting(false)
1652 throw error
1653 }
1654 }
1655
1656 const onApprove = async (data: { orderID: string }) => {
1657 try {
1658 setSubmitting(true)
1659 setErrorMessage(null)
1660
1661 // After PayPal approval, place the order
1662 // The Medusa server will handle the payment authorization
1663 await onPaymentCompleted()
1664 } catch (error: any) {
1665 setErrorMessage(error.message || "Failed to process PayPal payment")
1666 setSubmitting(false)
1667 }
1668 }
1669
1670 const onError = (err: Record<string, unknown>) => {
1671 setErrorMessage(
1672 (err.message as string) || "An error occurred with PayPal payment"
1673 )
1674 setSubmitting(false)
1675 }
1676
1677 const onCancel = () => {
1678 setSubmitting(false)
1679 setErrorMessage("PayPal payment was cancelled")
1680 }
1681
1682 // TODO: add a return statement
1683 ```
1684
1685 You add the following function handlers:
1686
1687 - `onPaymentCompleted`: Places the Medusa order by calling the `placeOrder` function. This function is called after the PayPal payment is approved.
1688 - `getPayPalOrderId`: Retrieves the PayPal order ID from the payment session's `data` field.
1689 - `createOrder`: Returns the PayPal order ID that was created by the Medusa server during payment initialization. If no order ID exists, it throws an error.
1690 - `onApprove`: Called when the customer approves the PayPal payment. It calls the `onPaymentCompleted` function to place the Medusa order.
1691 - `onError`: Called when an error occurs during the PayPal payment process. It updates the error message state.
1692 - `onCancel`: Called when the customer cancels the PayPal payment. It updates the error message state.
1693
1694 Finally, you'll add the return statement to render the PayPal button.
1695
1696 Replace the `// TODO: add a return statement` comment with the following:
1697
1698 ```tsx title="src/modules/checkout/components/payment-button/paypal-payment-button.tsx" badgeLabel="Storefront" badgeColor="blue"
1699 // If PayPal SDK is not ready, show a loading button
1700 if (!isResolved) {
1701 return (
1702 <>
1703 <Button
1704 disabled={true}
1705 size="large"
1706 isLoading={true}
1707 data-testid={dataTestId}
1708 >
1709 Loading PayPal...
1710 </Button>
1711 <ErrorMessage
1712 error={errorMessage}
1713 data-testid="paypal-payment-error-message"
1714 />
1715 </>
1716 )
1717 }
1718
1719 return (
1720 <>
1721 <div className="mb-4">
1722 <PayPalButtons
1723 createOrder={createOrder}
1724 onApprove={onApprove}
1725 onError={onError}
1726 onCancel={onCancel}
1727 style={{
1728 layout: "horizontal",
1729 color: "black",
1730 shape: "rect",
1731 label: "buynow",
1732 }}
1733 disabled={notReady || submitting}
1734 />
1735 </div>
1736 <ErrorMessage
1737 error={errorMessage}
1738 data-testid="paypal-payment-error-message"
1739 />
1740 </>
1741 )
1742 ```
1743
1744 You render two different states:
1745
1746 - If the PayPal SDK is not ready, you render a loading button.
1747 - If the SDK is ready, you render the `PayPalButtons` component from the PayPal React SDK, passing the function handlers as props.
1748
1749 ### e. Use PayPal Button in Checkout Page
1750
1751 Next, you'll use the `PayPalPaymentButton` component in the checkout page to allow customers to pay with PayPal.
1752
1753 In `src/modules/checkout/components/payment-button/index.tsx`, add the following imports at the top of the file:
1754
1755 ```tsx title="src/modules/checkout/components/payment-button/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1756 import { isPaypal } from "@lib/constants"
1757 import PayPalPaymentButton from "./paypal-payment-button"
1758 ```
1759
1760 Then, in the `PaymentButton` component, add to the `switch` block a case for PayPal:
1761
1762 ```tsx title="src/modules/checkout/components/payment-button/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1763 const PaymentButton: React.FC<PaymentButtonProps> = ({
1764 cart,
1765 "data-testid": dataTestId,
1766 }) => {
1767 // ...
1768 switch (true) {
1769 case isPaypal(paymentSession?.provider_id):
1770 return (
1771 <PayPalPaymentButton
1772 notReady={notReady}
1773 cart={cart}
1774 data-testid={dataTestId}
1775 />
1776 )
1777 // ...
1778 }
1779 }
1780 ```
1781
1782 When the customer selects PayPal as the payment method, you render the `PayPalPaymentButton` component, passing the cart and `notReady` flag as props.
1783
1784 ### f. Handle Selecting PayPal in Checkout Page
1785
1786 Finally, you'll handle selecting PayPal as the payment method in the checkout page. You'll ensure that when the customer selects PayPal, the payment session is created and initialized correctly.
1787
1788 In `src/modules/checkout/components/payment/index.tsx`, add the following import at the top of the file:
1789
1790 ```tsx title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="blue"
1791 import { isPaypal } from "@lib/constants"
1792 ```
1793
1794 Then, replace the `setPaymentMethod` function defined in the `Payment` component with the following:
1795
1796 export const setPaymentMethodHighlights = [
1797 ["4", "", "Add condition to check if the selected method is PayPal."]
1798 ]
1799
1800 ```tsx title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={setPaymentMethodHighlights}
1801 const setPaymentMethod = async (method: string) => {
1802 setError(null)
1803 setSelectedPaymentMethod(method)
1804 if (isStripeLike(method) || isPaypal(method)) {
1805 await initiatePaymentSession(cart, {
1806 provider_id: method,
1807 })
1808 }
1809 }
1810 ```
1811
1812 You change the `if` condition in the `setPaymentMethod` function to also initialize the payment session when PayPal is selected.
1813
1814 Finally, change the `handleSubmit` function defined in the `Payment` component to the following:
1815
1816 export const handleSubmitHighlights = [
1817 ["17", "", "Add condition to check if the selected method is PayPal."],
1818 ]
1819
1820 ```tsx title="src/modules/checkout/components/payment/index.tsx" badgeLabel="Storefront" badgeColor="blue" highlights={handleSubmitHighlights}
1821 const handleSubmit = async () => {
1822 setIsLoading(true)
1823 try {
1824 const shouldInputCard =
1825 isStripeLike(selectedPaymentMethod) && !activeSession
1826
1827 const checkActiveSession =
1828 activeSession?.provider_id === selectedPaymentMethod
1829
1830 if (!checkActiveSession) {
1831 await initiatePaymentSession(cart, {
1832 provider_id: selectedPaymentMethod,
1833 })
1834 }
1835
1836 // For PayPal, we don't need to input card details, so go to review
1837 if (!shouldInputCard || isPaypal(selectedPaymentMethod)) {
1838 return router.push(
1839 pathname + "?" + createQueryString("step", "review"),
1840 {
1841 scroll: false,
1842 }
1843 )
1844 }
1845 } catch (err: any) {
1846 setError(err.message)
1847 } finally {
1848 setIsLoading(false)
1849 }
1850 }
1851 ```
1852
1853 You mainly change the condition that checks whether to navigate to the review step. If PayPal is selected, you navigate to the review step directly since no card details are needed.
1854
1855 ### Test the PayPal Integration
1856
1857 You can now test the PayPal integration by placing an order from the Next.js Starter Storefront.
1858
1859 #### Get Sandbox PayPal Account Credentials
1860
1861 Before you test the integration, you'll need to get sandbox PayPal account credentials to use for testing payments.
1862
1863 To get sandbox PayPal account credentials:
1864
1865 1. [Go to your PayPal Developer Dashboard](https://developer.paypal.com/dashboard/).
1866 2. Make sure you're in the Sandbox environment using the environment toggle at the top left.
1867 3. Go to **Testing Tools** -> **Sandbox Accounts**.
1868 4. Click on the email ending with `@personal.example.com` to view the account details.
1869
1870 ![PayPal Developer Dashboard showing sandbox accounts](https://res.cloudinary.com/dza7lstvk/image/upload/v1765267446/Medusa%20Resources/CleanShot_2025-12-09_at_10.03.49_2x_phd4cj.png)
1871
1872 5. On the account details page, copy the **Email** and **Password** values. You'll use those to pay with PayPal during testing.
1873
1874 #### Test Checkout with PayPal
1875
1876 First, run the Medusa application with the following command:
1877
1878 ```bash npm2yarn badgeLabel="Medusa Application" badgeColor="green"
1879 npm run dev
1880 ```
1881
1882 Then, run the Next.js Starter Storefront with the following command in the storefront directory:
1883
1884 ```bash npm2yarn badgeLabel="Storefront" badgeColor="blue"
1885 npm run dev
1886 ```
1887
1888 Open the storefront at `http://localhost:8000` in your browser. Add an item to the cart and proceed to checkout.
1889
1890 On the payment step, select PayPal as the payment method, then click **Continue to Review**.
1891
1892 ![Next.js Starter Storefront checkout page showing PayPal selected as payment method](https://res.cloudinary.com/dza7lstvk/image/upload/v1765267123/Medusa%20Resources/CleanShot_2025-12-09_at_09.58.25_2x_b4ogqz.png)
1893
1894 This navigates you to the review step, where a PayPal button appears for completing your order.
1895
1896 ![Next.js Starter Storefront checkout page showing PayPal button](https://res.cloudinary.com/dza7lstvk/image/upload/v1765267289/Medusa%20Resources/CleanShot_2025-12-09_at_09.59.36_2x_r9sboh.png)
1897
1898 Click the PayPal button to be redirected to PayPal's payment page. On the PayPal login page, use the [sandbox account credentials](#get-sandbox-paypal-account-credentials) you obtained earlier to log in and complete the payment.
1899
1900 Once you complete the payment, PayPal redirects you back to the storefront's order confirmation page.
1901
1902 #### Check Webhook Event Handling
1903
1904 If you've [set up webhooks](#paypal-webhook-id) using ngrok or with your deployed Medusa instance, PayPal sends webhook events to your Medusa application after payment completion.
1905
1906 You'll see the following logged in your Medusa application's terminal:
1907
1908 ```bash
1909 info: Processing payment.webhook_received which has 1 subscribers
1910 http: POST /hooks/payment/paypal_paypal ← - (200) - 6.028 ms
1911 ```
1912
1913 Medusa uses the `getWebhookActionAndData` method you implemented earlier to process the webhook event and perform any necessary actions, such as authorizing the payment.
1914
1915 #### Capturing and Refunding Payments
1916
1917 In the Medusa Admin dashboard, you can go to Orders and view the order you just placed. You can see the payment status and details.
1918
1919 From the order's details page, you can capture the authorized payment, and refund the captured payment from the **Payments** section. Medusa will use your PayPal Payment Module Provider to perform these actions.
1920
1921 ![Medusa Admin dashboard showing order payment details with capture and refund options](https://res.cloudinary.com/dza7lstvk/image/upload/v1765267658/Medusa%20Resources/CleanShot_2025-12-09_at_10.06.57_2x_qsazep.png)
1922
1923 ---
1924
1925 ## Next Steps
1926
1927 You've successfully integrated PayPal with Medusa. You can now receive payments using PayPal in your Medusa store.
1928
1929 ### Learn More About Medusa
1930
1931 If you're new to Medusa, check out the [main documentation](!docs!/learn), where you'll get a more in-depth understanding of all the concepts you've used in this guide and more.
1932
1933 To learn more about the commerce features that Medusa provides, check out Medusa's [Commerce Modules](../../../commerce-modules/page.mdx).
1934
1935 ### Troubleshooting
1936
1937 If you encounter issues during development, check out the [troubleshooting guides](../../../troubleshooting/page.mdx).
1938
1939 ### Getting Help
1940
1941 If you encounter issues not covered in the troubleshooting guides:
1942
1943 1. Visit the [Medusa GitHub repository](https://github.com/medusajs/medusa) to report issues or ask questions.
1944 2. Join the [Medusa Discord community](https://discord.gg/medusajs) for real-time support from community members.