Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 33 ยท Payments, Shipping and Integrations

Payment Providers

Learn how Medusa handles payments: payment collections and sessions, the Stripe provider, writing a custom provider, webhooks with signatures, capture and refund.

Medusa never talks to a bank itself. It talks to a payment provider: a small class that translates Medusa's neutral payment steps ("start a payment", "authorize it", "capture the money", "refund") into calls to a real gateway such as Stripe. The Payment Module owns the records and the state machine, and the provider owns the conversation with the outside world.

This lesson explains the records the Payment Module keeps, how a provider is registered, what a custom provider has to implement, and how webhooks bring late news back into Medusa. Real Medusa code needs a running server and a gateway account, so it is shown read-only. The runnable parts are plain Node stand-ins that follow the same flow and say clearly which parts are invented. The general payment ideas are in Payments Overview, Authorization, Capture, Refunds and Chargebacks and Webhooks and Signature Verification; here we focus on how Medusa names and wires them.

Collections, sessions and payments

Three records describe a payment in the Payment Module:

  • Payment collection: the amount a cart or order still has to pay. A cart gets one collection, and its amount follows the cart total.
  • Payment session: one attempt with one provider. The shopper picks "card" or "PayPal", and Medusa creates a session for that provider. Starting a session calls the provider's initiatePayment, and whatever the gateway returns (for Stripe, a client secret) is stored in the session's data so the storefront can finish the payment in the browser.
  • Payment: created when a session is authorized. A payment can be captured (fully or in parts) and refunded, and each capture and refund is its own record.
flowchart LR
    C["Cart"] --> PC["Payment collection<br/>amount to pay"]
    PC --> PS["Payment session<br/>one provider attempt"]
    PS -->|"authorize"| P["Payment"]
    P -->|"capture"| CAP["Capture records"]
    P -->|"refund"| REF["Refund records"]

A collection can have several sessions over time; only an authorized session becomes a payment.

Because sessions are separate from payments, a shopper can fail a card, switch to another provider and try again without leaving a mess behind. Only one session needs to succeed. This mirrors the "intent first, money later" model from Authorization, Capture, Refunds and Chargebacks.

Registering a provider

Providers are registered in medusa-config.ts under the Payment Module. This is real Medusa configuration (read-only here); check option names against your Medusa version:

TypeScript
import { loadEnv, defineConfig } from "@medusajs/framework/utils"

loadEnv(process.env.NODE_ENV || "development", process.cwd())

module.exports = defineConfig({
  projectConfig: {
    databaseUrl: process.env.DATABASE_URL,
    http: {
      storeCors: process.env.STORE_CORS!,
      adminCors: process.env.ADMIN_CORS!,
      authCors: process.env.AUTH_CORS!,
      jwtSecret: process.env.JWT_SECRET || "supersecret",
      cookieSecret: process.env.COOKIE_SECRET || "supersecret",
    },
  },
  modules: [
    {
      resolve: "@medusajs/medusa/payment",
      options: {
        providers: [
          {
            resolve: "@medusajs/medusa/payment-stripe",
            id: "stripe",
            options: {
              apiKey: process.env.STRIPE_API_KEY,
              webhookSecret: process.env.STRIPE_WEBHOOK_SECRET,
            },
          },
        ],
      },
    },
  ],
})

The id in the entry joins the provider's identifier to build the provider ID that appears in the Store API, for example pp_stripe_stripe. After you enable the provider for a region in the Admin, the storefront sees it when it lists payment providers for that region. Keys come from the environment; never commit them. See Create a Medusa Project for how medusa-config.ts is loaded.

The storefront side

From the storefront, the flow uses the Store API (covered in The Store API and in detail in Building the Checkout Flow):

HTTP
POST /store/payment-collections
{ "cart_id": "cart_01..." }

POST /store/payment-collections/{id}/payment-sessions
{ "provider_id": "pp_stripe_stripe" }

The second response contains the session with the provider's data. The browser then confirms the payment with the gateway's own script, and finally the storefront completes the cart. For card payments, the gateway's script does the sensitive part, so card numbers never reach your server (see PCI Scope, 3-D Secure and SCA).

Writing a custom provider

When there is no ready-made module for your gateway, you write a payment provider module service by extending AbstractPaymentProvider. A trimmed, read-only sketch:

TypeScript
import { AbstractPaymentProvider } from "@medusajs/framework/utils"
import type {
  InitiatePaymentInput,
  InitiatePaymentOutput,
  AuthorizePaymentInput,
  AuthorizePaymentOutput,
  CapturePaymentInput,
  CapturePaymentOutput,
  RefundPaymentInput,
  RefundPaymentOutput,
  ProviderWebhookPayload,
  WebhookActionResult,
} from "@medusajs/framework/types"

type Options = { apiKey: string; webhookSecret: string }

class AcmePayProvider extends AbstractPaymentProvider<Options> {
  static identifier = "acmepay"

  static validateOptions(options: Record<string, any>) {
    if (!options.apiKey) {
      throw new Error("acmepay: apiKey is required")
    }
  }

  async initiatePayment(input: InitiatePaymentInput): Promise<InitiatePaymentOutput> {
    // create an intent at the gateway, return its id and client data
    return { id: "acme_intent_1", data: { clientSecret: "..." } }
  }

