# `MishkaPay.Providers.Stripe`
[🔗](https://github.com/mishka-group/mishka_pay/blob/v0.0.1/lib/mishka_pay/providers/stripe.ex#L5)

Stripe as a provider: one time payments with Stripe Checkout, reading a payment and refunds.

Supervise it to install it, and answer its keys for each tenant (`MishkaPay.Credentials`); only
`secret_key` is needed here, `webhook_secret` joins with webhooks.

    children = [MishkaPay.Providers.Stripe]

It talks to Stripe through `MishkaPay.Client` (retries, one idempotency key per call,
telemetry), with the tenant's secret key and one pinned Stripe API version,
`2026-10-28.endive`, so a change of the account's default version never changes what this
module reads. No third party Stripe library is used. Stripe's field names live only in
`MishkaPay.Providers.Stripe.Mapper`.

  * `checkout/2` opens a Checkout Session in `payment` mode and answers its page. A price's
    `:tax_code` is its product tax code, and `:merchant_of_record` (the checkout's, else the
    tenant's setting in `MishkaPay.Credentials`) turns Stripe Managed Payments on or off for the
    session; an account with Managed Payments on by default needs a tax code
    on every price. The caller's
    `:reference` goes to Stripe as `client_reference_id` and as metadata on the session and its
    payment, and it makes the idempotency key, so the same reference never opens two sessions.
  * `fetch_checkout/2` reads a Checkout Session back, with the PaymentIntent it made.
  * `capture: :automatic`, on a checkout or a PaymentIntent, is Stripe's `automatic_async`
    (its default and recommended way), `:automatic_sync` its older `automatic`; `:manual`
    holds the money. Both `automatic` and
    `automatic_async` read back as `:automatic`.
  * `fetch_payment/2` reads a PaymentIntent with its latest charge, the charge's refunds and the
    customer, in one request: the buyer, the card, the receipt, why it failed and every refund.
  * `fetch_subscription/2`, `cancel_subscription/3`, `resume_subscription/2` and
    `list_invoices/2` read a Subscription with its customer and products, cancel it at once
    (`DELETE`) or at the period's end (`cancel_at_period_end`), take that back, and list its
    Invoices. A checkout in `mode: :subscription` starts one, with its trial and the reference
    on the subscription. `list_subscriptions/2` lists them by customer, price or status (Stripe
    leaves canceled ones out unless asked for them or for `:all`), and `search_subscriptions/2`
    finds them with Stripe's search by status, reference or metadata. Every subscription it
    makes (a subscription checkout, a new schedule) sends Stripe's `billing_mode`: `flexible`
    with `itemized` proration discounts, Stripe's recommended ones, unless the checkout, the
    schedule or the tenant's keys ask for `classic` or `included`.
  * `create_subscription_schedule/2`, `fetch_subscription_schedule/2`,
    `list_subscription_schedules/2`, `update_subscription_schedule/2`,
    `release_subscription_schedule/2` and `cancel_subscription_schedule/3` use Subscription
    Schedules (`sub_sched_...`): made `from_subscription`, or for a customer with phases; a
    phase's `:iterations` and `:interval` are its `duration` (this API version has no
    `iterations`), and the reference makes the idempotency key and is kept in its metadata
    (set in a second request on one made from a subscription, which Stripe makes without
    metadata).
  * `create_customer/2`, `fetch_customer/2`, `update_customer/2`, `list_customers/2` and
    `delete_customer/2` keep customers with Accounts v2 (an account with the customer
    configuration, `acct_...`, the default) or as Customers (`/v1/customers`, `cus_...`), as the
    customer's `:api` or the tenant's `:customer_api` says; a read, a change and a delete use
    the API the id belongs to. On v2 the email is `contact_email`, the name `display_name`, the
    phone and address the identity's individual's, the invoice default the customer
    configuration's billing; a read includes the configuration and the identity. The reference
    is kept in the metadata either way. A v2 delete closes the account (every configuration it
    has, read first); a v1 delete is for good and cancels the customer's subscriptions at once.
    A v2 list has no email filter and holds at most 20; `search_customers/2` is Stripe's
    Customer search on either, which finds customers made on v2 by the Customer Stripe links
    to each, and names them by their account on v2. Every call that names a customer sends an
    `acct_` id as `customer_account` and a `cus_` one as `customer` (checkout, intents,
    subscriptions and schedules, invoices, invoice items, credit notes, the portal, payments
    and promotion codes), and a path under `/v1/customers/:id` takes either (tax ids, payment
    methods, the customer balance). Usage reports and summaries, entitlements and tax
    calculations take only a `cus_` id: Stripe takes no `customer_account` there yet. Managed
    Payments sells to no customer account, so a checkout for one as the merchant of record is
    refused. `create_tax_id/2`, `list_tax_ids/2` and `delete_tax_id/3` keep a customer's tax ids
    (`txi_...`); `portal_session/2` opens a
    billing portal session for one, with the portal configuration (`bpc_...`) it names;
    `create_portal_configuration/2`, `update_portal_configuration/2`,
    `fetch_portal_configuration/2` and `list_portal_configurations/2` keep those (Stripe never
    deletes one: `active: false` turns it off). Stripe answers a portal session only once the account's
    portal is set up (Settings, Billing, Customer portal), in test mode too.
  * A checkout in `mode: :setup` opens a session in Stripe's `setup` mode that saves a card
    without a charge, with Managed Payments off (Stripe takes no setup mode with it) and, without
    a known customer, `customer_creation: always`. `list_payment_methods/2`,
    `fetch_payment_method/2`, `detach_payment_method/2` and `set_default_payment_method/3` keep
    a customer's PaymentMethods (`pm_...`); the default is a change of the customer: a v1
    Customer's `invoice_settings.default_payment_method`, or a v2 account's
    `configuration.customer.billing.default_payment_method`.
  * `create_shipping_rate/2` and `list_shipping_rates/2` keep Shipping Rates (`shr_...`). A
    checkout's `:shipping_countries` is `shipping_address_collection` and its `:shipping_rates`
    are `shipping_options` (a rate by id, or `shipping_rate_data`), up to 5, in payment mode
    only. Stripe refuses shipping where Managed Payments is on.
  * `calculate_tax/2` asks Stripe Tax for the tax on a sale made outside Checkout
    (`POST /v1/tax/calculations`), and `record_tax/3` records it as a Tax Transaction
    (`create_from_calculation`) under the caller's reference, which makes its idempotency key.
    An account without Stripe Tax turned on is refused with code `"tax_not_set_up"`.
  * `create_payment_intent/2`, `fetch_payment_intent/2`, `update_payment_intent/2`,
    `confirm_payment_intent/3` and `cancel_payment_intent/2` keep PaymentIntents (`pi_...`) for
    a page with Stripe Elements; `create_setup_intent/2`, `fetch_setup_intent/2`,
    `confirm_setup_intent/3` and `cancel_setup_intent/2` keep SetupIntents (`seti_...`). The
    reference makes the idempotency key and is kept in the metadata, so `fetch_payment/2`
    reads a paid one with its reference like a checkout's.
  * `create_tax_rate/2`, `fetch_tax_rate/2`, `update_tax_rate/2` and `list_tax_rates/2` keep
    Tax Rates (`txr_...`) set by hand; a rate's reference makes the idempotency key and is kept
    in its metadata. A checkout's line takes them as `tax_rates`, an invoice item too, and a
    draft invoice as `default_tax_rates`; Stripe takes none on a price or a payment link, nor
    with automatic tax on the same checkout.
  * `create_tax_registration/2`, `list_tax_registrations/2` and `expire_tax_registration/3`
    keep Stripe Tax Registrations (`taxreg_...`), the type and state sent under the country's
    own `country_options`; `fetch_tax_settings/1` and `update_tax_settings/2` read and change
    Stripe Tax's settings (head office, default tax code and behavior).
  * `create_invoice_item/2`, `update_invoice_item/2`, `delete_invoice_item/2` and
    `list_invoice_items/2` keep Invoice Items (`ii_...`) on their own: a charge that waits for
    the customer's next invoice, or goes on a draft one; the reference makes the idempotency
    key and is kept in the item's metadata.
  * `create_credit_note/2`, `preview_credit_note/2`, `fetch_credit_note/2`,
    `void_credit_note/2`, `list_credit_notes/2` and `list_credit_note_lines/3` use Credit
    Notes (`cn_...`) on finalized invoices: by `amount` or by line (an invoice line `il_...`
    or a custom one), with `refund_amount`, `credit_amount` and `out_of_band_amount`; the
    reference makes the idempotency key and is kept in the note's metadata. A note's lines
    carry no currency, so its lines are read with the note first.
  * `refund/2` refunds a PaymentIntent, in full or in part, once or many times as the tenant
    allows (`MishkaPay.Refund`).
  * `upload_file/2` sends a file to `files.stripe.com` as `multipart/form-data`; dispute
    evidence only as PDF, JPEG or PNG, up to 5 MB, and its bytes must be the type it names.
    `fetch_file/2` reads one, and `file_link/3` makes a `MishkaPay.File.Link`, a public address of it.
    `update_dispute/2` takes only a file id (`file_...`) in the evidence fields that hold a
    file, such as `receipt` and `uncategorized_file`.
  * `create_meter/2`, `fetch_meter/2`, `update_meter/2` (its display name only),
    `list_meters/2`, `deactivate_meter/2`, `reactivate_meter/2`, `report_usage/2`,
    `cancel_usage/2` and `usage_summary/3` use Billing Meters (`mtr_...`) and meter events,
    Stripe's basic usage billing; a price with `:meter_id` is a metered price on one. A
    report's reference makes its `identifier`; Stripe takes reports from the last 35 days and
    up to 5 minutes ahead, and counts summaries from and to whole minutes. A cancel is a meter
    event adjustment (`type: cancel`) of one identifier, within 24 hours of the report; the
    identifier makes its idempotency key. A report with `stream: true` goes through the API v2
    meter event stream instead: a meter event session's token, kept in
    `MishkaPay.Helpers.TokenCache` until shortly before it runs out, then the report as JSON to
    `meter-events.stripe.com`, which Stripe checks after it answers.
  * `create_feature/2`, `attach_feature/3` and `list_entitlements/2` use Entitlements: features
    (`feat_...`) on products, and the active entitlements of a customer.
  * `fetch_fraud_warning/2` and `list_fraud_warnings/2` read Radar's early fraud warnings
    (`issfr_...`), by PaymentIntent or charge; `list_fraud_reviews/2` lists the open Reviews
    (`prv_...`) Radar's rules placed, `fetch_fraud_review/2` reads one and
    `approve_fraud_review/2` approves it. Stripe sends `radar.early_fraud_warning.*` and
    `review.opened`/`review.closed` about them.
  * `fetch_balance/1` reads the payments balance, and `list_balance_transactions/2` its
    balance transactions (`txn_...`), by payout (`po_...`) or type.
  * `adjust_customer_balance/2` and `list_customer_balance/2` keep a customer's credit balance
    (`cbtxn_...`): below zero is credit.
  * `create_connected_account/2`, `fetch_connected_account/3`, `update_connected_account/2`,
    `list_connected_accounts/2` and `close_connected_account/3` keep Connect accounts
    (`acct_...`) with Accounts v2 (`/v2/core/accounts`, the default) or Accounts v1
    (`/v1/accounts`), as the call's `:api` or the tenant's `:connect_api` says; both answer the
    same `MishkaPay.ConnectedAccount`. On v2 an account is made with its configurations
    (a merchant asks for card payments, a recipient for transfers into its balance), its
    dashboard and who collects fees and losses, and read with its configurations, requirements,
    defaults and identity (`include`); on v1 the same choices are its `controller` and
    capabilities. Its reference makes the idempotency key and is kept in its metadata. A v2
    close sends every configuration the account has, read first; a v1 close is a reject.
    `account_link/2` makes an `account_onboarding` or `account_update` link
    (`/v2/core/account_links` or `/v1/account_links`), and `login_link/2` an Express dashboard
    login link, on v1 only (v2 has none; it takes an account made with either). Stripe sends
    `account.updated` and `account.application.deauthorized` as snapshot events, and API v2's
    `v2.core.account.*` as thin events (`thin_events/0`). A platform that has not signed up for
    Connect is refused with code `"connect_not_set_up"`, and an account made on v1 where Stripe
    allows only v2 with `"connect_v1_refused"`.
  * A checkout's `:application_fee`, `:destination` and `:on_behalf_of` go in its
    `payment_intent_data` (`application_fee_amount`, `transfer_data[destination]`,
    `on_behalf_of`), and `:application_fee_percent` with them in `subscription_data`; ids are
    `acct_...` and the fee is in the items' currency. `fetch_application_fee/2`,
    `list_application_fees/2` and `refund_application_fee/3` keep the fees (`fee_...`); a refund
    answers its fee expanded, in one request.
  * `create_transfer/2`, `fetch_transfer/2`, `list_transfers/2` and `reverse_transfer/3` use
    Transfers (`tr_...`): the reference makes the idempotency key and is kept in metadata, and a
    reversal answers its transfer expanded. `fetch_payout/2`, `list_payouts/2` and
    `cancel_payout/2` read and stop Payouts (`po_...`) of the account the keys act for. Stripe
    sends `transfer.*`, `payout.*` and `application_fee.*` about them.
  * `raw_request/2` calls any path of `api.stripe.com` with the tenant's key, the pinned
    version or the call's own `api_version` (`Stripe-Version`) and its `expand[]`, and answers
    Stripe's JSON as it is; a write's reference, with its method and path, makes the
    idempotency key. A `/v2/` path is sent as API v2 takes it: a write's params as JSON, a
    read's as a query with indexed lists; v2 has no `expand[]` and reads more with `include`
    in the params.

  * `verify_webhook/3` checks the `Stripe-Signature` header: an HMAC-SHA256 of
    `"<timestamp>.<raw body>"` with the tenant's `webhook_secret`, or any of its
    `webhook_secrets` while a rolled secret runs out, compared in constant time with every
    `v1` signature in it, signed within the last five minutes
    (`config :mishka_pay, MishkaPay.Providers.Stripe, webhook_tolerance: seconds`), and from the
    same mode (live or test) as the tenant's keys. It takes snapshot and thin events alike; a
    thin one becomes the Event its snapshot event gives (`thin_events/0`), reading its object
    when an id it needs sits inside it.
  * `list_events/2` reads the tenant's kind of events (`:events`, a call's `events:` first):
    thin ones from API v2's `/v2/core/events`, snapshot ones from `/v1/events`.
    `MishkaPay.Providers.Stripe.WebhookEndpoint` sets up the endpoint for either kind.

