ex_shopify_app
Your entrypoint to create a Shopify Application in Elixir.
Installation
Add ex_shopify_app to your dependencies in mix.exs:
def deps do
[
{:ex_shopify_app, "~> 2.3"}
]
end
The library uses Ecto for the canonical access-token
schema, so :ecto is a required dependency. The durable store
(ExShopifyApp.AccessToken.Repo) runs against your application's Ecto.Repo
(and therefore your :ecto_sql driver); the library itself does not pull in
ecto_sql or a database driver.
Offline access tokens
Shopify's expiring offline access tokens rotate both the access token and the refresh token on every refresh. Shopify retires the previous refresh token once the new one is used, or 30 days after its own first use. If the new refresh token is not durably persisted, the merchant may have to re-authorize the app. The access-token modules are built around that safety concern.
1. Run the migration
Create the shopify_access_tokens table. shopify_domain is the primary key, so there
is exactly one canonical token chain per shop/installation. Delegate to
ExShopifyApp.AccessToken.Migrations so the table can never drift from the schema the
library is compiled against:
defmodule MyApp.Repo.Migrations.CreateShopifyAccessTokens do
use Ecto.Migration
def up, do: ExShopifyApp.AccessToken.Migrations.up()
def down, do: ExShopifyApp.AccessToken.Migrations.down()
end
The migrations are versioned (PostgreSQL only; version tracking uses table comments): up/0 runs every version up to the latest and is a
no-op once you are current, so future releases ship as additional versions you pick
up with another migration. See ExShopifyApp.AccessToken.Migrations for pinning a
specific version.
2. Define your store
defmodule MyApp.ShopifyAccessTokens do
use ExShopifyApp.AccessToken.Repo, repo: MyApp.Repo
end
This generates a module implementing ExShopifyApp.AccessToken.Store with
fetch_token/1, put_token/2, valid_token/2, and refresh_token/2.
3. Persist the token at install / re-auth
{:ok, token} = ExShopifyApp.AccessToken.fetch(shop, session_token, expiring: true)
:ok = MyApp.ShopifyAccessTokens.put_token(shop.shopify_domain, token)
Don't consider the install complete until put_token/2 returns :ok.
4. Get a usable token
valid_token/2 is the safe primary API. It refreshes under a per-shop, cross-node lock
only when needed, and never returns a refreshed token until the new refresh token is
durably committed:
case MyApp.ShopifyAccessTokens.valid_token(shop) do
{:ok, token} -> # use token.access_token
{:error, :reauthorization_required} -> # send the merchant back through OAuth
{:error, reason} -> # operational error; retry / escalate
end
| State | Behaviour |
|---|---|
| Fresh token | Returned as-is, with no lock or HTTP call |
| Stale token | Locked refresh; on failure returns {:error, reason} (or the old token with stale_while_error: true) |
| Hard-expired token | Blocking locked refresh |
| Refresh token expired | {:error, :reauthorization_required} |
| No stored token | {:error, :no_token} |
5. Keep dormant shops alive (optional)
On-demand refreshing only fires when a token is used. A shop with no API activity can silently cross the 90-day refresh-token expiry, after which only the merchant relaunching the app restores access. Add the heartbeat process to your supervision tree to rotate chains before they reach the cliff:
{ExShopifyApp.AccessToken.Heartbeat, store: MyApp.ShopifyAccessTokens}
It scans every :interval (default 6h) for chains whose refresh token expires
within :window (default 7 days) and refreshes them through the store's lock —
safe to run on every node. Lifetime (non-expiring) rows are never touched.
6. Encrypt the stored tokens (optional)
access_token and refresh_token are plaintext columns by default. To encrypt them,
set an encrypted Ecto type for both fields, for example a
Cloak.Ecto.Binary type:
# config/config.exs
config :ex_shopify_app, ExShopifyApp.AccessToken.Token, token_type: MyApp.Encrypted.Binary
The library reads the type at runtime. A binary type needs bytea columns:
defmodule MyApp.Repo.Migrations.EncryptShopifyAccessTokens do
use Ecto.Migration
def change do
execute(
"""
ALTER TABLE shopify_access_tokens
ALTER COLUMN access_token TYPE bytea USING convert_to(access_token, 'UTF8'),
ALTER COLUMN refresh_token TYPE bytea USING convert_to(refresh_token, 'UTF8')
""",
"""
ALTER TABLE shopify_access_tokens
ALTER COLUMN access_token TYPE text USING convert_from(access_token, 'UTF8'),
ALTER COLUMN refresh_token TYPE text USING convert_from(refresh_token, 'UTF8')
"""
)
end
end
Rows stored before this change stay plaintext, and loading them fails. Encrypt them
in a data migration, for example with MyApp.Vault.encrypt!/1.
Safety guarantees
The store provides at-least-once persistence attempt after a refresh response, not
absolute never-loss. Refresh runs inside Repo.transaction/2 holding a
SELECT ... FOR UPDATE row lock for the whole decision: it re-reads the row under the
lock, calls Shopify only if a refresh is still required, and synchronously persists the
new token before committing. The lock serializes refreshes across all processes and
nodes sharing the database.
That transaction runs in a library-supervised task on its own connection, so neither a
caller that rolls back nor one that dies mid-refresh can discard a token Shopify has
already rotated. Still avoid refreshing inside your own Repo.transaction/2 — it pins a
pooled connection for the wait, and logs a warning saying so.
The unavoidable residual risk is a VM/host crash after Shopify responds but before the commit: Shopify and your database cannot share a transaction.
A write that fails after a successful Shopify refresh rolls back, so the row keeps
the token it had. Shopify still accepts that token: a refresh token stays valid until
its replacement is used (for at most 30 days after its first use), and a repeated
migration returns the same token pair for 7 days. The store therefore runs the locked
refresh once more and emits :persistence_retried with a warning log. Only when the
second write also fails does the call return
{:error, {:token_persistence_failed_after_refresh, %ExShopifyApp.AccessToken.PersistenceFailure{}}}
and emit :persistence_failed with an error log (token values redacted). The row
still holds a usable token, so the next call recovers. See
how refresh token rotation works.
Error taxonomy
{:error, :no_token}{:error, :reauthorization_required}{:error, {:refresh_failed, reason}}(retryable;reasonis:timeoutwhen the Shopify request exceeds the 15s request timeout){:error, {:token_persistence_failed_after_refresh, %PersistenceFailure{reason: reason, token: token}}}(retryable; the write failed twice, and the stored token still refreshes){:error, {:lock_timeout, reason}}{:error, {:refresh_crashed, reason}}{:error, {:refresh_unavailable, reason}}(the refresh task exited abnormally)
Telemetry
[:ex_shopify_app, :access_token, :refresh, :start | :stop | :exception][:ex_shopify_app, :access_token, :refresh, :persistence_retried][:ex_shopify_app, :access_token, :refresh, :persistence_failed][:ex_shopify_app, :access_token, :refresh, :stale_while_error]
Metadata carries :shopify_domain, :refresh_generation, and a :result
classification, never token values.
App Events
Report usage events through Shopify's App Events API, keyed by meter handle. Meters can
be billing or tracking-only (analytics). See docs/APP_EVENTS.md; the entry point
is ExShopifyApp.AppEvents.
Billing
Shopify-native metered billing: report usage through App Events and
read the merchant's active plan from the Admin API. See docs/BILLING.md
for the full guide; the entry points are ExShopifyApp.Billing and
ExShopifyApp.Billing.Subscription.
Storefront API
Query the Storefront API server-side with the shop's offline access token. See
docs/STOREFRONT.md; the entry point is ExShopifyApp.Storefront.
Testing
ExShopifyApp.Testing signs session tokens, webhooks and app proxy queries the way
Shopify does, so your tests can send requests through the real plugs. See
docs/TESTING.md.
Docs
Documentation can be generated with ExDoc and published on HexDocs.