  async authorizePayment(input: AuthorizePaymentInput): Promise<AuthorizePaymentOutput> {
    // ask the gateway whether the intent is authorized
    return { status: "authorized", data: input.data }
  }

  async capturePayment(input: CapturePaymentInput): Promise<CapturePaymentOutput> {
    return { data: input.data }
  }

  async refundPayment(input: RefundPaymentInput): Promise<RefundPaymentOutput> {
    return { data: input.data }
  }

  // also required: cancelPayment, deletePayment, retrievePayment,
  // updatePayment, getPaymentStatus, getWebhookActionAndData

  async getWebhookActionAndData(payload: ProviderWebhookPayload["payload"]): Promise<WebhookActionResult> {
    // verify the signature, then map the gateway event to a Medusa action
    return { action: "not_supported" }
  }
}

export default AcmePayProvider

The module's index.ts registers it with ModuleProvider(Modules.PAYMENT, { services: [AcmePayProvider] }), and you add it to the Payment Module's providers list like Stripe above. Method signatures and the exact input and output types have changed between Medusa releases, so treat this as the shape of the contract and let your installed types be the source of truth.

The methods fall into a simple map:

Method When Medusa calls it What it should do
initiatePayment A payment session is created Create the gateway intent, return its id and client data
authorizePayment The cart is completed Report whether the gateway holds the funds
capturePayment An admin (or workflow) captures Take the money
refundPayment An admin refunds Return an amount to the customer
cancelPayment / deletePayment Abandoned or replaced sessions Release the hold or discard the intent
getWebhookActionAndData The gateway hits the webhook URL Verify, translate the event

Webhooks

Some results arrive later: a 3-D Secure challenge finishes in another tab, a bank approves late, an async method settles. The gateway then calls Medusa. Medusa exposes a route per provider, in the form /hooks/payment/{identifier}_{id} (for Stripe configured as above, /hooks/payment/stripe_stripe), and passes the raw request to your getWebhookActionAndData. You return an action such as authorized, captured or failed, plus the data Medusa needs to find the session and amount. Medusa then runs the matching workflow.

Your method must verify the signature against the raw body before trusting anything, as explained in Webhooks and Signature Verification. Events can also repeat, so handling the same event twice must not authorize or capture twice (Idempotency).

Stand-in 1: a provider and the session life cycle

The first stand-in is not Medusa code. It implements the same method names with an in-memory "gateway", so you can see the state transitions the Payment Module drives.

Node.js A stand-in provider through authorize, capture and refund

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that every amount is an integer number of cents (see Money as Integers) and that the provider enforces the gateway's own rules: you cannot capture more than was authorized or refund more than was captured. Real gateways enforce these limits too, and Medusa surfaces their errors.

Stand-in 2: a signed webhook handler

The second stand-in verifies an HMAC signature, rejects stale timestamps and ignores duplicate events. The signature scheme here is invented for teaching; real gateways document their own (Stripe, for example, signs a timestamp plus the body and ships its own verification helper, which you should use instead of hand-rolled code).

Node.js Verifying a webhook signature and ignoring duplicates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The checks run in a deliberate order: authenticity first, freshness second, deduplication third, and only then a state change. The timingSafeEqual comparison avoids leaking where a forged signature first differs. A real handler also needs the raw bytes of the body, because re-serializing parsed JSON can change them and break the signature.

Common mistakes

  • Capturing at checkout by habit. Authorize at checkout and capture when you ship if your gateway and business allow it; otherwise refunds get frequent.
  • Trusting the browser. The storefront saying "paid" proves nothing. Rely on the provider's authorization result and its verified webhooks.
  • Parsing the body before verifying. Signature checks need the raw body.
  • Hard-coding keys. Provider options come from environment variables.
  • Forgetting to enable the provider in the region. A configured provider is invisible to shoppers until the region lists it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the relationship between a payment collection and payment sessions?

    The collection is the amount a cart or order has to pay. Sessions are attempts with a provider, so a shopper can switch providers without corrupting anything, and only an authorized session becomes a payment.
  2. 2. Which method of a custom provider receives the gateway's webhook request?

    Medusa routes the provider's webhook URL to getWebhookActionAndData, where you verify the signature and translate the event into an action Medusa understands.
  3. 3. Why must a webhook handler verify the signature against the raw body?

    The signature is computed over the exact bytes the gateway sent. Whitespace or key order changes after parsing would make a valid signature fail.
  4. 4. The same payment.authorized event is delivered twice. What should the handler do?

    Gateways retry deliveries, so handlers must be idempotent. Remember processed event IDs (or check the current state) and ignore repeats.

Summary

  • The Payment Module keeps collections, sessions, payments, captures and refunds; the provider talks to the gateway.
  • Providers are registered under the Payment Module in medusa-config.ts and enabled per region.
  • A custom provider extends AbstractPaymentProvider and implements initiate, authorize, capture, refund, cancel and webhook methods.
  • Webhooks arrive at /hooks/payment/{identifier}_{id}; verify the raw-body signature, check freshness and ignore duplicates.
  • Use integer amounts and let the gateway's limits protect you from over-capture and over-refund.

Next, learn how orders get to customers in Fulfillment, Shipping and Tax Providers.