Keep payments in Ash resources and Mishka CMS
v0.0.1
With Ash, Mishka Pay, the Elixir and Ash payment SDK, keeps payments, subscriptions, customers and disputes in your own resources. It reads each object again from the provider whenever a webhook says something changed, and stores every webhook in an inbox that an Oban job works with retries. Inside Mishka CMS, the same resources belong to one site each. This guide adds the resources, runs their actions, gates content with a subscription policy, keeps sites apart and shows rows live.
Before you begin
- An Ash project with
ash_postgresandash_oban, and Oban in the supervision tree. - Mishka Pay installed with keys and the webhook endpoint. See Get Started.
- A webhook for each site. See Receive and verify webhooks.
Add the resources
The installer writes a MyApp.Pay domain with five resources (a webhook inbox, payment, subscription, customer and dispute), then you generate and run the migrations:
mix igniter.install ash_postgres ash_oban
mix igniter.install mishka_pay --ash --pubsub
mix ash.codegen mishka_pay
mix ash.migrateThe installer also adds the inbox's Oban queue, each resource's listener to the application's children and :mishka_pay to the formatter's import_deps. Add --admin to also get products, prices, coupons, promotion codes, payment links and invoices that a site manages from its admin. A resource looks like this:
defmodule MyApp.Pay.Payment do
use Ash.Resource,
domain: MyApp.Pay,
data_layer: AshPostgres.DataLayer,
extensions: [MishkaPay.Ash.Resource]
mishka_pay do
kind :payment
end
postgres do
table "pay_payments"
repo MyApp.Repo
end
endBy hand, supervise the listeners of the domain (each resource makes <Resource>.MishkaPayListener) and add the queue to Oban:
children =
[MishkaPay.Providers.Stripe, MyApp.Pay.Keys] ++
MishkaPay.Ash.listeners(MyApp.Pay)
config :my_app, Oban,
repo: MyApp.Repo,
queues: [mishka_pay_inbox: 5],
plugins: [{Oban.Plugins.Cron, []}]Never write the kind's attributes, actions or listener yourself. What you define with the same name is kept, so you can change one. The provider's fields are never an action's input, and a row's provider id is provider_id.
Run the actions of a kind
| Kind | Actions |
|---|---|
| inbox | Stores each verified webhook once and works it with up to 10 tries, keeping the reason of each failure on the row. |
| payment | :sync, :start_checkout, :refund, and the read-only :refunds |
| subscription | :sync, :cancel, :resume, :change, :pause, :resume_collection, and the read-only :upcoming_invoice and :preview_change |
| customer | :register, :sync, :edit, :remove, :portal |
| dispute | :sync, :submit_evidence, :accept |
| product, price, coupon, promotion code, payment link, invoice | :sync, :add, :edit or :remove, plus an invoice's :finalize, :send, :pay, :void and :mark_uncollectible (the --admin set) |
Every provider kind also has :resync, which reads its row again, and resync_after: 6 adds an hourly trigger that reads rows still open at the provider when no webhook came. Every action asks the provider first, writes what the provider answered, and announces mishka_pay:<kind>:changed afterwards unless you set announce? false.
{:ok, %MishkaPay.Checkout{url: url}} =
MyApp.Pay.Payment
|> Ash.ActionInput.for_action(
:start_checkout,
%{checkout: checkout_map},
actor: user
)
|> Ash.run_action()
{:ok, row} =
row
|> Ash.Changeset.for_update(:cancel, %{at: :now})
|> Ash.update()checkout_map is the map MishkaPay.checkout/1 takes. With code_interface? on (the default), each action is also a function of the resource, such as MyApp.Pay.Subscription.cancel!(row, %{at: :now}). A bad input comes back as an Ash error on its field.
A customer's :register reads again the customer the site already has for that reference instead of making a second one, so it is safe to call on every purchase. The options of the mishka_pay section are actions, listen?, announce?, code_interface?, belongs_to_user, tenant_from, resync_after and, for the inbox, keep_events_for (30 days; processed events are deleted daily, failed ones stay).
Know who paid and who has access
Add belongs_to_user to a payment or subscription resource. :start_checkout then names the actor as the checkout's owner, the provider keeps the owner, and every sync writes it into the user attribute.
mishka_pay do
kind :subscription
belongs_to_user MyApp.Accounts.User
end
policies do
policy action(:read) do
authorize_if {MishkaPay.Ash.Subscribed,
resource: MyApp.Pay.Subscription}
end
policy action(:download) do
authorize_if {MishkaPay.Ash.Subscribed,
resource: MyApp.Pay.Subscription,
product: "prod_pro"}
end
end
MishkaPay.Ash.subscribed?(
MyApp.Pay.Subscription,
current_user,
tenant: site.id
)Access is :active, or :trialing until the trial ends. Pass statuses: [:active, :trialing, :past_due] to keep it while the provider retries a failed renewal. product: and price: narrow it to a tier. Each check is one query, so a cancel that a webhook brought counts at once. A subscription row has the calculations active?, on_trial? and canceling? for filters, sorts and admin tables, and keeps price_ids and product_ids. A payment row keeps checkout_id, price_ids and product_ids, which is what a shop delivers.
Keep sites apart
Mishka CMS serves many sites from one install. Mishka Pay supports that two ways.
With Ash multitenancy on your own attribute, every action runs with tenant: site.id, the keys are read for that site and each webhook's row is synced inside the site its URL names. The same Stripe object in two sites is two rows.
attributes do
attribute :site_id, :uuid, allow_nil?: false, public?: true
end
multitenancy do
strategy :attribute
attribute :site_id
endKeep the inbox global, because a webhook arrives before any site is chosen. Without Ash multitenancy, name your own column and each create action writes the site there too:
mishka_pay do
kind :payment
tenant_from :site_id
end
relationships do
belongs_to :site, MyApp.Sites.Site
endEvery call still names the site, and a site's keys, refund rule and Stripe Tax settings come from your keys plugin, from the site's own settings. Changing a site's keys needs no restart. An extension for Mishka CMS lists its keys plugin and MishkaPay.Ash.listeners(MyExtension.Pay) in its application's plugins/0 and children, and adds mishka_pay_inbox to Oban's queues. Mishka CMS starts the plugin registry of Mishka Installer and Mishka Pay's application starts the providers, so the extension lists only its own.
Show changes live
defmodule MyApp.Pay.Broadcast do
use MishkaPay.PubSub, pubsub: MyApp.PubSub
end
# in a LiveView of the site's admin
Phoenix.PubSub.subscribe(
MyApp.PubSub,
MishkaPay.PubSub.topic(:payment, site.id)
)
def handle_info(
{:mishka_pay, :payment, %{payment: payment, record: row}},
socket
),
do: ...Supervise MyApp.Pay.Broadcast after the PubSub. Each change goes to the kind's topic and to the site's topic. Mishka Pay has no admin pages of its own. A screen built with Mishka Gervaz, or any Ash UI, lists and acts on these resources like any other, with the primary :read and the kind's actions as buttons. Put your own policies on them.
Next steps
- Keys and options: the per-site settings the keys plugin answers.
- Errors and telemetry: the inbox telemetry and Ash error messages.
- How Mishka Pay works: why the provider is the source of truth.