PaymentProcessor
Overview
A Payment Processor is the payment method used to authorize, capture, and refund payment, among other actions. An example of a Payment Processor is Stripe.
By default, Medusa has a manual
payment provider that has minimal implementation. It can be synonymous with a Cash on Delivery payment method. It allows
store operators to manage the payment themselves but still keep track of its different stages on Medusa.
A payment processor is a service that extends the AbstractPaymentProcessor
and implements its methods. So, adding a Payment Processor is as simple as
creating a service file in src/services
. The file's name is the payment processor's class name as a slug and without the word Service
.
For example, if you're creating a MyPaymentService
class, the file name is src/services/my-payment.ts
.
The methods of the payment processor are used at different points in the Checkout flow as well as when processing an order after it’s placed.
Identifier Property
The PaymentProvider
entity has 2 properties: id
and is_installed
. The identifier
property in the payment processor service is used when the payment processor is added to the database.
The value of this property is also used to reference the payment processor throughout Medusa. For example, it is used to add a payment processor to a region.
PaymentProcessorError
Before diving into the methods of the Payment Processor, you'll notice that part of the expected return signature of these method includes PaymentProcessorError
.
While implementing the Payment Processor's methods, if you need to inform the Medusa core that an error occurred at a certain stage,
return an object having the attributes defined in the PaymentProcessorError
interface.
For example, the Stripe payment processor has the following method to create the error object, which is used within other methods:
abstract class StripeBase extends AbstractPaymentProcessor {
// ...
protected buildError(
message: string,
e: Stripe.StripeRawError | PaymentProcessorError | Error
): PaymentProcessorError {
return {
error: message,
code: "code" in e ? e.code : "",
detail: isPaymentProcessorError(e)
? `${e.error}${EOL}${e.detail ?? ""}`
: "detail" in e
? e.detail
: e.message ?? "",
}
}
// used in other methods
async retrievePayment(
paymentSessionData: Record<string, unknown>
): Promise<
PaymentProcessorError |
PaymentProcessorSessionResponse["session_data"]
> {
try {
// ...
} catch (e) {
return this.buildError(
"An error occurred in retrievePayment",
e
)
}
}
}
Methods
initiatePayment
This method is called either if a region has only one payment provider enabled or when a Payment Session is selected, which occurs when the customer selects their preferred payment method during checkout.
It is used to allow you to make any necessary calls to the third-party provider to initialize the payment. For example, in Stripe this method is used to create a Payment Intent for the customer.
Example
import {
PaymentProcessorContext,
PaymentProcessorSessionResponse,
// ...
} from "@medusajs/medusa"
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async initiatePayment(
context: PaymentProcessorContext
): Promise<
PaymentProcessorError | PaymentProcessorSessionResponse
> {
// assuming client is an initialized client
// communicating with a third-party service.
const clientPayment = await this.client.initiate(context)
return {
session_data: {
id: clientPayment.id
},
}
}
}
Parameters
The context of the payment.
Returns
Either the payment's data or an error object.
updatePayment
This method is used to update the payment session when the payment amount changes. It's called whenever the cart or any of its related data is updated. For example, when a line item is added to the cart or when a shipping method is selected.
Example
import {
PaymentProcessorContext,
PaymentProcessorError,
PaymentProcessorSessionResponse,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async updatePayment(
context: PaymentProcessorContext
): Promise<
void |
PaymentProcessorError |
PaymentProcessorSessionResponse
> {
// assuming client is an initialized client
// communicating with a third-party service.
const paymentId = context.paymentSessionData.id
await this.client.update(paymentId, context)
return {
session_data: context.paymentSessionData
}
}
}
Parameters
The context of the payment.
Returns
Either the payment's data or an error object.
refundPayment
This method is used to refund an order’s payment. This is typically triggered manually by the store operator from the admin. The refund amount might be the total order amount or part of it.
This method is also used for refunding payments of a swap or a claim of an order, or when a request is sent to the Refund Payment API Route.
You can utilize this method to interact with the third-party provider and perform any actions necessary to refund the payment.
Example
import {
PaymentProcessorError,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async refundPayment(
paymentSessionData: Record<string, unknown>,
refundAmount: number
): Promise<Record<string, unknown> | PaymentProcessorError> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
const refundData = this.client.refund(paymentId, refundAmount)
return {
id: paymentId,
...refundData
}
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of a Payment.refundAmount
numberRequiredReturns
Either an error object or a value that's stored in the data
field of the Payment.
data
field of the Payment.authorizePayment
This method is used to authorize payment using the Payment Session of an order. This is called when the cart is completed and before the order is created.
This method is also used for authorizing payments of a swap of an order and when authorizing sessions in a payment collection. You can interact with a third-party provider and perform any actions necessary to authorize the payment.
The payment authorization might require additional action from the customer before it is declared authorized. Once that additional action is performed,
the authorizePayment
method will be called again to validate that the payment is now fully authorized. So, make sure to implement it for this case as well, if necessary.
Once the payment is authorized successfully and the Payment Session status is set to authorized
, the associated order or swap can then be placed or created.
If the payment authorization fails, then an error will be thrown and the order will not be created.
The payment authorization status is determined using the getPaymentStatus method. If the status is requires_more
, then it means additional actions are required
from the customer. If you try to create the order with a status that isn't authorized
, the process will fail.
Example
import {
PaymentProcessorError,
PaymentSessionStatus,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async authorizePayment(
paymentSessionData: Record<string, unknown>,
context: Record<string, unknown>
): Promise<
PaymentProcessorError |
{
status: PaymentSessionStatus;
data: Record<string, unknown>;
}
> {
try {
await this.client.authorize(paymentSessionData.id)
return {
status: PaymentSessionStatus.AUTHORIZED,
data: {
id: paymentSessionData.id
}
}
} catch (e) {
return {
error: e.message
}
}
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of the payment session.context
Record<string, unknown>Requiredip
: The customer’s IP.idempotency_key
: The Idempotency Key that is associated with the current cart. It is useful when retrying payments, retrying checkout at a failed point, or for payments that require additional actions from the customer.cart_id
: The ID of a cart. This is only during operations like placing an order or creating a swap.
Returns
The authorization details or an error object.
capturePayment
This method is used to capture the payment amount of an order. This is typically triggered manually by the store operator from the admin.
This method is also used for capturing payments of a swap of an order, or when a request is sent to the Capture Payment API Route.
You can utilize this method to interact with the third-party provider and perform any actions necessary to capture the payment.
Example
import {
PaymentProcessorError,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async capturePayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown> | PaymentProcessorError> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
const captureData = this.client.catch(paymentId)
return {
id: paymentId,
...captureData
}
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of the Payment for its first parameter.Returns
Either an error object or a value that's stored in the data
field of the Payment.
data
field of the Payment.deletePayment
This method is used to perform any actions necessary before a Payment Session is deleted. The Payment Session is deleted in one of the following cases:
- When a request is sent to delete the Payment Session.
- When the Payment Session is refreshed. The Payment Session is deleted so that a newer one is initialized instead.
- When the Payment Processor is no longer available. This generally happens when the store operator removes it from the available Payment Processor in the admin.
- When the region of the store is changed based on the cart information and the Payment Processor is not available in the new region.
Example
import {
PaymentProcessorError,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async deletePayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown> | PaymentProcessorError> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
this.client.delete(paymentId)
return {}
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of the Payment Session.Returns
Either an error object or an empty object.
retrievePayment
This method is used to provide a uniform way of retrieving the payment information from the third-party provider. For example, in Stripe’s Payment Processor this method is used to retrieve the payment intent details from Stripe.
Example
import {
PaymentProcessorError
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async retrievePayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown> | PaymentProcessorError> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
return await this.client.retrieve(paymentId)
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of a Payment Session. Make sure to store in the data
field any necessary data that would allow you to retrieve the payment data from the third-party provider.Returns
The payment's data, typically retrieved from a third-party provider.
cancelPayment
This method is used to cancel an order’s payment. This method is typically triggered by one of the following situations:
- Before an order is placed and after the payment is authorized, an inventory check is done on products to ensure that products are still available for purchase. If the inventory check fails for any of the products, the payment is canceled.
- If the store operator cancels the order from the admin.
- When the payment of an order's swap is canceled.
You can utilize this method to interact with the third-party provider and perform any actions necessary to cancel the payment.
Example
import {
PaymentProcessorError,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async cancelPayment(
paymentSessionData: Record<string, unknown>
): Promise<Record<string, unknown> | PaymentProcessorError> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
const cancelData = this.client.cancel(paymentId)
return {
id: paymentId,
...cancelData
}
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of the Payment.Returns
Either an error object or a value that's stored in the data
field of the Payment.
data
field of the Payment.getPaymentStatus
This method is used to get the status of a Payment or a Payment Session. Its main usage is within the place order and create swap flows.
If the status returned is not authorized
within these flows, then the payment is considered failed and an error will be thrown, stopping the flow from completion.
Example
import {
PaymentSessionStatus
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
// ...
async getPaymentStatus(
paymentSessionData: Record<string, unknown>
): Promise<PaymentSessionStatus> {
const paymentId = paymentSessionData.id
// assuming client is an initialized client
// communicating with a third-party service.
return await this.client.getStatus(paymentId) as PaymentSessionStatus
}
}
Parameters
paymentSessionData
Record<string, unknown>Requireddata
field of a Payment as a parameter. You can use this data to interact with the third-party provider to check the status of the payment if necessary.Returns
The status of the Payment or Payment Session.
updatePaymentData
This method is used to update the data
field of a payment session. It's called when a request is sent to the
Update Payment Session API Route, or when the CartService
's updatePaymentSession
is used.
This method can also be used to update the data in the third-party payment provider, if necessary.
Example
import {
PaymentProcessorError,
PaymentProviderService,
// ...
} from "@medusajs/medusa"
// ...
class MyPaymentService extends AbstractPaymentProcessor {
protected paymentProviderService: PaymentProviderService
// ...
constructor(container, options) {
super(container)
this.paymentProviderService = container.paymentProviderService
// ...
}
// ...
async updatePaymentData(
sessionId: string,
data: Record<string, unknown>
): Promise<
Record<string, unknown> |
PaymentProcessorError
> {
const paymentSession = await this.paymentProviderService.retrieveSession(sessionId)
// assuming client is an initialized client
// communicating with a third-party service.
const clientPayment = await this.client.update(paymentSession.data.id, data)
return {
id: clientPayment.id
}
}
}
Parameters
sessionId
stringRequireddata
Record<string, unknown>RequiredReturns
the data to store in the data
field of the payment session.
You can keep the data as-is, or make changes to it by communicating with the third-party provider.
data
field of the payment session.
You can keep the data as-is, or make changes to it by communicating with the third-party provider.