Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

fix(core): own the payment webhook so carts complete as split orders (#1418)

Viktor Holikef0bf397457b
diff --git a/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts b/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts
new file mode 100644
index 000000000..904f6e22c
--- /dev/null
+++ b/integration-tests/http/payment/payment-webhook-cart-completion.spec.ts
@@ -0,0 +1,399 @@
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ IRegionModuleService,
+ ISalesChannelModuleService,
+ MedusaContainer,
+} from "@medusajs/framework/types"
+import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
+import { MercurModules, SellerStatus } from "@mercurjs/types"
+import { createSellerUser } from "../../helpers/create-seller-user"
+import { createCustomerUser } from "../../helpers/create-customer-user"
+import { createVendorProduct } from "../../helpers/create-product"
+import {
+ generatePublishableKey,
+ generateStoreHeaders,
+} from "../../helpers/create-admin-user"
+
+jest.setTimeout(180000)
+
+const approveSeller = async (container: MedusaContainer, sellerId: string) => {
+ const sellerModule: any = container.resolve(MercurModules.SELLER)
+ await sellerModule.updateSellers({ id: sellerId, status: SellerStatus.OPEN })
+}
+
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Payment webhook - cart completion", () => {
+ let appContainer: MedusaContainer
+ let sellerSeed: any
+ let storeHeaders: any
+ let region: any
+ let salesChannel: any
+ let counter = 0
+
+ const seedSellerOfferWithShipping = async (opts: {
+ email: string
+ name: string
+ }) => {
+ const result = await createSellerUser(appContainer, {
+ email: opts.email,
+ name: opts.name,
+ })
+ await approveSeller(appContainer, (result.seller as any).id)
+ const headers = result.headers
+ const tag = `_${opts.name}_${Date.now()}_${++counter}`
+
+ const stockLocation = (
+ await api.post(
+ `/vendor/stock-locations`,
+ { name: `Warehouse${tag}` },
+ headers
+ )
+ ).data.stock_location
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-sets`,
+ { name: `FS${tag}`, type: "shipping" },
+ headers
+ )
+ const fulfillmentSet = (
+ await api.get(
+ `/vendor/stock-locations/${stockLocation.id}?fields=*fulfillment_sets`,
+ headers
+ )
+ ).data.stock_location.fulfillment_sets[0]
+ const serviceZone = (
+ await api.post(
+ `/vendor/fulfillment-sets/${fulfillmentSet.id}/service-zones`,
+ {
+ name: `SZ${tag}`,
+ geo_zones: [{ type: "country", country_code: "us" }],
+ },
+ headers
+ )
+ ).data.fulfillment_set.service_zones.find(
+ (z: any) => z.name === `SZ${tag}`
+ )
+ const shippingProfile = (
+ await api.post(
+ `/vendor/shipping-profiles`,
+ { name: `SP${tag}`, type: "default" },
+ headers
+ )
+ ).data.shipping_profile
+
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/fulfillment-providers`,
+ { add: ["manual_manual"] },
+ headers
+ )
+ await api.post(
+ `/vendor/stock-locations/${stockLocation.id}/sales-channels`,
+ { add: [salesChannel.id] },
+ headers
+ )
+ await api.post(
+ `/vendor/shipping-options`,
+ {
+ name: `Ship${tag}`,
+ service_zone_id: serviceZone.id,
+ shipping_profile_id: shippingProfile.id,
+ provider_id: "manual_manual",
+ price_type: "flat",
+ type: {
+ label: "Standard",
+ description: "Standard",
+ code: "standard",
+ },
+ prices: [{ currency_code: "usd", amount: 500 }],
+ rules: [
+ {
+ attribute: "enabled_in_store",
+ value: "true",
+ operator: "eq",
+ },
+ ],
+ },
+ headers
+ )
+
+ const product = await createVendorProduct(api, headers, {
+ title: `Prod${tag}`,
+ sku: `V${tag}`,
+ })
+
+ await api.post(
+ `/vendor/sales-channels/${salesChannel.id}/products`,
+ { add: [product.id] },
+ headers
+ )
+
+ const offer = (
+ await api.post(
+ `/vendor/offers`,
+ {
+ sku: `OF${tag}`,
+ variant_id: product.variants[0].id,
+ shipping_profile_id: shippingProfile.id,
+ inventory_items: [
+ {
+ title: `Inv${tag}`,
+ required_quantity: 1,
+ stock_levels: [
+ {
+ location_id: stockLocation.id,
+ stocked_quantity: 10,
+ },
+ ],
+ },
+ ],
+ prices: [{ amount: 2500, currency_code: "usd" }],
+ },
+ headers
+ )
+ ).data.offer
+
+ return { offer }
+ }
+
+ const seedReadyCart = async (offerId: string) => {
+ const cart = (
+ await api.post(
+ `/store/carts`,
+ {
+ region_id: region.id,
+ sales_channel_id: salesChannel.id,
+ currency_code: "usd",
+ },
+ storeHeaders
+ )
+ ).data.cart
+
+ await api.post(
+ `/store/carts/${cart.id}/line-items`,
+ { offer_id: offerId, quantity: 1 },
+ storeHeaders
+ )
+
+ const address = {
+ first_name: "Buyer",
+ last_name: "Test",
+ address_1: "123 Main St",
+ city: "New York",
+ country_code: "us",
+ postal_code: "10001",
+ }
+ await api.post(
+ `/store/carts/${cart.id}`,
+ {
+ email: "[email protected]",
+ shipping_address: address,
+ billing_address: address,
+ },
+ storeHeaders
+ )
+
+ const shippingOptionsResp = await api.get(
+ `/store/shipping-options?cart_id=${cart.id}`,
+ storeHeaders
+ )
+ const allOptions = Object.values(
+ shippingOptionsResp.data.shipping_options as Record<
+ string,
+ any[]
+ >
+ ).flat()
+ for (const opt of allOptions) {
+ await api.post(
+ `/store/carts/${cart.id}/shipping-methods`,
+ { option_id: opt.id },
+ storeHeaders
+ )
+ }
+
+ const paymentCollection = (
+ await api.post(
+ `/store/payment-collections`,
+ { cart_id: cart.id },
+ storeHeaders
+ )
+ ).data.payment_collection
+ const session = (
+ await api.post(
+ `/store/payment-collections/${paymentCollection.id}/payment-sessions`,
+ { provider_id: "pp_system_default" },
+ storeHeaders
+ )
+ ).data.payment_collection.payment_sessions[0]
+
+ return { cart, sessionId: session.id }
+ }
+
+ beforeAll(async () => {
+ appContainer = getContainer()
+ })
+
+ beforeEach(async () => {
+ const customerResult = await createCustomerUser(appContainer, {
+ email: "[email protected]",
+ first_name: "Webhook",
+ last_name: "Buyer",
+ })
+ const apiKey = await generatePublishableKey(appContainer)
+ const baseStoreHeaders = generateStoreHeaders({
+ publishableKey: apiKey,
+ })
+ storeHeaders = {
+ headers: {
+ ...baseStoreHeaders.headers,
+ ...customerResult.headers.headers,
+ },
+ }
+
+ const salesChannelModule =
+ appContainer.resolve<ISalesChannelModuleService>(
+ Modules.SALES_CHANNEL
+ )
+ salesChannel = await salesChannelModule.createSalesChannels({
+ name: "Webhook Channel",
+ })
+
+ const regionModule = appContainer.resolve<IRegionModuleService>(
+ Modules.REGION
+ )
+ region = await regionModule.createRegions({
+ name: "Webhook Region",
+ currency_code: "usd",
+ countries: ["us"],
+ })
+
+ const link = appContainer.resolve(ContainerRegistrationKeys.LINK)
+ await link.create({
+ [Modules.REGION]: { region_id: region.id },
+ [Modules.PAYMENT]: {
+ payment_provider_id: "pp_system_default",
+ },
+ })
+
+ sellerSeed = await seedSellerOfferWithShipping({
+ email: "[email protected]",
+ name: "WebhookS1",
+ })
+ })
+
+ it("routes /hooks/payment/:provider to Mercur, leaving Medusa's webhook event unemitted", async () => {
+ const eventBus = appContainer.resolve(Modules.EVENT_BUS)
+ const mercurEvents: any[] = []
+ const medusaEvents: any[] = []
+
+ eventBus.subscribe(
+ "mercur.payment.webhook_received",
+ async (data: any) => {
+ mercurEvents.push(data)
+ }
+ )
+ eventBus.subscribe(
+ "payment.webhook_received",
+ async (data: any) => {
+ medusaEvents.push(data)
+ }
+ )
+
+ const response = await api.post(
+ `/hooks/payment/pp_system_default`,
+ { hello: "world" }
+ )
+ expect(response.status).toEqual(200)
+
+ await new Promise((resolve) => setTimeout(resolve, 8000))
+
+ expect(mercurEvents).toHaveLength(1)
+ expect(medusaEvents).toHaveLength(0)
+
+ // The raw body is what providers sign; losing it would break
+ // signature verification without failing any other assertion.
+ const payload = mercurEvents[0].data.payload
+ expect(payload.data).toEqual({ hello: "world" })
+ expect(Buffer.from(payload.rawData).toString()).toEqual(
+ JSON.stringify({ hello: "world" })
+ )
+ })
+
+ it("completes the cart into split orders when the payment is authorized", async () => {
+ const { cart, sessionId } = await seedReadyCart(
+ sellerSeed.offer.id
+ )
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const { processPaymentWorkflow } = await import(
+ "@mercurjs/core/workflows/payment/workflows/process-payment"
+ )
+
+ await processPaymentWorkflow(appContainer).run({
+ input: {
+ action: "authorized",
+ data: { session_id: sessionId },
+ },
+ })
+
+ const { data: groups } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "orders.id"],
+ filters: { cart_id: cart.id },
+ })
+ expect(groups).toHaveLength(1)
+ expect((groups[0] as any).orders).toHaveLength(1)
+
+ const { data: orderCarts } = await query.graph({
+ entity: "order_cart",
+ fields: ["order_id"],
+ filters: { cart_id: cart.id },
+ })
+ expect(orderCarts).toHaveLength(1)
+ })
+
+ it("does not create a second order when the storefront already completed the cart", async () => {
+ const { cart, sessionId } = await seedReadyCart(
+ sellerSeed.offer.id
+ )
+ const query = appContainer.resolve(
+ ContainerRegistrationKeys.QUERY
+ )
+ const { processPaymentWorkflow } = await import(
+ "@mercurjs/core/workflows/payment/workflows/process-payment"
+ )
+
+ const completed = await api.post(
+ `/store/carts/${cart.id}/complete`,
+ {},
+ storeHeaders
+ )
+ const orderGroupId = completed.data.order_group.id
+
+ await processPaymentWorkflow(appContainer).run({
+ input: {
+ action: "authorized",
+ data: { session_id: sessionId },
+ },
+ })
+
+ const { data: groups } = await query.graph({
+ entity: "order_group",
+ fields: ["id", "orders.id"],
+ filters: { cart_id: cart.id },
+ })
+ expect(groups).toHaveLength(1)
+ expect(groups[0].id).toEqual(orderGroupId)
+ expect((groups[0] as any).orders).toHaveLength(1)
+
+ const { data: orderCarts } = await query.graph({
+ entity: "order_cart",
+ fields: ["order_id"],
+ filters: { cart_id: cart.id },
+ })
+ expect(orderCarts).toHaveLength(1)
+ })
+ })
+ },
+})
diff --git a/packages/cli/routes-manifest.json b/packages/cli/routes-manifest.json
index d7269135f..655cb19bc 100644
--- a/packages/cli/routes-manifest.json
+++ b/packages/cli/routes-manifest.json
@@ -319,7 +319,7 @@
"/auth/verification/request": "typeof import(\"@medusajs/medusa/api/auth/verification/request/route\")",
"/cloud/auth": "typeof import(\"@medusajs/medusa/api/cloud/auth/route\")",
"/cloud/auth/users": "typeof import(\"@medusajs/medusa/api/cloud/auth/users/route\")",
- "/hooks/payment/:provider": "typeof import(\"@medusajs/medusa/api/hooks/payment/[provider]/route\")",
+ "/hooks/payment/:provider": "typeof import(\"@mercurjs/core/api/hooks/payment/[provider]/route\")",
"/hooks/payout": "typeof import(\"@mercurjs/core/api/hooks/payout/route\")",
"/store/carts": "typeof import(\"@medusajs/medusa/api/store/carts/route\")",
"/store/carts/:id": "typeof import(\"@medusajs/medusa/api/store/carts/[id]/route\")",
diff --git a/packages/core/.mercur/routes.d.ts b/packages/core/.mercur/routes.d.ts
index 8d5ea780a..f708aa67e 100644
--- a/packages/core/.mercur/routes.d.ts
+++ b/packages/core/.mercur/routes.d.ts
@@ -553,7 +553,7 @@ export type Routes = {
};
hooks: {
payment: {
- $provider: typeof import("@medusajs/medusa/api/hooks/payment/[provider]/route");
+ $provider: typeof import("../src/api/hooks/payment/[provider]/route");
};
payout: typeof import("../src/api/hooks/payout/route");
};
diff --git a/packages/core/src/api/hooks/payment/[provider]/route.ts b/packages/core/src/api/hooks/payment/[provider]/route.ts
new file mode 100644
index 000000000..4189390bc
--- /dev/null
+++ b/packages/core/src/api/hooks/payment/[provider]/route.ts
@@ -0,0 +1,44 @@
+import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
+import { Modules } from "@medusajs/framework/utils"
+
+import { PaymentWebhookEvents } from "../../../../workflows/events"
+
+// Overrides Medusa's `/hooks/payment/:provider` route — plugin routes are
+// registered after core's, so this file wins the path. It is identical except
+// for the event name: emitting Mercur's own event keeps Medusa's
+// `payment-webhook` subscriber — and with it the stock cart completion — out
+// of the marketplace checkout entirely.
+export const POST = async (req: MedusaRequest, res: MedusaResponse) => {
+ try {
+ const { provider } = req.params
+
+ const options =
+ (req.scope.resolve(Modules.PAYMENT) as unknown as { options?: Record<string, number> })
+ .options || {}
+
+ const eventBus = req.scope.resolve(Modules.EVENT_BUS)
+
+ await eventBus.emit(
+ {
+ name: PaymentWebhookEvents.WEBHOOK_RECEIVED,
+ data: {
+ provider,
+ payload: {
+ data: req.body,
+ rawData: req.rawBody,
+ headers: req.headers,
+ },
+ },
+ },
+ {
+ delay: options.webhook_delay || 5000,
+ attempts: options.webhook_retries || 3,
+ }
+ )
+ } catch (err: any) {
+ res.status(400).send(`Webhook Error: ${err.message}`)
+ return
+ }
+
+ res.sendStatus(200)
+}
diff --git a/packages/core/src/subscribers/payment-webhook.ts b/packages/core/src/subscribers/payment-webhook.ts
new file mode 100644
index 000000000..39bc56f4e
--- /dev/null
+++ b/packages/core/src/subscribers/payment-webhook.ts
@@ -0,0 +1,59 @@
+import { SubscriberArgs, SubscriberConfig } from "@medusajs/framework"
+import { ProviderWebhookPayload } from "@medusajs/framework/types"
+import { Modules, PaymentActions } from "@medusajs/framework/utils"
+
+import { PaymentWebhookEvents } from "../workflows/events"
+import { processPaymentWorkflowId } from "../workflows/payment"
+
+type SerializedBuffer = {
+ data: ArrayBuffer
+ type: "Buffer"
+}
+
+const IGNORED_ACTIONS: string[] = [
+ PaymentActions.NOT_SUPPORTED,
+ PaymentActions.CANCELED,
+ PaymentActions.FAILED,
+ PaymentActions.REQUIRES_MORE,
+ PaymentActions.PENDING_AUTHORIZATION,
+ // Intermediate provider events (e.g. Stripe `payment_intent.created`) must
+ // not trigger cart completion.
+ PaymentActions.PENDING,
+]
+
+export default async function paymentWebhookHandler({
+ event,
+ container,
+}: SubscriberArgs<ProviderWebhookPayload>) {
+ const paymentService = container.resolve(Modules.PAYMENT)
+
+ const input = event.data
+
+ if ((input.payload?.rawData as unknown as SerializedBuffer)?.type === "Buffer") {
+ input.payload.rawData = Buffer.from(
+ (input.payload.rawData as unknown as SerializedBuffer).data
+ )
+ }
+
+ const processedEvent = await paymentService.getWebhookActionAndData(input)
+
+ // Without a session id the event cannot be tied to a payment session, and
+ // the workflow's filters would resolve to an arbitrary unrelated cart.
+ if (!processedEvent.data?.session_id) {
+ return
+ }
+
+ if (IGNORED_ACTIONS.includes(processedEvent.action)) {
+ return
+ }
+
+ const wfEngine = container.resolve(Modules.WORKFLOW_ENGINE)
+ await wfEngine.run(processPaymentWorkflowId, { input: processedEvent })
+}
+
+export const config: SubscriberConfig = {
+ event: PaymentWebhookEvents.WEBHOOK_RECEIVED,
+ context: {
+ subscriberId: "mercur-payment-webhook-handler",
+ },
+}
diff --git a/packages/core/src/workflows/events.ts b/packages/core/src/workflows/events.ts
index 9c9202171..cacfb7a00 100644
--- a/packages/core/src/workflows/events.ts
+++ b/packages/core/src/workflows/events.ts
@@ -42,4 +42,14 @@ export const OfferWorkflowEvents = {
CREATED: "offer.created",
UPDATED: "offer.updated",
DELETED: "offer.deleted",
-}
\ No newline at end of file
+}
+export const PaymentWebhookEvents = {
+ /**
+ * Emitted when a payment provider webhook reaches `/hooks/payment/:provider`.
+ *
+ * Mercur-specific on purpose: Medusa's `payment.webhook_received` would also
+ * wake its own subscriber, which completes carts with the stock complete-cart
+ * workflow instead of the marketplace split-order one.
+ */
+ WEBHOOK_RECEIVED: "mercur.payment.webhook_received",
+}
diff --git a/packages/core/src/workflows/index.ts b/packages/core/src/workflows/index.ts
index 7234b0441..827f0be71 100644
--- a/packages/core/src/workflows/index.ts
+++ b/packages/core/src/workflows/index.ts
@@ -22,3 +22,4 @@ export * from './offer'
export * from './media'
export * from './order'
export * from './review'
+export * from './payment'
diff --git a/packages/core/src/workflows/payment/index.ts b/packages/core/src/workflows/payment/index.ts
new file mode 100644
index 000000000..e399489e8
--- /dev/null
+++ b/packages/core/src/workflows/payment/index.ts
@@ -0,0 +1 @@
+export * from "./workflows"
diff --git a/packages/core/src/workflows/payment/workflows/index.ts b/packages/core/src/workflows/payment/workflows/index.ts
new file mode 100644
index 000000000..a6475e214
--- /dev/null
+++ b/packages/core/src/workflows/payment/workflows/index.ts
@@ -0,0 +1 @@
+export * from "./process-payment"
diff --git a/packages/core/src/workflows/payment/workflows/process-payment.ts b/packages/core/src/workflows/payment/workflows/process-payment.ts
new file mode 100644
index 000000000..744b80db3
--- /dev/null
+++ b/packages/core/src/workflows/payment/workflows/process-payment.ts
@@ -0,0 +1,200 @@
+import { BigNumberInput } from "@medusajs/framework/types"
+import { PaymentActions } from "@medusajs/framework/utils"
+import {
+ createWorkflow,
+ transform,
+ when,
+} from "@medusajs/framework/workflows-sdk"
+import {
+ acquireLockStep,
+ authorizePaymentSessionStep,
+ capturePaymentWorkflow,
+ releaseLockStep,
+ useQueryGraphStep,
+} from "@medusajs/medusa/core-flows"
+
+import { completeCartWithSplitOrdersWorkflow } from "../../cart/workflows/complete-cart-with-split-orders"
+
+export type ProcessPaymentWorkflowInput = {
+ action: string
+ data?: {
+ session_id?: string
+ amount?: BigNumberInput
+ }
+}
+
+const THIRTY_SECONDS = 30
+const TWO_MINUTES = 60 * 2
+
+export const processPaymentWorkflowId = "mercur-process-payment"
+
+/**
+ * Mercur's counterpart to Medusa's `processPaymentWorkflow`. The capture and
+ * authorization branches mirror the stock workflow; the difference is the
+ * completion branch, which runs `completeCartWithSplitOrdersWorkflow` so a
+ * webhook-driven checkout produces per-seller orders under an order group
+ * rather than a single stock order.
+ */
+export const processPaymentWorkflow = createWorkflow(
+ processPaymentWorkflowId,
+ (input: ProcessPaymentWorkflowInput) => {
+ const paymentData = useQueryGraphStep({
+ entity: "payment",
+ fields: ["id"],
+ filters: { payment_session_id: input.data?.session_id },
+ }).config({ name: "payment-query" })
+
+ const paymentSessionResult = useQueryGraphStep({
+ entity: "payment_session",
+ fields: ["payment_collection_id"],
+ filters: { id: input.data?.session_id },
+ }).config({ name: "payment-session-query" })
+
+ const cartPaymentCollection = useQueryGraphStep({
+ entity: "cart_payment_collection",
+ fields: ["cart_id"],
+ filters: {
+ payment_collection_id:
+ paymentSessionResult.data[0]?.payment_collection_id,
+ },
+ }).config({ name: "cart-payment-query" })
+
+ // An undefined filter value matches every row, so a webhook action
+ // without a session id would otherwise resolve to an arbitrary cart.
+ const cartId = transform(
+ { cartPaymentCollection, input },
+ ({ cartPaymentCollection, input }) => {
+ if (!input.data?.session_id) {
+ return undefined
+ }
+ return cartPaymentCollection.data[0]?.cart_id
+ }
+ )
+
+ const { data: order } = useQueryGraphStep({
+ entity: "order_cart",
+ fields: ["id"],
+ filters: { cart_id: cartId },
+ options: { isList: false },
+ }).config({ name: "cart-order-query" })
+
+ when("lock-cart-when-available", { cartId }, ({ cartId }) => {
+ return !!cartId
+ }).then(() => {
+ acquireLockStep({
+ key: cartId,
+ timeout: THIRTY_SECONDS,
+ ttl: TWO_MINUTES,
+ })
+ })
+
+ when({ input, paymentData }, ({ input, paymentData }) => {
+ return (
+ !!input.data?.session_id &&
+ input.action === PaymentActions.SUCCESSFUL &&
+ !!paymentData.data.length
+ )
+ }).then(() => {
+ capturePaymentWorkflow
+ .runAsStep({
+ input: {
+ payment_id: paymentData.data[0].id,
+ amount: input.data?.amount,
+ },
+ })
+ .config({ name: "capture-payment" })
+ })
+
+ // Captured with the provider but no payment record yet, meaning
+ // authorize was never called — the autocapture flow.
+ when({ input, paymentData }, ({ input, paymentData }) => {
+ return (
+ !!input.data?.session_id &&
+ input.action === PaymentActions.SUCCESSFUL &&
+ !paymentData.data.length
+ )
+ }).then(() => {
+ const payment = authorizePaymentSessionStep({
+ id: input.data!.session_id!,
+ context: {},
+ }).config({ name: "authorize-payment-session-autocapture" })
+
+ capturePaymentWorkflow
+ .runAsStep({
+ input: {
+ payment_id: payment.id,
+ amount: input.data?.amount,
+ },
+ })
+ .config({ name: "capture-payment-autocapture" })
+ })
+
+ // No cart is linked to the payment, so nothing will authorize the
+ // session later on our behalf.
+ when(
+ { input, cartPaymentCollection },
+ ({ input, cartPaymentCollection }) => {
+ return (
+ !cartPaymentCollection.data.length &&
+ input.action === PaymentActions.AUTHORIZED &&
+ !!input.data?.session_id
+ )
+ }
+ ).then(() => {
+ authorizePaymentSessionStep({
+ id: input.data!.session_id!,
+ context: {},
+ }).config({ name: "authorize-payment-session" })
+ })
+
+ // The orders already exist (placed with pending_authorization) and the
+ // payment has now been authorized, so create the Payment record.
+ when(
+ "authorize-existing-order",
+ { input, paymentData, cartPaymentCollection, order },
+ ({ input, paymentData, cartPaymentCollection, order }) => {
+ return (
+ !!order &&
+ !paymentData.data.length &&
+ !!cartPaymentCollection.data.length &&
+ input.action === PaymentActions.AUTHORIZED &&
+ !!input.data?.session_id
+ )
+ }
+ ).then(() => {
+ authorizePaymentSessionStep({
+ id: input.data!.session_id!,
+ context: {},
+ }).config({ name: "authorize-payment-session-deferred" })
+ })
+
+ // Released before completion to prevent a deadlock: the split-order
+ // workflow takes the same cart lock.
+ when("release-lock-cart-when-available", { cartId }, ({ cartId }) => {
+ return !!cartId
+ }).then(() => {
+ releaseLockStep({ key: cartId })
+ })
+
+ when(
+ { input, cartPaymentCollection, order },
+ ({ input, cartPaymentCollection, order }) => {
+ return (
+ !!input.data?.session_id &&
+ !!cartPaymentCollection.data.length &&
+ !order
+ )
+ }
+ ).then(() => {
+ completeCartWithSplitOrdersWorkflow
+ .runAsStep({
+ input: { cart_id: cartPaymentCollection.data[0].cart_id },
+ })
+ .config({
+ name: "complete-cart-with-split-orders",
+ // Payment processing must continue even if completion fails.
+ continueOnPermanentFailure: true,
+ })
+ })
+ }
+)