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

The keys of one provider for one tenant (a site, a shop, an account): the secret key, the
publishable key, the webhook secret, test or live, and whatever else the provider needs in
`:extra`.

Mishka Pay keeps no keys itself. `fetch/3` fires `mishka_pay:credentials`
(`MishkaPay.Events.credentials/0`) and the host answers through a plugin, from its settings, its
database or the environment:

    defmodule MyApp.PayKeys do
      use MishkaPay.Credentials

      @impl MishkaPay.Credentials
      def credentials("stripe", _tenant),
        do: %{secret_key: System.fetch_env!("STRIPE_SECRET_KEY"), mode: :live}

      def credentials(_provider, _tenant), do: nil
    end

Supervise it like any other plugin. A project with one site answers the same keys for every
tenant; a multi-site one reads the tenant's own. When several plugins listen, the first one that
answers wins, in the order of their `:priority` (50 by default).

Besides keys, the answer carries the provider's settings for the tenant:

  * `:merchant_of_record`: `true` or `false` turns selling as the merchant of record on or off
    for every checkout of this tenant (Stripe Managed Payments); left out, the provider
    account's own default applies. A checkout's own `:merchant_of_record` still wins.
  * `:automatic_tax`: `true` has the provider count the tax of this tenant's checkouts and
    payment links from the buyer's address (Stripe Tax); a checkout's own `:automatic_tax` still
    wins.
  * `:billing_mode`: how this tenant's new subscriptions count prorations and bill: `:flexible`
    (the default when left out, Stripe's recommended mode) or `:classic`. A checkout's or a
    schedule's own `:billing_mode` still wins. Mishka Pay sends it with every subscription it
    makes (a subscription checkout, a new schedule).
  * `:proration_discounts`: with the flexible mode, `:itemized` (the default when left out,
    Stripe's recommended way: a proration shows the full amount and its discount) or
    `:included` (the amount after the discount). A checkout's or a schedule's own still wins.
  * `:webhook_secrets`: other webhook secrets still accepted beside `:webhook_secret`, while a
    rolled secret runs out. Stripe keeps signing with the old secret for a while after a roll
    (up to a day), so a site lists the old one here and puts the new one in
    `:webhook_secret`; a message passes when any of them verifies it. Drop the old one once
    Stripe stops using it. Only for providers that check a shared secret (Stripe); PayPal checks
    its messages by `:webhook_secret`, the webhook id, alone.
  * `:refunds`: how this tenant refunds a payment. `:once` (the default): one refund, whole or
    in part, and a buyer who wants it again makes a new purchase. `:many`: part refunds until
    the payment is used up, as the provider itself allows; each refund then needs its own
    `:reference` (`MishkaPay.Refund`).
  * `:account_id`: the connected account this tenant acts for, at a provider with connected
    accounts (Stripe Connect, `acct_...`). A platform answers its own secret key with each site's
    connected account: every request is then made as that account (Stripe's `Stripe-Account`
    header), and a webhook message about any other account is refused. Left out, the tenant is
    the account that owns the secret key (the platform itself, or a plain site). It comes only
    from these keys: no call, request option or raw request can set the header. A provider
    without `:connect` (PayPal) never reads it. `MishkaPay.create_connected_account/1`
    makes one with the platform's keys.
  * `:connect_api`: which of the provider's APIs keeps this tenant's connected accounts, at a
    provider that has two. `:v2` (the default: Stripe's Accounts v2, the one Stripe recommends
    and the only one a platform that turned Connect on lately may use to make accounts) or
    `:v1` (Stripe's Accounts v1, still needed for OAuth, Treasury, card issuing and older
    capabilities). A call's own `:api` still wins (`MishkaPay.ConnectedAccount`,
    `MishkaPay.ConnectedAccount.Link`, `api:` on a read, a list or a close).
  * `:customer_api`: which of the provider's APIs makes this tenant's customers, at a provider
    that has two. `:v2` (the default: Stripe's Accounts v2, an account with the customer
    configuration, `acct_...`, the one Stripe recommends) or `:v1` (Stripe's Customers,
    `cus_...`). A customer's own `:api` (`MishkaPay.Customer`) and `api:` on a list or a search
    still win; a customer made with either is read, changed and sold to with either setting.
  * `:events`: how the provider sends this tenant's events, at a provider that has two kinds.
    `:thin` (the default: Stripe's thin events, the format Stripe recommends, a small
    notification Mishka Pay reads the rest for) or `:snapshot` (each event carries its object
    as it was). It picks the kind `MishkaPay.Providers.Stripe.WebhookEndpoint` sets up and the
    event API `MishkaPay.list_events/3` and `MishkaPay.replay_events/3` read; a call's own
    `events:` still wins. The webhook takes either kind whatever it says.
  * `:webhook_api`: which of the provider's APIs keeps this tenant's webhook endpoint. `:v2`
    (the default: Stripe's event destinations, `/v2/core/event_destinations`, the only one for
    thin events) or `:v1` (Stripe's `/v1/webhook_endpoints`, snapshot events only). A call's
    own `api:` still wins.

These are read at runtime on every call, never from `config.exs`, so each tenant of a
multi-site project carries its own and a change in its settings applies to the next call.

The answer may use atom or string keys, and the mode may be `"test"` or `"live"`. Its own
`:provider` and `:tenant` are ignored: they always come from the call.

`inspect/1` shows only the provider, the tenant and the mode, so a key never reaches a log line.

# `t`

```elixir
@type t() :: %MishkaPay.Credentials{
  account_id: String.t() | nil,
  automatic_tax: boolean() | nil,
  billing_mode: (:flexible | :classic) | nil,
  connect_api: (:v2 | :v1) | nil,
  customer_api: (:v2 | :v1) | nil,
  events: (:thin | :snapshot) | nil,
  extra: map() | nil,
  merchant_of_record: boolean() | nil,
  mode: (:test | :live) | nil,
  proration_discounts: (:itemized | :included) | nil,
  provider: String.t(),
  publishable_key: String.t() | nil,
  refunds: (:once | :many) | nil,
  secret_key: String.t(),
  tenant: term() | nil,
  webhook_api: (:v2 | :v1) | nil,
  webhook_secret: String.t() | nil,
  webhook_secrets: [String.t()] | nil
}
```

The struct that `builder/1` returns.

| Field | Type | Required | Default | Description | Derives |
| --- | --- | --- | --- | --- | --- |
| `:provider` | `String.t()` | yes |  |  | `sanitize(trim) validate(not_nil_value, string, not_empty)` |
| `:tenant` | `term()` \| `nil` | no |  |  |  |
| `:mode` | `:test` \| `:live` \| `nil` | no | `:test` |  | `validate(not_nil_value, enum=Atom[test::live])`<br>validator `{MishkaPay.Credentials, :mode}` |
| `:secret_key` | `String.t()` | yes |  |  | `sanitize(trim) validate(not_nil_value, string, not_empty)` |
| `:publishable_key` | `String.t()` \| `nil` | no |  |  | `sanitize(trim) validate(string)` |
| `:merchant_of_record` | `boolean()` \| `nil` | no |  |  | `validate(boolean)` |
| `:automatic_tax` | `boolean()` \| `nil` | no |  |  | `validate(boolean)` |
| `:billing_mode` | `:flexible` \| `:classic` \| `nil` | no |  |  | `validate(enum=Atom[flexible::classic])`<br>validator `{MishkaPay.Checkout, :billing_mode}` |
| `:proration_discounts` | `:itemized` \| `:included` \| `nil` | no |  |  | `validate(enum=Atom[itemized::included])`<br>validator `{MishkaPay.Checkout, :proration_discounts}` |
| `:refunds` | `:once` \| `:many` \| `nil` | no | `:once` |  | `validate(not_nil_value, enum=Atom[once::many])`<br>validator `{MishkaPay.Credentials, :refunds}` |
| `:account_id` | `String.t()` \| `nil` | no |  |  | `sanitize(trim) validate(string, max_len=255, regex=\A[A-Za-z0-9_]+\z)` |
| `:connect_api` | `:v2` \| `:v1` \| `nil` | no | `:v2` |  | `validate(not_nil_value, enum=Atom[v2::v1])`<br>validator `{MishkaPay.Credentials, :api}` |
| `:customer_api` | `:v2` \| `:v1` \| `nil` | no | `:v2` |  | `validate(not_nil_value, enum=Atom[v2::v1])`<br>validator `{MishkaPay.Credentials, :api}` |
| `:events` | `:thin` \| `:snapshot` \| `nil` | no | `:thin` |  | `validate(not_nil_value, enum=Atom[thin::snapshot])`<br>validator `{MishkaPay.Credentials, :events}` |
| `:webhook_api` | `:v2` \| `:v1` \| `nil` | no | `:v2` |  | `validate(not_nil_value, enum=Atom[v2::v1])`<br>validator `{MishkaPay.Credentials, :api}` |
| `:webhook_secret` | `String.t()` \| `nil` | no |  |  | `sanitize(trim) validate(string)` |
| `:webhook_secrets` | `[String.t()]` \| `nil` | no | `[]` |  | `validate(list)`<br>validator `{MishkaPay.Credentials, :secret_list}` |
| `:extra` | `map()` \| `nil` | no | `%{}` |  | `validate(map)` |

# `credentials`

```elixir
@callback credentials(provider :: String.t(), tenant :: term()) :: map() | nil
```

Answers with a map of this struct's fields for `provider` and `tenant` (without `:provider` and
`:tenant`, which come from the call), or `nil` when this plugin has no keys for them.

# `builder`

# `enforce_keys`

# `enforce_keys`

# `example`

A sample %MishkaPay.Credentials{} populated from defaults + type-based fallbacks.

# `fetch`

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

The keys of `provider` for `tenant`, or a `MishkaPay.Errors.MissingCredentials` error when no
plugin answers, the event cannot run, a plugin raises, exits or throws, or no answer comes within
the time limit. An answer that is not valid keys is an `:invalid` class error naming the field.

The plugins run in a task under `MishkaPay.TaskSupervisor`, not linked to the caller, so a
plugin that fails or hangs never takes the caller down. The limit is `opts[:timeout]`, or
`config :mishka_pay, credentials_timeout: ms`, 5 seconds by default; `0` gives no plugin time to
answer, and anything other than milliseconds or `:infinity` raises an `ArgumentError`.

Each fetch is a telemetry span, `[:mishka_pay, :credentials, :start | :stop]`, with `:provider`
and `:tenant`, and on `:stop` the `:outcome`: `:ok`, `:invalid`, or the missing-keys reason
(`:no_answer`, `:cannot_run`, `:raised`, `:exited`, `:timeout`). Never a key.

# `keys`

# `keys`

# `webhook_secrets`

```elixir
@spec webhook_secrets(t()) :: [String.t()]
```

Every webhook secret `keys` accept: `:webhook_secret` first, then `:webhook_secrets`, each once,
without empty ones. `[]` when the keys have none.

---

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