A tenant whose keys name a connected account (`:account_id`, `acct_...`) acts as that account:
every request carries it in the `Stripe-Account` header (`Stripe-Context` on an API v2 path),
and only from the keys. Such a tenant
takes only webhook messages about its own account (Stripe's `account` on the event); one about
the platform or another connected account is refused like a bad signature. Keys without one
are the platform's own, and take its connected accounts' events, each with its `:account`.

Stripe answers 402 for a declined card (`MishkaPay.Errors.Declined`, with Stripe's decline code)
and other errors as `MishkaPay.Errors.Rejected` with its code and status. Both keep Stripe's
`Request-Id` header as `:request_id` (`req_...`) and its error page as `:doc_url`, for support and
the log; their messages never show them.

Stripe counts a few currencies differently from ISO 4217: ISK and UGX as two-decimal amounts
ending in 00, and MGA as zero-decimal. Mishka Pay sends and reads them as Stripe counts them,
and refuses a fraction of one before any request. HUF and TWD charge with two decimals like
other currencies (Stripe pays them out in whole units). It takes BHD, JOD, KWD, OMR and TND only with a last decimal of 0, and metadata up to 48 keys of 40
characters with values of 500; anything past that is an `:invalid` error before any request.

A refund first reads the payment. A tenant that refunds once is refused a second refund, and a
part refund in another currency than the payment's, or over what is left, is refused, since
Stripe counts a refund in the payment's own currency.

`config :mishka_pay, MishkaPay.Providers.Stripe, base_url: "http://localhost:12111"` points it at
another address, such as Stripe's own mock server in tests. Uploads go to `files_url` when it is
set, else to `base_url` when that is set, else to `https://files.stripe.com`; streamed usage
reports (`stream: true`) to `meter_events_url` the same way, else to
`https://meter-events.stripe.com`.

# `error_return`

```elixir
@type error_return() ::
  {:error, [%{action: atom(), field: atom(), message: String.t()}]}
```

# `okey_return`

```elixir
@type okey_return() :: {:ok, struct() | map() | module() | [any()]}
```

# `child_spec`

Returns a specification to start this module under a supervisor.

See `Supervisor`.

# `config`

```elixir
@spec config() :: keyword()
```

# `config`

```elixir
@spec config(atom()) :: any()
```

# `enable`

```elixir
@spec enable() :: okey_return() | error_return()
```

# `event_types`

```elixir
@spec event_types() :: %{required(String.t()) =&gt; [atom()]}
```

The events Mishka Pay acts on, by the type their `MishkaPay.Event` carries: `handled_events/0`,
and `thin_events/0` named as `Mapper.event_type/1` names them (`invoice.overpaid`,
`v2.core.account.updated`). `MishkaPay.replay_events/3` delivers only these.

# `form`

```elixir
@spec form(map() | list()) :: [{String.t(), String.t()}]
```

Stripe's form encoding of nested params: `%{"line_items" => [%{"quantity" => 1}]}` becomes
`[{"line_items[0][quantity]", "1"}]`. `nil` values are left out.

# `get`

```elixir
@spec get() :: keyword()
```

# `handled_events`

```elixir
@spec handled_events() :: %{required(String.t()) =&gt; [atom()]}
```

The Stripe events that change what Mishka Pay keeps, each with what it updates: `:payment`
(a resource with `mishka_pay do kind :payment end`), `:subscription`, `:customer`, `:dispute`,
`:invoice`, `:product`, `:price`, `:coupon`, `:promotion_code` or `:payment_link`; or the
provider object it is about (`:credit_note`, `:tax_rate`; `:subscription_schedule`, which names its
subscription too; `:fraud_warning` and `:fraud_review`, which name their payment too;
`:account`, a connected account, which the event names as its `:account`; `:transfer`,
`:payout` and `:application_fee`, money between accounts). Each is mapped to its
ids (`MishkaPay.Event`) and tested; any other event is still verified and stored, and changes
nothing. Send these to the webhook endpoint in the Stripe Dashboard.

# `health_check`

```elixir
@spec health_check() :: :ok | {:degraded, term()} | {:error, term()}
```

Optional. See `c:MishkaInstaller.Event.Hook.health_check/0`. Override to report health.

# `latest_version`

```elixir
@spec latest_version() :: {:ok, String.t()} | {:error, Splode.Error.t()}
```

The API version of Stripe's newest published OpenAPI spec (github.com/stripe/openapi): its
`info.version`, the first value in Stripe's version form (`2026-10-28.endive`) in the file's
first bytes. `mix mishka_pay.stripe.check_version` compares it with `version/0`.

# `on_dependency_error`

```elixir
@spec on_dependency_error(term()) :: term()
```

Optional. See `c:MishkaInstaller.Event.Hook.on_dependency_error/1`. Override to react.

# `place_of_supply_schemes`

```elixir
@spec place_of_supply_schemes(String.t(), String.t()) :: [
  :inbound_goods | :small_seller | :standard
]
```

The place of supply schemes Stripe takes for a tax registration of `type` in `country` (two
capital letters), from its API's `country_options`: a `"standard"` registration in an EU
country takes `:standard`, `:small_seller` or `:inbound_goods`; one in the other countries
whose standard registration has a scheme (the UK, Norway, Switzerland, Australia, Japan and
others) takes `:standard` or `:inbound_goods`; any other registration takes none (`[]`).
`MishkaPay.create_tax_registration/1` refuses any other before asking Stripe.

# `register`

```elixir
@spec register() :: okey_return() | error_return()
```

# `restart`

```elixir
@spec restart() :: okey_return() | error_return()
```

# `signature`

```elixir
@spec signature(binary(), integer(), String.t()) :: String.t()
```

Stripe's signature of `payload` at `timestamp` (Unix seconds) with webhook `secret`: the `v1`
value of a `Stripe-Signature` header. `verify_webhook/3` compares with it, and a test signs a
message with it.

# `start`

```elixir
@spec start() :: okey_return() | error_return()
```

# `start_link`

# `stop`

```elixir
@spec stop() :: okey_return() | error_return()
```

# `thin_events`

```elixir
@spec thin_events() :: %{required(String.t()) =&gt; [atom()]}
```

The thin events Mishka Pay maps, each with what it updates (the words of `handled_events/0`),
as an event destination with the thin payload sends them (the default of
`MishkaPay.Providers.Stripe.WebhookEndpoint`); Stripe never sends one to a
`/v1/webhook_endpoints` endpoint:

  * `v1.<type>` for each of `handled_events/0`, the thin form of the same event;
  * thin events with no snapshot event of their name, about what Mishka Pay keeps: a
    subscription that turned `active`, `past_due`, `unpaid`, `trialing` or `incomplete`, or
    whose items, cancel date or payment method changed; an invoice paid, due, overpaid, or
    whose lines or discounts changed; a schedule's phases; a product's or a price's activation,
    tax code, lookup key or default price; a promotion code used up; an entitlement added or
    removed;
  * `v1.billing.meter.error_report_triggered` and `v1.billing.meter.no_meter_found`
    (`:meter`): usage reports Stripe refused after answering (a streamed report). The event's
    `:object_id` is the meter (`mtr_...`) when Stripe found one; the counts and samples are in
    the full event, `GET /v2/core/events/:id` (`MishkaPay.request/1`);
  * API v2's connected account events (`v2.core.account.*`, `:account`): `:object_id` and
    `:account` are the account (read it with `MishkaPay.fetch_connected_account/4`). The
    events a customer made on Accounts v2 sends (`v2.core.account.updated` and `.closed`,
    `[identity].updated`, `[configuration.customer].*`) name the account as its `:customer_id`
    too, so the Ash customer listener syncs it; for an account that is only a seller, that
    read answers `resource_missing` and the listener leaves the event done.

A thin event names its object and no more. `verify_webhook/3` turns one into the same
`MishkaPay.Event` a snapshot event gives: an id that sits inside the object (the payment of a
charge, the subscription of an invoice, the customer of a tax id, the account a customer made
on Accounts v2 is) is read from the object, one request as the event's account; an event
whose object is itself the id it names (a PaymentIntent, a subscription, a product) needs none. Its `:type` is the snapshot
event's (`invoice.paid` for `v1.invoice.paid`, `invoice.overpaid` for the thin-only
`v1.invoice.overpaid`: `Mapper.event_type/1`), so a listener matches one name in either mode;
API v2's own events keep Stripe's names (`v2.core.account.updated`).

# `unregister`

```elixir
@spec unregister() :: okey_return() | error_return()
```

# `version`

```elixir
@spec version() :: String.t()
```

The Stripe API version every request is pinned to.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
