chore: add TSDocs to the Payment Module (#6885)

This commit is contained in:
Shahed Nasser authored and GitHub committed 2024-04-05 12:01:36 +02:00
1 parent d345496dbc
commit 4c374e3a14
6 files changed
+1035 -173

No files matched your search

@@ -677,13 +677,13 @@ export abstract class AbstractPaymentProcessor implements PaymentProcessor {
) {} ) {}
/** /**
* @ignore * @ignore
*/ */
static _isPaymentProcessor = true static _isPaymentProcessor = true
/** /**
* @ignore * @ignore
*/ */
static isPaymentProcessor(object): boolean { static isPaymentProcessor(object): boolean {
return object?.constructor?._isPaymentProcessor return object?.constructor?._isPaymentProcessor
} }
+205 -57
View File
@@ -1,6 +1,5 @@
import { BaseFilterable } from "../dal" import { BaseFilterable } from "../dal"
import { OperatorMap } from "../dal/utils" import { OperatorMap } from "../dal/utils"
/* ********** PAYMENT COLLECTION ********** */ /* ********** PAYMENT COLLECTION ********** */
/** /**
* @enum * @enum
@@ -14,12 +13,12 @@ export enum PaymentCollectionStatus {
NOT_PAID = "not_paid", NOT_PAID = "not_paid",
/** /**
* The payment collection is awaiting payment. * The payment sessions in the payment collection are await authorization.
*/ */
AWAITING = "awaiting", AWAITING = "awaiting",
/** /**
* The payment collection is authorized. * The payment sessions in the payment collection are authorized.
*/ */
AUTHORIZED = "authorized", AUTHORIZED = "authorized",
@@ -29,7 +28,7 @@ export enum PaymentCollectionStatus {
PARTIALLY_AUTHORIZED = "partially_authorized", PARTIALLY_AUTHORIZED = "partially_authorized",
/** /**
* The payment collection is canceled. * The payments in the payment collection are canceled.
*/ */
CANCELED = "canceled", CANCELED = "canceled",
} }
@@ -44,18 +43,22 @@ export enum PaymentSessionStatus {
* The payment is authorized. * The payment is authorized.
*/ */
AUTHORIZED = "authorized", AUTHORIZED = "authorized",
/** /**
* The payment is pending. * The payment is pending.
*/ */
PENDING = "pending", PENDING = "pending",
/** /**
* The payment requires an action. * The payment requires an action.
*/ */
REQUIRES_MORE = "requires_more", REQUIRES_MORE = "requires_more",
/** /**
* An error occurred while processing the payment. * An error occurred while processing the payment.
*/ */
ERROR = "error", ERROR = "error",
/** /**
* The payment is canceled. * The payment is canceled.
*/ */
@@ -67,76 +70,76 @@ export enum PaymentSessionStatus {
*/ */
export interface PaymentCollectionDTO { export interface PaymentCollectionDTO {
/** /**
* The ID of the Payment Collection * The ID of the payment collection.
*/ */
id: string id: string
/** /**
* The currency of the payments/sessions associated with payment collection * The ISO 3 character currency code of the payment sessions and payments associated with payment collection.
*/ */
currency_code: string currency_code: string
/** /**
* The id of the region * The id of the associated region.
*/ */
region_id: string region_id: string
/** /**
* The amount * The total amount to be authorized and captured.
*/ */
amount: number amount: number
/** /**
* The amount authorized within associated payment sessions * The amount authorized within the associated payment sessions.
*/ */
authorized_amount?: number authorized_amount?: number
/** /**
* The amount refunded from associated payments * The amount refunded within the associated payments.
*/ */
refunded_amount?: number refunded_amount?: number
/** /**
* When the payment collection was completed * When the payment collection was completed.
*/ */
completed_at?: string | Date completed_at?: string | Date
/** /**
* When the payment collection was created * When the payment collection was created.
*/ */
created_at?: string | Date created_at?: string | Date
/** /**
* When the payment collection was updated * When the payment collection was updated.
*/ */
updated_at?: string | Date updated_at?: string | Date
/** /**
* Holds custom data in key-value pairs * Holds custom data in key-value pairs.
*/ */
metadata?: Record<string, unknown> metadata?: Record<string, unknown>
/** /**
* The status of the payment collection * The status of the payment collection.
*/ */
status: PaymentCollectionStatus status: PaymentCollectionStatus
/** /**
* The payment provider for the payments * The payment provider used to process the associated payment sessions and payments.
* *
* @expandable * @expandable
*/ */
payment_providers: PaymentProviderDTO[] payment_providers: PaymentProviderDTO[]
/** /**
* The associated payment sessions * The associated payment sessions.
* *
* @expandable * @expandable
*/ */
payment_sessions?: PaymentSessionDTO[] payment_sessions?: PaymentSessionDTO[]
/** /**
* The associated payments * The associated payments.
* *
* @expandable * @expandable
*/ */
@@ -169,48 +172,145 @@ export interface FilterablePaymentCollectionProps
updated_at?: OperatorMap<string> updated_at?: OperatorMap<string>
} }
/**
* The filters to apply on the retrieved payment sessions.
*/
export interface FilterablePaymentSessionProps export interface FilterablePaymentSessionProps
extends BaseFilterable<PaymentSessionDTO> { extends BaseFilterable<PaymentSessionDTO> {
/**
* The IDs to filter the payment sessions by.
*/
id?: string | string[] id?: string | string[]
/**
* Filter the payment sessions by their currency code.
*/
currency_code?: string | string[] currency_code?: string | string[]
/**
* Filter the payment sessions by their amount.
*/
amount?: number | OperatorMap<number> amount?: number | OperatorMap<number>
/**
* Filter the payment sessions by the ID of their associated payment provider.
*/
provider_id?: string | string[] provider_id?: string | string[]
/**
* Filter the payment sessions by the ID of their associated payment collection.
*/
payment_collection_id?: string | string[] payment_collection_id?: string | string[]
/**
* Filter the payment sessions by the ID of their associated region.
*/
region_id?: string | string[] | OperatorMap<string> region_id?: string | string[] | OperatorMap<string>
/**
* Filter the payment sessions by their creation date.
*/
created_at?: OperatorMap<string> created_at?: OperatorMap<string>
/**
* Filter the payment sessions by their update date.
*/
updated_at?: OperatorMap<string> updated_at?: OperatorMap<string>
/**
* Filter the payment sessions by their deletion date.
*/
deleted_at?: OperatorMap<string> deleted_at?: OperatorMap<string>
} }
/**
* The filters to apply on the retrieved captures.
*/
export interface FilterableCaptureProps extends BaseFilterable<CaptureDTO> { export interface FilterableCaptureProps extends BaseFilterable<CaptureDTO> {
/**
* The IDs to filter the captures by.
*/
id?: string | string[] id?: string | string[]
/**
* Filter the captures by their currency code.
*/
currency_code?: string | string[] currency_code?: string | string[]
/**
* Filter the captures by their amounts.
*/
amount?: number | OperatorMap<number> amount?: number | OperatorMap<number>
/**
* Filter the captures by the ID of their associated payment.
*/
payment_id?: string | string[] payment_id?: string | string[]
/**
* Filter the captures by their creation date.
*/
created_at?: OperatorMap<string> created_at?: OperatorMap<string>
/**
* Filter the captures by their update date.
*/
updated_at?: OperatorMap<string> updated_at?: OperatorMap<string>
/**
* Filter the captures by their deletion date.
*/
deleted_at?: OperatorMap<string> deleted_at?: OperatorMap<string>
} }
/**
* The filters to apply on the retrieved refunds.
*/
export interface FilterableRefundProps extends BaseFilterable<RefundDTO> { export interface FilterableRefundProps extends BaseFilterable<RefundDTO> {
/**
* The IDs to filter the refunds by.
*/
id?: string | string[] id?: string | string[]
/**
* Filter the refunds by their currency code.
*/
currency_code?: string | string[] currency_code?: string | string[]
/**
* Filter the refunds by their amount.
*/
amount?: number | OperatorMap<number> amount?: number | OperatorMap<number>
/**
* Filter the refunds by the ID of their associated payment.
*/
payment_id?: string | string[] payment_id?: string | string[]
/**
* Filter the refunds by their creation date.
*/
created_at?: OperatorMap<string> created_at?: OperatorMap<string>
/**
* Filter the refunds by their update date.
*/
updated_at?: OperatorMap<string> updated_at?: OperatorMap<string>
/**
* Filter the refunds by their deletion date.
*/
deleted_at?: OperatorMap<string> deleted_at?: OperatorMap<string>
} }
/* ********** PAYMENT ********** */ /* ********** PAYMENT ********** */
export interface PaymentDTO { export interface PaymentDTO {
/** /**
* The ID of the Payment * The ID of the payment.
*/ */
id: string id: string
/** /**
* The payment amount * The payment's total amount.
*/ */
amount: number amount: number
@@ -220,113 +320,152 @@ export interface PaymentDTO {
authorized_amount?: number authorized_amount?: number
/** /**
* Payment currency * The ISO 3 character currency code of the payment.
*/ */
currency_code: string currency_code: string
/** /**
* The ID of payment provider * The ID of the associated payment provider.
*/ */
provider_id: string provider_id: string
/** /**
* The associated cart's ID. * The ID of the associated cart.
*/ */
cart_id?: string cart_id?: string
/** /**
* The associated order's ID. * The ID of the associated order.
*/ */
order_id?: string order_id?: string
/** /**
* The associated order edit's ID. * The ID of the associated order edit.
*/ */
order_edit_id?: string order_edit_id?: string
/** /**
* The associated customer's ID. * The ID of the associated customer.
*/ */
customer_id?: string customer_id?: string
/** /**
* Payment provider data * The data relevant for the payment provider to process the payment.
*/ */
data?: Record<string, unknown> data?: Record<string, unknown>
/** /**
* When the payment collection was created * When the payment was created.
*/ */
created_at?: string | Date created_at?: string | Date
/** /**
* When the payment collection was updated * When the payment was updated.
*/ */
updated_at?: string | Date updated_at?: string | Date
/** /**
* When the payment was captured * When the payment was captured.
*/ */
captured_at?: string | Date captured_at?: string | Date
/** /**
* When the payment was canceled * When the payment was canceled.
*/ */
canceled_at?: string | Date canceled_at?: string | Date
/** /**
* The sum of the associated captures * The sum of the associated captures' amounts.
*/ */
captured_amount?: number captured_amount?: number
/** /**
* The sum of the associated refunds * The sum of the associated refunds' amounts.
*/ */
refunded_amount?: number refunded_amount?: number
/** /**
* The associated payment captures * The associated captures.
* *
* @expandable * @expandable
*/ */
captures?: CaptureDTO[] captures?: CaptureDTO[]
/** /**
* The associated refunds of the payment * The associated refunds.
* *
* @expandable * @expandable
*/ */
refunds?: RefundDTO[] refunds?: RefundDTO[]
/** /**
* The payment collection the payment is associated with * The associated payment collection.
* *
* @expandable * @expandable
*/ */
payment_collection?: PaymentCollectionDTO payment_collection?: PaymentCollectionDTO
/** /**
* The payment session from which the payment is created * The payment session from which the payment is created.
* *
* @expandable * @expandable
*/ */
payment_session?: PaymentSessionDTO payment_session?: PaymentSessionDTO
} }
/**
* The filters to apply on the retrieved payments.
*/
export interface FilterablePaymentProps export interface FilterablePaymentProps
extends BaseFilterable<FilterablePaymentProps> { extends BaseFilterable<FilterablePaymentProps> {
/**
* The IDs to filter the payments by.
*/
id?: string | string[] id?: string | string[]
/**
* Filter the payments by the ID of their associated payment session.
*/
session_id?: string | string[] | OperatorMap<string> session_id?: string | string[] | OperatorMap<string>
/**
* Filter the payments by the ID of their associated customer.
*/
customer_id?: string | string[] | OperatorMap<string> customer_id?: string | string[] | OperatorMap<string>
/**
* Filter the payments by the ID of their associated cart.
*/
cart_id?: string | string[] | OperatorMap<string> cart_id?: string | string[] | OperatorMap<string>
/**
* Filter the payments by the ID of their associated order.
*/
order_id?: string | string[] | OperatorMap<string> order_id?: string | string[] | OperatorMap<string>
/**
* Filter the payments by the ID of their associated order edit.
*/
order_edit_id?: string | string[] | OperatorMap<string> order_edit_id?: string | string[] | OperatorMap<string>
/**
* Filter the payments by their creation date.
*/
created_at?: OperatorMap<string> created_at?: OperatorMap<string>
/**
* Filter the payments by their update date.
*/
updated_at?: OperatorMap<string> updated_at?: OperatorMap<string>
/**
* Filter the payments by their capture date.
*/
captured_at?: OperatorMap<string> captured_at?: OperatorMap<string>
/**
* Filter the payments by their cancelation date.
*/
canceled_at?: OperatorMap<string> canceled_at?: OperatorMap<string>
} }
@@ -335,12 +474,12 @@ export interface FilterablePaymentProps
*/ */
export interface CaptureDTO { export interface CaptureDTO {
/** /**
* The ID of the Capture * The ID of the capture.
*/ */
id: string id: string
/** /**
* Captured amount * The captured amount.
*/ */
amount: number amount: number
@@ -350,7 +489,8 @@ export interface CaptureDTO {
created_at: Date created_at: Date
/** /**
* Who the capture was created by. * Who the capture was created by. For example,
* the ID of a user.
*/ */
created_by?: string created_by?: string
@@ -365,12 +505,12 @@ export interface CaptureDTO {
*/ */
export interface RefundDTO { export interface RefundDTO {
/** /**
* The ID of the Refund * The ID of the refund
*/ */
id: string id: string
/** /**
* Refunded amount * The refunded amount.
*/ */
amount: number amount: number
@@ -380,7 +520,8 @@ export interface RefundDTO {
created_at: Date created_at: Date
/** /**
* Who created the refund. * Who created the refund. For example,
* the user's ID.
*/ */
created_by?: string created_by?: string
@@ -389,57 +530,61 @@ export interface RefundDTO {
*/ */
payment: PaymentDTO payment: PaymentDTO
} }
/* ********** PAYMENT SESSION ********** */
/* ********** PAYMENT ********** */ /**
* The payment session details.
*/
export interface PaymentSessionDTO { export interface PaymentSessionDTO {
/** /**
* The ID of the Payment Session * The ID of the payment session.
*/ */
id: string id: string
/** /**
* The amount * The amount to authorize.
*/ */
amount: number amount: number
/** /**
* Payment session currency * The 3 character currency code of the payment session.
*/ */
currency_code: string currency_code: string
/** /**
* The ID of payment provider * The ID of the associated payment provider.
*/ */
provider_id: string provider_id: string
/** /**
* Payment provider data * The data necessary for the payment provider to process the payment session.
*/ */
data: Record<string, unknown> data: Record<string, unknown>
/** /**
* Payment session context * The context necessary for the payment provider.
*/ */
context?: Record<string, unknown> context?: Record<string, unknown>
/** /**
* The status of the payment session * The status of the payment session.
*/ */
status: PaymentSessionStatus status: PaymentSessionStatus
/** /**
* When the session was authorized * When the payment session was authorized.
*/ */
authorized_at?: Date authorized_at?: Date
/** /**
* The payment collection the session is associated with * The payment collection the session is associated with.
*
* @expandable * @expandable
*/ */
payment_collection?: PaymentCollectionDTO payment_collection?: PaymentCollectionDTO
/** /**
* The payment created from the session * The payment created from the session.
*
* @expandable * @expandable
*/ */
payment?: PaymentDTO payment?: PaymentDTO
@@ -460,6 +605,9 @@ export interface PaymentProviderDTO {
is_enabled: string is_enabled: string
} }
/**
* The filters to apply on the retrieved payment providers.
*/
export interface FilterablePaymentProviderProps export interface FilterablePaymentProviderProps
extends BaseFilterable<PaymentProviderDTO> { extends BaseFilterable<PaymentProviderDTO> {
/** /**
@@ -468,7 +616,7 @@ export interface FilterablePaymentProviderProps
id?: string | string[] | OperatorMap<string | string[]> id?: string | string[] | OperatorMap<string | string[]>
/** /**
* Filter by enabled status * Filter by whether the payment provider is enabled.
*/ */
is_enabled?: boolean is_enabled?: boolean
} }
+77 -17
View File
@@ -10,7 +10,7 @@ export interface CreatePaymentCollectionDTO {
region_id: string region_id: string
/** /**
* The currency code of the payment collection. * The ISO 3 character currency code of the payment collection.
*/ */
currency_code: string currency_code: string
@@ -36,11 +36,33 @@ export interface UpdatePaymentCollectionDTO
id: string id: string
} }
/**
* The attributes in the payment collection to be created or updated.
*/
export interface UpsertPaymentCollectionDTO { export interface UpsertPaymentCollectionDTO {
/**
* The ID of the payment collection.
*/
id?: string id?: string
/**
* The associated region's ID.
*/
region_id?: string region_id?: string
/**
* The ISO 3 character currency code of the payment collection.
*/
currency_code?: string currency_code?: string
/**
* The amount of the payment collection.
*/
amount?: number amount?: number
/**
* Holds custom data in key-value pairs.
*/
metadata?: Record<string, unknown> metadata?: Record<string, unknown>
} }
@@ -48,9 +70,24 @@ export interface UpsertPaymentCollectionDTO {
* The attributes to update in the payment collection. * The attributes to update in the payment collection.
*/ */
export interface PaymentCollectionUpdatableFields { export interface PaymentCollectionUpdatableFields {
/**
* The associated region's ID.
*/
region_id?: string region_id?: string
/**
* {The ISO 3 character currency code of the payment collection.
*/
currency_code?: string currency_code?: string
/**
* The amount of the payment collection.
*/
amount?: number amount?: number
/**
* Holds custom data in key-value pairs.
*/
metadata?: Record<string, unknown> metadata?: Record<string, unknown>
} }
@@ -64,7 +101,7 @@ export interface CreatePaymentDTO {
amount: number amount: number
/** /**
* The currency code of the payment. * The ISO 3 character currency code of the payment.
*/ */
currency_code: string currency_code: string
@@ -74,12 +111,12 @@ export interface CreatePaymentDTO {
provider_id: string provider_id: string
/** /**
* The data of the payment. * The data necessary for the associated payment provider to process the payment.
*/ */
data: Record<string, unknown> data: Record<string, unknown>
/** /**
* The associated payment session's ID. * The ID of the payment session this payment was created from.
*/ */
payment_session_id: string payment_session_id: string
@@ -154,7 +191,8 @@ export interface CreateCaptureDTO {
payment_id: string payment_id: string
/** /**
* The captured by of the capture. * Who captured the payment. For example,
* a user's ID.
*/ */
captured_by?: string captured_by?: string
} }
@@ -174,7 +212,8 @@ export interface CreateRefundDTO {
payment_id: string payment_id: string
/** /**
* The created by of the refund. * Who refunded the payment. For example,
* a user's ID.
*/ */
created_by?: string created_by?: string
} }
@@ -187,20 +226,24 @@ export interface CreatePaymentSessionDTO {
* The provider's ID. * The provider's ID.
*/ */
provider_id: string provider_id: string
/** /**
* The selected currency code. * The ISO 3 character currency code of the payment session.
*/ */
currency_code: string currency_code: string
/** /**
* The payment's amount. * The amount to be authorized.
*/ */
amount: number amount: number
/** /**
* The value of the payment session's `data` field. * Necessary data for the associated payment provider to process the payment.
*/ */
data: Record<string, unknown> data: Record<string, unknown>
/** /**
* The payment session's context. * Necessary context data for the associated payment provider.
*/ */
context?: PaymentProviderContext context?: PaymentProviderContext
} }
@@ -213,20 +256,24 @@ export interface UpdatePaymentSessionDTO {
* The payment session's ID. * The payment session's ID.
*/ */
id: string id: string
/** /**
* The value of the payment session's `data` field. * Necessary data for the associated payment provider to process the payment.
*/ */
data: Record<string, unknown> data: Record<string, unknown>
/** /**
* The selected currency code. * The ISO 3 character currency code.
*/ */
currency_code: string currency_code: string
/** /**
* The payment's amount. * The amount to be authorized.
*/ */
amount: number amount: number
/** /**
* The payment session's context. * Necessary context data for the associated payment provider.
*/ */
context?: PaymentProviderContext context?: PaymentProviderContext
} }
@@ -239,6 +286,7 @@ export interface CreatePaymentProviderDTO {
* The provider's ID. * The provider's ID.
*/ */
id: string id: string
/** /**
* Whether the provider is enabled. * Whether the provider is enabled.
*/ */
@@ -246,19 +294,31 @@ export interface CreatePaymentProviderDTO {
} }
/** /**
* Webhook * The details of the webhook event payload.
*/ */
export interface ProviderWebhookPayload { export interface ProviderWebhookPayload {
/**
* The ID of the provider to pass the webhook event payload to.
*/
provider: string provider: string
/**
* The webhook event payload passed to the specified provider.
*/
payload: { payload: {
/** /**
* Parsed webhook body * The parsed webhook body.
*/ */
data: Record<string, unknown> data: Record<string, unknown>
/** /**
* Raw request body * The raw webhook request body.
*/ */
rawData: string | Buffer rawData: string | Buffer
/**
* The headers of the webhook request.
*/
headers: Record<string, unknown> headers: Record<string, unknown>
} }
} }
+146 -43
View File
@@ -3,8 +3,14 @@ import { CustomerDTO } from "../customer"
import { PaymentSessionStatus } from "./common" import { PaymentSessionStatus } from "./common"
import { ProviderWebhookPayload } from "./mutations" import { ProviderWebhookPayload } from "./mutations"
/**
* The address of the payment.
*/
export type PaymentAddressDTO = Partial<AddressDTO> export type PaymentAddressDTO = Partial<AddressDTO>
/**
* The customer associated with the payment.
*/
export type PaymentCustomerDTO = Partial<CustomerDTO> export type PaymentCustomerDTO = Partial<CustomerDTO>
/** /**
@@ -15,14 +21,17 @@ export enum PaymentActions {
* Payment session has been authorized and there are available funds for capture. * Payment session has been authorized and there are available funds for capture.
*/ */
AUTHORIZED = "authorized", AUTHORIZED = "authorized",
/** /**
* Payment was successful and the mount is captured. * Payment was successful and the mount is captured.
*/ */
SUCCESSFUL = "captured", SUCCESSFUL = "captured",
/** /**
* Payment failed. * Payment failed.
*/ */
FAILED = "failed", FAILED = "failed",
/** /**
* Received an event that is not processable. * Received an event that is not processable.
*/ */
@@ -32,41 +41,82 @@ export enum PaymentActions {
/** /**
* @interface * @interface
* *
* A payment's context. * Context data provided to the payment provider when authorizing a payment session.
*/ */
export type PaymentProviderContext = { export type PaymentProviderContext = {
/** /**
* The payment's billing address. * The payment's billing address.
*/ */
billing_address?: PaymentAddressDTO billing_address?: PaymentAddressDTO
/** /**
* The customer's email. * The associated customer's email.
*/ */
email?: string email?: string
/** /**
* The ID of the resource the payment is associated with i.e. the ID of the PaymentSession in Medusa * The ID of the resource the payment is associated with. For example, the ID of the payment session.
*/ */
resource_id?: string resource_id?: string
/** /**
* The customer associated with this payment. * The customer associated with this payment.
*/ */
customer?: PaymentCustomerDTO customer?: PaymentCustomerDTO
/** /**
* The extra fields specific to the provider session. * The extra fields specific to the provider session.
*/ */
extra?: Record<string, unknown> extra?: Record<string, unknown>
} }
/**
* @interface
*
* The data used initiate a payment in a provider when a payment
* session is created.
*/
export type CreatePaymentProviderSession = { export type CreatePaymentProviderSession = {
/**
* A context necessary for the payment provider.
*/
context: PaymentProviderContext context: PaymentProviderContext
/**
* The amount to be authorized.
*/
amount: number amount: number
/**
* The ISO 3 character currency code.
*/
currency_code: string currency_code: string
} }
/**
* @interface
*
* The attributes to update a payment related to a payment session in a provider.
*/
export type UpdatePaymentProviderSession = { export type UpdatePaymentProviderSession = {
/**
* A payment's context.
*/
context: PaymentProviderContext context: PaymentProviderContext
/**
* The `data` field of the payment session.
*/
data: Record<string, unknown> data: Record<string, unknown>
/**
* The payment session's amount.
*/
amount: number amount: number
/**
* The ISO 3 character code of the payment session.
*/
currency_code: string currency_code: string
} }
@@ -83,19 +133,38 @@ export type PaymentProviderSessionResponse = {
data: Record<string, unknown> data: Record<string, unknown>
} }
/**
* @interface
*
* The successful result of authorizing a payment session using a payment provider.
*/
export type PaymentProviderAuthorizeResponse = { export type PaymentProviderAuthorizeResponse = {
/** /**
* The status of the payment, which will be stored in the payment session's `status` field. * The status of the payment, which will be stored in the payment session's `status` field.
*/ */
status: PaymentSessionStatus status: PaymentSessionStatus
/** /**
* The `data` to be stored in the payment session's `data` field. * The `data` to be stored in the payment session's `data` field.
*/ */
data: PaymentProviderSessionResponse["data"] data: PaymentProviderSessionResponse["data"]
} }
/**
* @interface
*
* The details of which payment provider to use to perform an action, and what
* data to be passed to that provider.
*/
export type PaymentProviderDataInput = { export type PaymentProviderDataInput = {
/**
* The ID of the provider to be used to perform an action.
*/
provider_id: string provider_id: string
/**
* The data to be passed to the provider.
*/
data: Record<string, unknown> data: Record<string, unknown>
} }
@@ -107,27 +176,57 @@ export interface PaymentProviderError {
* The error message * The error message
*/ */
error: string error: string
/** /**
* The error code. * The error code.
*/ */
code?: string code?: string
/** /**
* Any additional helpful details. * Any additional helpful details.
*/ */
detail?: any detail?: any
} }
/**
* @interface
*
* The details of an action to be performed as a result of a received webhook event.
*/
export type WebhookActionData = { export type WebhookActionData = {
/**
* The associated resource's ID. For example,
* a payment session's ID.
*/
resource_id: string resource_id: string
/**
* The amount to be captured or authorized (based on the action's type.)
*/
amount: number amount: number
} }
/**
* @interface
*
* The actions that the payment provider informs the Payment Module to perform.
*/
export type WebhookActionResult = export type WebhookActionResult =
| { | {
/**
* Received an event that is not processable.
*/
action: PaymentActions.NOT_SUPPORTED action: PaymentActions.NOT_SUPPORTED
} }
| { | {
/**
* Normalized events from payment provider to internal payment module events.
*/
action: PaymentActions action: PaymentActions
/**
* The webhook action's details.
*/
data: WebhookActionData data: WebhookActionData
} }
@@ -140,19 +239,22 @@ export interface IPaymentProvider {
getIdentifier(): string getIdentifier(): string
/** /**
* Make 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. * This methods sends a request to the third-party provider to initialize the payment. It's called when the payment session is created.
* *
* @param {CreatePaymentProviderSession} context * For example, in the Stripe provider, this method is used to create a Payment Intent for the customer.
* @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse>} Either the payment's data or an error object. *
* @param {CreatePaymentProviderSession} data - The data necessary to initiate the payment.
* @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse>} Either the payment's data, which is stored in the `data` field
* of the payment session, or an error object.
*/ */
initiatePayment( initiatePayment(
data: CreatePaymentProviderSession data: CreatePaymentProviderSession
): Promise<PaymentProviderError | PaymentProviderSessionResponse> ): Promise<PaymentProviderError | PaymentProviderSessionResponse>
/** /**
* This method is used to update the payment session. * This method is used to update a payment associated with a session in the third-party provider.
* *
* @param {UpdatePaymentProviderSession} context * @param {UpdatePaymentProviderSession} context - The data related to the update.
* @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse | void>} Either the payment's data or an error object. * @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse | void>} Either the payment's data or an error object.
*/ */
updatePayment( updatePayment(
@@ -160,32 +262,26 @@ export interface IPaymentProvider {
): Promise<PaymentProviderError | PaymentProviderSessionResponse> ): Promise<PaymentProviderError | PaymentProviderSessionResponse>
/** /**
* 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: * This method is called before a payment session is deleted. It's used to perform any actions necessary before the deletion.
* *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of the Payment Session. * @param {Record<string, unknown>} paymentSessionData - The `data` field of the Payment Session.
* @returns Either an error object or an empty object. * @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>} Either an error object or an empty object.
*/ */
deletePayment( deletePayment(
paymentSessionData: Record<string, unknown> paymentSessionData: Record<string, unknown>
): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]> ): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>
/** /**
* This method is used to authorize payment using the Payment Session. * This method is called when a payment session should be authorized.
* You can interact with a third-party provider and perform any actions necessary to authorize the payment. * You can interact with a third-party provider and perform the necessary actions 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, * Refer to [this guide](https://docs.medusajs.com/experimental/payment/payment-flow/#3-authorize-payment-session)
* 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. * to learn more about how this fits into the payment flow and how to handle required actions.
*
* :::note
*
* The payment authorization status is determined using the {@link getPaymentStatus} method. If the status is `requires_more`, then it means additional actions are required
* from the customer.
*
* :::
* *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of the payment session. * @param {Record<string, unknown>} paymentSessionData - The `data` field of the payment session.
* @param {Record<string, unknown>} context - The context of the authorization. * @param {Record<string, unknown>} context - The context of the authorization.
* @returns The authorization details or an error object. * @returns {Promise<PaymentProviderError | PaymentProviderAuthorizeResponse>} The authorization details or an error object. If
* the authorization details are returned, the `data` and `status` field are set in the associated payment session.
*/ */
authorizePayment( authorizePayment(
paymentSessionData: Record<string, unknown>, paymentSessionData: Record<string, unknown>,
@@ -193,25 +289,29 @@ export interface IPaymentProvider {
): Promise<PaymentProviderError | PaymentProviderAuthorizeResponse> ): Promise<PaymentProviderError | PaymentProviderAuthorizeResponse>
/** /**
* This method is used to capture the payment amount. This is typically triggered manually by the store operator from the admin. * This method is called when a payment should be captured. The payment is captured in one of the following scenarios:
* *
* You can utilize this method to interact with the third-party provider and perform any actions necessary to capture the payment. * - The payment provider supports automatically capturing the payment after authorization.
* - The merchant requests to capture the payment after its associated payment session was authorized.
* - A webhook event occurred that instructs the payment provider to capture the payment session. Learn more about handing webhook events in [this guide](https://docs.medusajs.com/experimental/payment/webhook-events/)
* *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of the Payment for its first parameter. * In this method, you can interact with the third-party provider and perform any actions necessary to capture the payment.
* @returns Either an error object or a value that's stored in the `data` field of the Payment. *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of the payment.
* @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>} Either an error object or a value that's stored in the `data` field of the payment.
*/ */
capturePayment( capturePayment(
paymentSessionData: Record<string, unknown> paymentSessionData: Record<string, unknown>
): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]> ): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>
/** /**
* This method is used to refund a payment. This is typically triggered manually by the store operator from the admin. The refund amount might be the total amount or part of it. * This method is called when a payment should be refunded. This is typically triggered manually by the merchant.
* *
* You can utilize this method to interact with the third-party provider and perform any actions necessary to refund the payment. * In this method, you can interact with the third-party provider and perform any actions necessary to refund the payment.
* *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of a Payment. * @param {Record<string, unknown>} paymentSessionData - The `data` field of a Payment.
* @param {number} refundAmount - the amount to refund. * @param {number} refundAmount - The amount to refund.
* @returns Either an error object or a value that's stored in the `data` field of the Payment. * @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>} Either an error object or an object that's stored in the `data` field of the payment.
*/ */
refundPayment( refundPayment(
paymentSessionData: Record<string, unknown>, paymentSessionData: Record<string, unknown>,
@@ -220,45 +320,48 @@ export interface IPaymentProvider {
/** /**
* This method is used to provide a uniform way of retrieving the payment information from the third-party provider. * 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 Provider this method is used to retrieve the payment intent details from Stripe. *
* For example, in Stripe’s payment provider this method is used to retrieve the payment intent details from Stripe.
* *
* @param {Record<string, unknown>} paymentSessionData - * @param {Record<string, unknown>} paymentSessionData -
* The `data` 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. * The `data` 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 {Promise<PaymentProviderError | PaymentProviderSessionResponse["session_data"]>} The payment's data, typically retrieved from a third-party provider. * @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse["session_data"]>} Either an error object or the payment's data retrieved from a third-party provider.
*/ */
retrievePayment( retrievePayment(
paymentSessionData: Record<string, unknown> paymentSessionData: Record<string, unknown>
): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]> ): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>
/** /**
* This method is used to cancel a payment. This method is typically triggered by one of the following situations: * This method is called when a payment is canceled.
* *
* You can utilize this method to interact with the third-party provider and perform any actions necessary to cancel the payment. * In this method, you can interact with the third-party provider and perform any actions necessary to cancel the payment.
* *
* @param {Record<string, unknown>} paymentSessionData - The `data` field of the Payment. * @param {Record<string, unknown>} paymentSessionData - The `data` field of the payment.
* @returns Either an error object or a value that's stored in the `data` field of the Payment. * @returns {Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>} Either an error object or a value that's stored in the `data` field of the payment.
*/ */
cancelPayment( cancelPayment(
paymentSessionData: Record<string, unknown> paymentSessionData: Record<string, unknown>
): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]> ): Promise<PaymentProviderError | PaymentProviderSessionResponse["data"]>
/** /**
* This method is used to get the status of a Payment or a Payment Session. * This method is used to get the status of a payment or a payment session.
* *
* @param {Record<string, unknown>} paymentSessionData - * @param {Record<string, unknown>} paymentSessionData -
* The `data` 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. * The `data` 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 {Promise<PaymentSessionStatus>} The status of the Payment or Payment Session. * @returns {Promise<PaymentSessionStatus>} The status of the payment or payment session.
*/ */
getPaymentStatus( getPaymentStatus(
paymentSessionData: Record<string, unknown> paymentSessionData: Record<string, unknown>
): Promise<PaymentSessionStatus> ): Promise<PaymentSessionStatus>
/** /**
* The method is called when å webhook call for this particular provider is received. * The method is called when a webhook event is received for this provider.
* *
* The method is responsible for normalizing the received event and provide * The method is responsible for normalizing the received event and inform the Payment Module of actions to perform, such as authorize or capture payment.
* *
* @param data - object containing provider id and data from the provider * Learn more about handling webhook events in [this guide](https://docs.medusajs.com/experimental/payment/webhook-events/)
*
* @param data - The webhook event's details.
*/ */
getWebhookActionAndData( getWebhookActionAndData(
data: ProviderWebhookPayload["payload"] data: ProviderWebhookPayload["payload"]
+463 -39
View File
@@ -28,7 +28,7 @@ import {
} from "./mutations" } from "./mutations"
/** /**
* The main service interface for the payment module. * The main service interface for the Payment Module.
*/ */
export interface IPaymentModuleService extends IModuleService { export interface IPaymentModuleService extends IModuleService {
/* ********** PAYMENT COLLECTION ********** */ /* ********** PAYMENT COLLECTION ********** */
@@ -41,7 +41,19 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentCollectionDTO[]>} The created payment collections. * @returns {Promise<PaymentCollectionDTO[]>} The created payment collections.
* *
* @example * @example
* {example-code} * const paymentCollections =
* await paymentModuleService.createPaymentCollections([
* {
* region_id: "reg_123",
* currency_code: "usd",
* amount: 3000,
* },
* {
* region_id: "reg_321",
* currency_code: "eur",
* amount: 2000,
* },
* ])
*/ */
createPaymentCollections( createPaymentCollections(
data: CreatePaymentCollectionDTO[], data: CreatePaymentCollectionDTO[],
@@ -56,7 +68,12 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentCollectionDTO>} The created payment collection. * @returns {Promise<PaymentCollectionDTO>} The created payment collection.
* *
* @example * @example
* {example-code} * const paymentCollection =
* await paymentModuleService.createPaymentCollections({
* region_id: "reg_123",
* currency_code: "usd",
* amount: 3000,
* })
*/ */
createPaymentCollections( createPaymentCollections(
data: CreatePaymentCollectionDTO, data: CreatePaymentCollectionDTO,
@@ -76,13 +93,22 @@ export interface IPaymentModuleService extends IModuleService {
* A simple example that retrieves a {type name} by its ID: * A simple example that retrieves a {type name} by its ID:
* *
* ```ts * ```ts
* {example-code} * const paymentCollection =
* await paymentModuleService.retrievePaymentCollection(
* "pay_col_123"
* )
* ``` * ```
* *
* To specify relations that should be retrieved: * To specify relations that should be retrieved:
* *
* ```ts * ```ts
* {example-code} * const paymentCollection =
* await paymentModuleService.retrievePaymentCollection(
* "pay_col_123",
* {
* relations: ["payment_sessions"],
* }
* )
* ``` * ```
* *
* *
@@ -103,22 +129,43 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentCollectionDTO[]>} The list of payment collections. * @returns {Promise<PaymentCollectionDTO[]>} The list of payment collections.
* *
* @example * @example
* To retrieve a list of {type name} using their IDs: * To retrieve a list of payment collections using their IDs:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listPaymentCollections({
* id: ["pay_col_123", "pay_col_321"],
* })
* ``` * ```
* *
* To specify relations that should be retrieved within the {type name}: * To specify relations that should be retrieved within the payment collection:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listPaymentCollections(
* {
* id: ["pay_col_123", "pay_col_321"],
* },
* {
* relations: ["payment_sessions"],
* }
* )
* ``` * ```
* *
* By default, only the first `{default limit}` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listPaymentCollections(
* {
* id: ["pay_col_123", "pay_col_321"],
* },
* {
* relations: ["payment_sessions"],
* take: 20,
* skip: 2,
* }
* )
* ``` * ```
* *
* *
@@ -142,19 +189,40 @@ export interface IPaymentModuleService extends IModuleService {
* To retrieve a list of {type name} using their IDs: * To retrieve a list of {type name} using their IDs:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listAndCountPaymentCollections({
* id: ["pay_col_123", "pay_col_321"],
* })
* ``` * ```
* *
* To specify relations that should be retrieved within the {type name}: * To specify relations that should be retrieved within the {type name}:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listAndCountPaymentCollections(
* {
* id: ["pay_col_123", "pay_col_321"],
* },
* {
* relations: ["payment_sessions"],
* }
* )
* ``` * ```
* *
* By default, only the first `{default limit}` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter: * By default, only the first `{default limit}` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
* *
* ```ts * ```ts
* {example-code} * const paymentCollections =
* await paymentModuleService.listAndCountPaymentCollections(
* {
* id: ["pay_col_123", "pay_col_321"],
* },
* {
* relations: ["payment_sessions"],
* take: 20,
* skip: 2,
* }
* )
* ``` * ```
* *
* *
@@ -165,21 +233,96 @@ export interface IPaymentModuleService extends IModuleService {
sharedContext?: Context sharedContext?: Context
): Promise<[PaymentCollectionDTO[], number]> ): Promise<[PaymentCollectionDTO[], number]>
/**
* This method updates an existing payment collection.
*
* @param {string} paymentCollectionId - The payment collection's ID.
* @param {PaymentCollectionUpdatableFields} data - The attributes to update in the payment collection.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO>} The updated payment collection.
*
* @example
* const paymentCollection =
* await paymentModuleService.updatePaymentCollections(
* "pay_col_123",
* {
* amount: 3000,
* }
* )
*/
updatePaymentCollections( updatePaymentCollections(
paymentCollectionId: string, paymentCollectionId: string,
data: PaymentCollectionUpdatableFields, data: PaymentCollectionUpdatableFields,
sharedContext?: Context sharedContext?: Context
): Promise<PaymentCollectionDTO> ): Promise<PaymentCollectionDTO>
/**
* This method updates existing payment collections matching the specified filters.
*
* @param {FilterablePaymentCollectionProps} selector - The filters specifying which payment collections to update.
* @param {PaymentCollectionUpdatableFields} data - The attributes to update in the payment collections.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO[]>} The updated payment collections.
*
* @example
* const paymentCollections =
* await paymentModuleService.updatePaymentCollections(
* {
* id: ["pay_col_123", "pay_col_321"],
* },
* {
* currency_code: "usd",
* }
* )
*/
updatePaymentCollections( updatePaymentCollections(
selector: FilterablePaymentCollectionProps, selector: FilterablePaymentCollectionProps,
data: PaymentCollectionUpdatableFields, data: PaymentCollectionUpdatableFields,
sharedContext?: Context sharedContext?: Context
): Promise<PaymentCollectionDTO[]> ): Promise<PaymentCollectionDTO[]>
/**
* This method updates or creates payment collections if they don't exist.
*
* @param {UpsertPaymentCollectionDTO[]} data - The attributes in the payment collections to be created or updated. If
* the object includes the `id` field, then the payment collection is updated. Otherise, it's created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO[]>} The created or updated payment collections.
*
* @example
* const paymentCollections =
* await paymentModuleService.upsertPaymentCollections([
* {
* id: "pay_col_123",
* region_id: "reg_123",
* },
* {
* region_id: "reg_123",
* currency_code: "usd",
* amount: 3000,
* },
* ])
*/
upsertPaymentCollections( upsertPaymentCollections(
data: UpsertPaymentCollectionDTO[], data: UpsertPaymentCollectionDTO[],
sharedContext?: Context sharedContext?: Context
): Promise<PaymentCollectionDTO[]> ): Promise<PaymentCollectionDTO[]>
/**
* This method updates or creates a payment collection if it doesn't exist.
*
* @param {UpsertPaymentCollectionDTO} data - The attributes in the payment collection to be created or updated. If the `id`
* field is included, the payment collection is updated. Otherwise, it's created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO>} The created or updated payment collection.
*
* @example
* const paymentCollection =
* await paymentModuleService.upsertPaymentCollections({
* id: "pay_col_123",
* region_id: "reg_123",
* })
*/
upsertPaymentCollections( upsertPaymentCollections(
data: UpsertPaymentCollectionDTO, data: UpsertPaymentCollectionDTO,
sharedContext?: Context sharedContext?: Context
@@ -190,10 +333,13 @@ export interface IPaymentModuleService extends IModuleService {
* *
* @param {string[]} paymentCollectionId - The payment collection's ID. * @param {string[]} paymentCollectionId - The payment collection's ID.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<void>} Resolves when the payment collection is deleted. * @returns {Promise<void>} Resolves when the payment collection is deleted successfully.
* *
* @example * @example
* {example-code} * await paymentModuleService.deletePaymentCollections([
* "pay_col_123",
* "pay_col_321",
* ])
*/ */
deletePaymentCollections( deletePaymentCollections(
paymentCollectionId: string[], paymentCollectionId: string[],
@@ -205,10 +351,12 @@ export interface IPaymentModuleService extends IModuleService {
* *
* @param {string} paymentCollectionId - The payment collection's ID. * @param {string} paymentCollectionId - The payment collection's ID.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<void>} Resolves when the payment collection is deleted. * @returns {Promise<void>} Resolves when the payment collection is deleted successfully.
* *
* @example * @example
* {example-code} * await paymentModuleService.deletePaymentCollections(
* "pay_col_123"
* )
*/ */
deletePaymentCollections( deletePaymentCollections(
paymentCollectionId: string, paymentCollectionId: string,
@@ -216,14 +364,17 @@ export interface IPaymentModuleService extends IModuleService {
): Promise<void> ): Promise<void>
/** /**
* This method completes a payment collection. * This method marks a payment collection as completed by settings its `completed_at` field to the current date and time.
* *
* @param {string} paymentCollectionId - The payment collection's ID. * @param {string} paymentCollectionId - The payment collection's ID.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO>} The payment collection's details. * @returns {Promise<PaymentCollectionDTO>} The payment collection's details.
* *
* @example * @example
* {example-code} * const paymentCollection =
* await paymentModuleService.completePaymentCollections(
* "pay_col_123"
* )
*/ */
completePaymentCollections( completePaymentCollections(
paymentCollectionId: string, paymentCollectionId: string,
@@ -231,14 +382,18 @@ export interface IPaymentModuleService extends IModuleService {
): Promise<PaymentCollectionDTO> ): Promise<PaymentCollectionDTO>
/** /**
* This method completes payment collections. * This method marks payment collections as completed by settings their `completed_at` field to the current date and time.
* *
* @param {string[]} paymentCollectionId - The payment collections' IDs. * @param {string[]} paymentCollectionId - The payment collections' IDs.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentCollectionDTO[]>} The payment collections' details. * @returns {Promise<PaymentCollectionDTO[]>} The payment collections' details.
* *
* @example * @example
* {example-code} * const paymentCollection =
* await paymentModuleService.completePaymentCollections([
* "pay_col_123",
* "pay_col_321",
* ])
*/ */
completePaymentCollections( completePaymentCollections(
paymentCollectionId: string[], paymentCollectionId: string[],
@@ -248,7 +403,7 @@ export interface IPaymentModuleService extends IModuleService {
/* ********** PAYMENT SESSION ********** */ /* ********** PAYMENT SESSION ********** */
/** /**
* This method creates a payment session for a payment collection. * This method creates a payment session in a payment collection.
* *
* @param {string} paymentCollectionId - The ID of the payment collection to create the session for. * @param {string} paymentCollectionId - The ID of the payment collection to create the session for.
* @param {CreatePaymentSessionDTO} data - The details of the payment session. * @param {CreatePaymentSessionDTO} data - The details of the payment session.
@@ -256,7 +411,16 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentCollectionDTO>} The payment collection's details. * @returns {Promise<PaymentCollectionDTO>} The payment collection's details.
* *
* @example * @example
* {example-code} * const paymentSession =
* await paymentModuleService.createPaymentSession(
* "pay_col_1",
* {
* provider_id: "stripe",
* currency_code: "usd",
* amount: 3000,
* data: {},
* }
* )
*/ */
createPaymentSession( createPaymentSession(
paymentCollectionId: string, paymentCollectionId: string,
@@ -272,7 +436,13 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentSessionDTO>} The payment session's details. * @returns {Promise<PaymentSessionDTO>} The payment session's details.
* *
* @example * @example
* {example-code} * const paymentSession =
* await paymentModuleService.updatePaymentSession({
* id: "payses_123",
* currency_code: "usd",
* amount: 3000,
* data: {},
* })
*/ */
updatePaymentSession( updatePaymentSession(
data: UpdatePaymentSessionDTO, data: UpdatePaymentSessionDTO,
@@ -284,23 +454,29 @@ export interface IPaymentModuleService extends IModuleService {
* *
* @param {string} id - The ID of the payment session. * @param {string} id - The ID of the payment session.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<void>} Resolves whent the payment session is deleted. * @returns {Promise<void>} Resolves whent the payment session is deleted successfully.
* *
* @example * @example
* {example-code} * await paymentModuleService.deletePaymentSession("payses_123")
*/ */
deletePaymentSession(id: string, sharedContext?: Context): Promise<void> deletePaymentSession(id: string, sharedContext?: Context): Promise<void>
/** /**
* This method authorizes a payment session. * This method authorizes a payment session using its associated payment provider. This creates a payment that can later be captured.
*
* Learn more about the payment flow in [this guide](https://docs.medusajs.com/experimental/payment/payment-flow/)
* *
* @param {string} id - The payment session's ID. * @param {string} id - The payment session's ID.
* @param {Record<string, unknown>} context - The associated payment provider's context. * @param {Record<string, unknown>} context - Context data to pass to the associated payment provider.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentDTO>} The details of the payment created from the authorized payment session. * @returns {Promise<PaymentDTO>} The created payment.
* *
* @example * @example
* {example-code} * const payment =
* await paymentModuleService.authorizePaymentSession(
* "payses_123",
* {}
* )
*/ */
authorizePaymentSession( authorizePaymentSession(
id: string, id: string,
@@ -308,6 +484,55 @@ export interface IPaymentModuleService extends IModuleService {
sharedContext?: Context sharedContext?: Context
): Promise<PaymentDTO> ): Promise<PaymentDTO>
/**
* This method retrieves a paginated list of payment sessions based on optional filters and configuration.
*
* @param {FilterablePaymentSessionProps} filters - The filters to apply on the retrieved payment sessions.
* @param {FindConfig<PaymentSessionDTO>} config - The configurations determining how the payment session is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a payment session.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentSessionDTO[]>} The list of payment sessions.
*
* @example
* To retrieve a list of payment sessions using their IDs:
*
* ```ts
* const paymentSessions =
* await paymentModuleService.listPaymentSessions({
* id: ["payses_123", "payses_321"],
* })
* ```
*
* To specify relations that should be retrieved within the payment session:
*
* ```ts
* const paymentSessions =
* await paymentModuleService.listPaymentSessions(
* {
* id: ["payses_123", "payses_321"],
* },
* {
* relations: ["payment"],
* }
* )
* ```
*
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const paymentSessions =
* await paymentModuleService.listPaymentSessions(
* {
* id: ["payses_123", "payses_321"],
* },
* {
* relations: ["payment"],
* take: 20,
* skip: 2,
* }
* )
* ```
*/
listPaymentSessions( listPaymentSessions(
filters?: FilterablePaymentSessionProps, filters?: FilterablePaymentSessionProps,
config?: FindConfig<PaymentSessionDTO>, config?: FindConfig<PaymentSessionDTO>,
@@ -326,7 +551,41 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentDTO[]>} A list of payment. * @returns {Promise<PaymentDTO[]>} A list of payment.
* *
* @example * @example
* {example-code} * To retrieve a list of payments using their IDs:
*
* ```ts
* const payments = await paymentModuleService.listPayments({
* id: ["pay_123", "pay_321"],
* })
* ```
*
* To specify relations that should be retrieved within the payment:
*
* ```ts
* const payments = await paymentModuleService.listPayments(
* {
* id: ["pay_123", "pay_321"],
* },
* {
* relations: ["payment_session"],
* }
* )
* ```
*
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const payments = await paymentModuleService.listPayments(
* {
* id: ["pay_123", "pay_321"],
* },
* {
* relations: ["payment_session"],
* take: 20,
* skip: 2,
* }
* )
* ```
*/ */
listPayments( listPayments(
filters?: FilterablePaymentProps, filters?: FilterablePaymentProps,
@@ -342,7 +601,10 @@ export interface IPaymentModuleService extends IModuleService {
* @returns {Promise<PaymentDTO>} The updated payment. * @returns {Promise<PaymentDTO>} The updated payment.
* *
* @example * @example
* {example-code} * const payment = await paymentModuleService.updatePayment({
* id: "pay_123",
* customer_id: "cus_123",
* })
*/ */
updatePayment( updatePayment(
data: UpdatePaymentDTO, data: UpdatePaymentDTO,
@@ -350,14 +612,18 @@ export interface IPaymentModuleService extends IModuleService {
): Promise<PaymentDTO> ): Promise<PaymentDTO>
/** /**
* This method captures a payment. * This method captures a payment using its associated payment provider.
*
* Learn more about the payment flow in [this guide](https://docs.medusajs.com/experimental/payment/payment-flow/)
* *
* @param {CreateCaptureDTO} data - The payment capture to be created. * @param {CreateCaptureDTO} data - The payment capture to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentDTO>} The payment's details. * @returns {Promise<PaymentDTO>} The payment's details.
* *
* @example * @example
* {example-code} * const payment = await paymentModuleService.capturePayment({
* payment_id: "pay_123",
* })
*/ */
capturePayment( capturePayment(
data: CreateCaptureDTO, data: CreateCaptureDTO,
@@ -365,14 +631,17 @@ export interface IPaymentModuleService extends IModuleService {
): Promise<PaymentDTO> ): Promise<PaymentDTO>
/** /**
* This method refunds a payment. * This method refunds a payment using its associated payment provider. An amount can only be refunded if it has been captured first.
* *
* @param {CreateRefundDTO} data - The refund to be created. * @param {CreateRefundDTO} data - The refund to be created.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentDTO>} The payment's details. * @returns {Promise<PaymentDTO>} The payment's details.
* *
* @example * @example
* {example-code} * const payment = await paymentModuleService.refundPayment({
* payment_id: "pay_123",
* amount: 300,
* })
*/ */
refundPayment( refundPayment(
data: CreateRefundDTO, data: CreateRefundDTO,
@@ -380,29 +649,156 @@ export interface IPaymentModuleService extends IModuleService {
): Promise<PaymentDTO> ): Promise<PaymentDTO>
/** /**
* This method cancels a payment * This method cancels a payment.
* *
* @param {string} paymentId - The payment's ID. * @param {string} paymentId - The payment's ID.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module. * @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentDTO>} The payment's details. * @returns {Promise<PaymentDTO>} The payment's details.
* *
* @example * @example
* {example-code} * const payment =
* await paymentModuleService.cancelPayment("pay_123")
*/ */
cancelPayment(paymentId: string, sharedContext?: Context): Promise<PaymentDTO> cancelPayment(paymentId: string, sharedContext?: Context): Promise<PaymentDTO>
/**
* This method retrieves a paginated list of payment providers based on optional filters and configuration.
*
* @param {FilterablePaymentProviderProps} filters - The filters to apply on the retrieved payment providers.
* @param {FindConfig<PaymentProviderDTO>} config - The configurations determining how the payment provider is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a payment provider.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<PaymentProviderDTO[]>} The list of payment providers.
*
* @example
* To retrieve a list of payment providers using their IDs:
*
* ```ts
* const paymentProviders =
* await paymentModuleService.listPaymentProviders({
* id: ["stripe", "system"],
* })
* ```
*
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const paymentProviders =
* await paymentModuleService.listPaymentProviders(
* {
* id: ["stripe", "system"],
* },
* {
* take: 20,
* skip: 2,
* }
* )
* ```
*/
listPaymentProviders( listPaymentProviders(
filters?: FilterablePaymentProviderProps, filters?: FilterablePaymentProviderProps,
config?: FindConfig<PaymentProviderDTO>, config?: FindConfig<PaymentProviderDTO>,
sharedContext?: Context sharedContext?: Context
): Promise<PaymentProviderDTO[]> ): Promise<PaymentProviderDTO[]>
/**
* This method retrieves a paginated list of captures based on optional filters and configuration.
*
* @param {FilterableCaptureProps} filters - The filters to apply on the retrieved captures.
* @param {FindConfig<CaptureDTO>} config - The configurations determining how the capture is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a capture.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<CaptureDTO[]>} The list of captures.
*
* @example
* To retrieve a list of captures using their IDs:
*
* ```ts
* const captures = await paymentModuleService.listCaptures({
* id: ["capt_123", "capt_321"],
* })
* ```
*
* To specify relations that should be retrieved within the capture:
*
* ```ts
* const captures = await paymentModuleService.listCaptures(
* {
* id: ["capt_123", "capt_321"],
* },
* {
* relations: ["payment"],
* }
* )
* ```
*
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const captures = await paymentModuleService.listCaptures(
* {
* id: ["capt_123", "capt_321"],
* },
* {
* relations: ["payment"],
* take: 20,
* skip: 2,
* }
* )
* ```
*/
listCaptures( listCaptures(
filters?: FilterableCaptureProps, filters?: FilterableCaptureProps,
config?: FindConfig<CaptureDTO>, config?: FindConfig<CaptureDTO>,
sharedContext?: Context sharedContext?: Context
): Promise<CaptureDTO[]> ): Promise<CaptureDTO[]>
/**
* This method retrieves a paginated list of refunds based on optional filters and configuration.
*
* @param {FilterableRefundProps} filters - The filters to apply on the retrieved refunds.
* @param {FindConfig<RefundDTO>} config - The configurations determining how the refund is retrieved. Its properties, such as `select` or `relations`, accept the
* attributes or relations associated with a refund.
* @param {Context} sharedContext - A context used to share resources, such as transaction manager, between the application and the module.
* @returns {Promise<RefundDTO[]>} The list of refunds.
*
* @example
* To retrieve a list of refunds using their IDs:
*
* ```ts
* const refunds = await paymentModuleService.listRefunds({
* id: ["ref_123", "ref_321"],
* })
* ```
*
* To specify relations that should be retrieved within the refund:
*
* ```ts
* const refunds = await paymentModuleService.listRefunds(
* {
* id: ["ref_123", "ref_321"],
* },
* {
* relations: ["payment"],
* }
* )
* ```
*
* By default, only the first `15` records are retrieved. You can control pagination by specifying the `skip` and `take` properties of the `config` parameter:
*
* ```ts
* const refunds = await paymentModuleService.listRefunds(
* {
* id: ["ref_123", "ref_321"],
* },
* {
* relations: ["payment"],
* take: 20,
* skip: 2,
* }
* )
* ```
*/
listRefunds( listRefunds(
filters?: FilterableRefundProps, filters?: FilterableRefundProps,
config?: FindConfig<RefundDTO>, config?: FindConfig<RefundDTO>,
@@ -411,17 +807,45 @@ export interface IPaymentModuleService extends IModuleService {
/* ********** HOOKS ********** */ /* ********** HOOKS ********** */
/**
* This method handles a webhook event with the associated payment provider.
*
* Learn more about handling webhook events in [this guide](https://docs.medusajs.com/experimental/payment/webhook-events/)
*
* @param {ProviderWebhookPayload} data - The webhook event's details.
* @returns {Promise<void>} Resolves when the webhook event is handled successfully.
*
* @example
* In the following example, `req` is an instance of `MedusaRequest`:
*
* ```ts
* await paymentModuleService.processEvent({
* provider: "stripe",
* payload: {
* data: req.body,
* rawData: req.rawBody,
* headers: req.headers,
* },
* })
* ```
*/
processEvent(data: ProviderWebhookPayload): Promise<void> processEvent(data: ProviderWebhookPayload): Promise<void>
} }
/**
* The options that the Payment Module accepts.
*/
export interface PaymentModuleOptions { export interface PaymentModuleOptions {
/** /**
* The delay in milliseconds before processing the webhook event. * The delay in milliseconds before processing the webhook event.
*
* @defaultValue 5000 * @defaultValue 5000
*/ */
webhook_delay?: number webhook_delay?: number
/** /**
* The number of times to retry the webhook event processing in case of an error. * The number of times to retry the webhook event processing in case of an error.
*
* @defaultValue 3 * @defaultValue 3
*/ */
webhook_retries?: number webhook_retries?: number
@@ -10,27 +10,154 @@ import {
WebhookActionResult WebhookActionResult
} from "@medusajs/types" } from "@medusajs/types"
/**
* ## Overview
*
* A payment provider is used to handle and process payments, such as authorizing, capturing, and refund payments.
*
* Refer to [this guide](https://docs.medusajs.com/experimental/payment/payment-provider/) to learn more about payment providers.
*
* Refer to [this guide](https://docs.medusajs.com/experimental/payment/payment-flow/) to learn more about the payment flow.
*
* ---
*
* ## How to Create a Payment Provider
*
* A payment provider is a TypeScript or JavaScript class that extends the `AbstractPaymentProvider` class imported from `@medusajsa/utils`.
*
* You can create the payment provider in a module or plugin, then pass that module/plugin in the Payment Module's `providers` option. You can also pass the path to the file
* that defines the provider if it's created in the Medusa application's codebase.
*
* For example:
*
* ```ts
* abstract class MyPayment extends AbstractPaymentProvider<MyConfigurations> {
* // ...
* }
* ```
*
* ---
*
* ## Configuration Type Parameter
*
* The `AbstractPaymentProvider` class accepts an optional type parameter that defines the type of configuration that your payment provider expects.
*
* For example:
*
* ```ts
* interface MyConfigurations {
* apiKey: string
* }
*
* abstract class MyPayment extends AbstractPaymentProvider<MyConfigurations> {
* // ...
* }
* ```
*
* ---
*
* ## Identifier Property
*
* The `PaymentProvider` data model has 2 properties: `id` and `is_enabled`.
*
* ```ts
* class MyPaymentProvider extends AbstractPaymentProvider<MyConfigurations> {
* static identifier = "my-payment"
* // ...
* }
* ```
*
* ---
*
* ## PROVIDER Property
*
* The `PROVIDER` static property is used when registering the provider in the dependency container. Typically, it would have the
* same value as the `identifier` property.
*
* ```ts
* class MyPaymentProvider extends AbstractPaymentProvider<MyConfigurations> {
* static PROVIDER = "my-payment"
* // ...
* }
* ```
*
* ---
*
* ## PaymentProviderError
*
* Before diving into the methods of the Payment Provider, you'll notice that part of the expected return signature of these method includes `PaymentProviderError`.
*
* ```ts
* interface PaymentProviderError {
* error: string
* code?: string
* detail?: any
* }
* ```
*
* While implementing the Payment Provider's methods, if you need to inform the Payment Module that an error occurred at a certain stage,
* return an object having the attributes defined in the `PaymentProviderError` interface.
*
* For example, the Stripe payment provider has the following method to create the error object, which is used within other methods:
*
* ```ts
* abstract class StripeBase extends AbstractPaymentProvider {
* // ...
* protected buildError(
* message: string,
* error: Stripe.StripeRawError | PaymentProviderError | Error
* ): PaymentProviderError {
* return {
* error: message,
* code: "code" in error ? error.code : "unknown",
* detail: isPaymentProviderError(error)
* ? `${error.error}${EOL}${error.detail ?? ""}`
* : "detail" in error
* ? error.detail
* : error.message ?? "",
* }
* }
*
* // used in other methods
* async retrievePayment(
* paymentSessionData: Record<string, unknown>
* ): Promise<
* PaymentProviderError |
* PaymentProviderSessionResponse["session_data"]
* > {
* try {
* // ...
* } catch (e) {
* return this.buildError(
* "An error occurred in retrievePayment",
* e
* )
* }
* }
* }
* ```
*
*/
export abstract class AbstractPaymentProvider<TConfig = Record<string, unknown>> export abstract class AbstractPaymentProvider<TConfig = Record<string, unknown>>
implements IPaymentProvider implements IPaymentProvider
{ {
/** /**
* You can use the `constructor` of your Payment Provider to have access to different services in Medusa through [dependency injection](https://docs.medusajs.com/development/fundamentals/dependency-injection). * You can use the `constructor` of your Payment Provider to have access to resources in your application through the [dependency container](https://docs.medusajs.com/development/fundamentals/dependency-injection).
* *
* You can also use the constructor to initialize your integration with the third-party provider. For example, if you use a client to connect to the third-party provider’s APIs, * You can also use the constructor to initialize your integration with the third-party provider. For example, if you use a client to connect to the third-party provider’s APIs,
* you can initialize it in the constructor and use it in other methods in the service. * you can initialize it in the constructor and use it in other methods in the service.
* *
* Additionally, if you’re creating your Payment Provider as an external plugin to be installed on any Medusa backend and you want to access the options added for the plugin, * The payment provider also can access the configurations of the module or plugin it's created in as a second parameter.
* you can access it in the constructor. The options are passed as a second parameter.
* *
* @param {MedusaContainer} container - An instance of `MedusaContainer` that allows you to access other resources, such as services, in your Medusa backend through [dependency injection](https://docs.medusajs.com/development/fundamentals/dependency-injection) * @param {MedusaContainer} container - An instance of `MedusaContainer` that allows you to access other resources in the [dependency container](https://docs.medusajs.com/development/fundamentals/dependency-injection)
* @param {Record<string, unknown>} config - If this payment processor is created in a plugin, the plugin's options are passed in this parameter. * @param {Record<string, unknown>} config - If this provider processor is created in a module or plugin, their options are passed in this parameter.
* *
* @example * @example
* ```ts * ```ts
* class MyPaymentService extends AbstractPaymentProvider { * class MyPaymentProvider extends AbstractPaymentProvider<MyConfigurations> {
* // ... * // ...
* constructor(container, options) { * constructor(container, config) {
* super(container) * super(container, config)
* // you can access options here * // you can access options here
* *
* // you can also initialize a client that * // you can also initialize a client that
@@ -59,13 +186,10 @@ export abstract class AbstractPaymentProvider<TConfig = Record<string, unknown>>
} }
/** /**
* The `PaymentProvider` entity has 2 properties: `id` and `is_installed`. The `identifier` property in the payment provider service is used when the payment provider is added to the database. * The `PaymentProvider` data model has 2 properties: `id` and `is_enabled`.
*
* The value of this property is also used to reference the payment provider throughout Medusa.
* For example, it is used to [add a payment provider](https://docs.medusajs.com/api/admin#regions_postregionsregionpaymentproviders) to a region.
* *
* ```ts * ```ts
* class MyPaymentService extends AbstractPaymentProvider { * class MyPaymentProvider extends AbstractPaymentProvider<MyConfigurations> {
* static identifier = "my-payment" * static identifier = "my-payment"
* // ... * // ...
* } * }
@@ -137,6 +261,9 @@ export abstract class AbstractPaymentProvider<TConfig = Record<string, unknown>>
): Promise<WebhookActionResult> ): Promise<WebhookActionResult>
} }
/**
* @ignore
*/
export function isPaymentProviderError(obj: any): obj is PaymentProviderError { export function isPaymentProviderError(obj: any): obj is PaymentProviderError {
return ( return (
obj && obj &&