Upgrading from Shopifex 2.x to 3.0

Copy Markdown View Source

Shopifex 3.0 replaces the 2.x OAuth/Guardian auth stack with Shopify's managed installation (token exchange), adds expiring offline access tokens with background refresh, moves webhooks and billing to the GraphQL Admin API, and targets a Phoenix 1.8 baseline. This is a breaking upgrade — read CHANGELOG.md's "Breaking changes" section for the full list before you start. This guide gives the concrete steps.

1. Dependency

def deps do
  [
    {:shopifex, "~> 3.0"}
  ]
end
mix deps.update shopifex

2. Migrations

Add the token-lifecycle columns to your shop table. All four are nullable so existing (non-expiring) installs round-trip unchanged — they keep working on their non-expiring token (see §10 to move them onto expiring tokens):

mix ecto.gen.migration add_token_lifecycle_to_shops
defmodule MyApp.Repo.Migrations.AddTokenLifecycleToShops do
  use Ecto.Migration

  def change do
    alter table(:shops) do
      add :token_expires_at, :utc_datetime
      add :refresh_token, :string
      add :refresh_token_expires_at, :utc_datetime
    end
  end
end

Shopify may omit scope from a token response, and 3.0 persists it as nil in that case, so the scope column must be nullable. The 2.x installer created it nullable (add :scope, :string); only if you added a NOT NULL constraint yourself, drop it in the same migration:

modify :scope, :string, null: true, from: {:string, null: false}

(Replace :shops with your table name — the 2.x installer used :shopify_shops.)

Add the cross-node token lease table. It is required by Shopifex.Plug.ManagedInstall as well as by background/reactive refresh in Shopifex.Auth: the plug takes the per-shop lease around every id_token exchange so concurrent embedded loads of one shop exchange once (and a first install inserts the shop once), and the same lease serializes refresh-token grants. Without the table every load that needs an exchange raises on the missing relation:

mix ecto.gen.migration create_shopifex_token_refresh_leases
defmodule MyApp.Repo.Migrations.CreateShopifexTokenRefreshLeases do
  use Ecto.Migration

  def change do
    create table(:shopifex_token_refresh_leases, primary_key: false) do
      add :shop_url, :string, primary_key: true
      add :owner, :string, null: false
      add :lease_expires_at, :utc_datetime_usec, null: false
    end
  end
end

If you use the billing (PaymentGuard) flow and run on more than one node, add the persistent redirect-after table so a payment confirmation that lands on a different node than the one that started checkout doesn't drop the grant (see Shopifex.RedirectAfter.Ecto):

mix ecto.gen.migration create_shopifex_charge_redirects
defmodule MyApp.Repo.Migrations.CreateShopifexChargeRedirects do
  use Ecto.Migration

  def change do
    create table(:shopifex_charge_redirects, primary_key: false) do
      add :charge_id, :bigint, primary_key: true
      add :redirect_after, :text, null: false
      add :inserted_at, :utc_datetime, null: false
    end
  end
end

Run them:

mix ecto.migrate

3. Schema changesets

Declare the three new columns on your shop schema, and cast them in changeset/2 (and, if scope was required before, stop requiring it):

schema "shops" do
  field :url, :string
  field :access_token, :string
  field :scope, :string
  field :token_expires_at, :utc_datetime
  field :refresh_token, :string
  field :refresh_token_expires_at, :utc_datetime
  # ...your other fields
end

def changeset(shop, attrs) do
  shop
  |> cast(attrs, [
    :url,
    :scope,
    :access_token,
    :token_expires_at,
    :refresh_token,
    :refresh_token_expires_at
  ])
  |> validate_required([:url, :access_token])
end

Grant and Plan changesets generated by 2.x's mix shopifex.install required charge_id/remaining_usages (Grant) and usages (Plan). 3.0 treats these as nullable — unlimited plans have no usage cap, and Shopifex.Shops.create_shop_grant/2 never supplies a charge_id. Update your changesets' validate_required/2 lists to drop those three fields (or regenerate with mix shopifex.gen.schemas and diff). The grants.charge_id column should be :bigint in the migration — Shopify charge ids exceed Postgres's int4 range — while the Ecto field stays :integer (Ecto has no :bigint field type; :integer reads a bigint column fine).

4. Remove what 3.0 dropped

  • Guardian. Remove the dependency and any config :my_app, MyApp.Guardian, ... block. Shopifex no longer mints an app JWT; session tokens (id_token) are verified directly.
  • Plug.Static, at: "/shopifex-assets" in your endpoint. The built-in auth/payment/redirect pages now load App Bridge and Polaris from cdn.shopify.com — there's no vendored bundle to serve.
  • neuron, if you added it yourself for GraphQL — Shopifex 3.0 ships its own GraphQL transport (Shopifex.API.graphql/3) and no longer uses it internally.
  • phoenix_view, phoenix_html_helpers, plug_cowboy, if pinned directly — Shopifex 3.0 no longer depends on them (function components + Bandit). Check CHANGELOG.md's "Breaking changes" entry for the full drop list before removing anything your own app still uses directly.

5. Config keys

Review these against your config/config.exs / runtime.exs:

  • api_version — defaults to "2026-07". Set explicitly if you need to pin an older Admin API version during rollout.
  • redirect_after_agent — defaults to the in-memory Shopifex.RedirectAfterAgent. Set Shopifex.RedirectAfter.Ecto on any multi-node deploy (see §2).
  • configure_webhooks_on_exchange? — defaults to true (idempotent webhook reconcile on every managed-install token re-exchange). Set false to skip the reconcile after first install.
  • webhook_topics — if you declare webhooks in shopify.app.toml ([webhooks]) instead of letting Shopifex register them via GraphQL, set this to []. Registering the same topic both ways causes duplicate subscriptions (and duplicate delivery).
  • old_secret — set during an app-secret rotation so HMAC/session-token/ charge-binding verification accepts both the old and new secret.
  • hmac_timestamp_tolerance_seconds — defaults to 90. See "Reloads of a signed admin URL" below.
  • ensure_scopes_on_missing — defaults to :raise in 3.0 (2.x behaviour was to redirect through legacy OAuth). Set to :redirect to keep the 2.x bounce, or pass on_missing_scopes: :redirect to the plug directly.
  • redirect_uri / reinstall_uri — only needed if you keep the legacy OAuth fallback routes (/auth/install, /auth/update); managed installation doesn't use them.

Reloads of a signed admin URL

Shopify signs the URL of each app load from the admin with an hmac and a timestamp. ShopifySession rejects that signed query once the timestamp is older than hmac_timestamp_tolerance_seconds. 2.x checked only the hmac.

The rejection also applies when the admin iframe requests the same URL again after the tolerance: a frame reload, window.location.reload(), or a LiveView full-page reload. When the id_token in that URL has expired as well, ManagedInstall passes the request on and ShopifySession renders select_store.html.

To keep these reloads working, add a plug between :managed_install and :shopify_session for embedded GET requests. When the request carries an id_token that Shopifex.SessionToken.verify/1 rejects, or a signed query that Shopifex.Plug.timestamp_fresh?/2 rejects, the plug responds with a page that loads App Bridge, calls shopify.idToken(), and requests the same URL again with the new id_token. Mark that retry with a parameter holding the server time at which the page was rendered, and skip the page only while that time is recent. The marker stays in the iframe URL after the retry, so a marker without a time disables the page for every later reload of that URL.

Raising hmac_timestamp_tolerance_seconds also keeps these reloads working. It extends the time in which a copied signed URL is accepted.

6. Router

ShopifexWeb.Routes.auth_routes/1 now pipes /auth through [:shopifex_browser, :managed_install, :shopify_session] — token exchange runs automatically, no router changes needed beyond re-running ShopifexWeb.Routes.pipelines() to pick up the new :managed_install, :shopify_proxy, :shopify_embedded, and :validate_install_hmac pipelines.

If your router uses helpers: false (no generated Router.Helpers, the Phoenix 1.7+ default), Shopifex 3.0 no longer needs route helpers anywhere in the library — Shopifex.Plug.PaymentGuard builds its plan-picker redirect from path_prefix and URI.encode_query/1 directly.

If you called the old Shopifex.Plug.FetchFlash (or its :fetch_flash pipeline entry) expecting 2.x behaviour: it now delegates to Phoenix.Controller.fetch_flash/2. On Phoenix 1.7+ the old implementation was already a no-op and a subsequent put_flash raised — this fixes that, it doesn't change your pipeline declaration.

7. Billing

If you use the standard select_plan/2 action (use ShopifexWeb.PaymentController with no override), nothing changes. If you defined a custom select-plan action, it must now call ShopifexWeb.PaymentController.bind_charge/4 before redirecting the merchant to Shopify's confirmation URL:

def my_select_plan(conn, %{"plan_id" => plan_id, "redirect_after" => redirect_after}) do
  shop = Shopifex.Plug.current_shop(conn)
  plan = MyApp.Shops.PaymentGuard.get_plan(plan_id)

  {:ok, charge} = create_charge(shop, plan)
  ShopifexWeb.PaymentController.bind_charge(shop, plan, charge["id"], redirect_after)

  # ... redirect to charge["confirmation_url"]
end

complete_payment/2 now verifies the charge is actually active in Shopify (via the overridable verify_charge/3 callback) before creating a Grant, in addition to checking the signed binding. If your tests stub Shopify's GraphQL endpoint, add a stub response for the node(id: ...) status query verify_charge/3 sends (AppSubscription.status / AppPurchaseOneTime.status), or complete_payment/2 will see an unrecognised response and reject the charge with 403.

use_grant/2 (Shopifex.PaymentGuard) can now return nil (the grant's remaining_usages was already exhausted — e.g. a race between two guarded requests); if you overrode use_grant/2, make sure your implementation handles a nil result the same way the plug does (treat it as "no grant").

Charge ids flow as integers through the grant/redirect path. The GraphQL GID's trailing segment is a string, but complete_payment/2 coerces it with Integer.parse/1; the :redirect_after_agent store, create_grant/3 (spec charge_id :: pos_integer()), and the Grant.charge_id :bigint column all key on that integer. Only verify_charge/3 receives the string form (to build the GID). If you implement a custom :redirect_after_agent, key it by the integer charge_id — keying by string will miss the lookup and silently drop the grant.

8. API

If you called Shopify's REST Admin API directly (webhooks.json, recurring_application_charges, application_charges) — those endpoints were removed from Shopifex. Use Shopifex.API.graphql/3 for everything; it keeps the access token fresh (proactive + reactive refresh) and targets the configured api_version.

Shopifex.API.graphql/3's error tuple gained a new terminal case: {:error, {:token_refresh_failed, reason}}, returned when a terminal refresh failure (expired/missing refresh token, a 400/401 from Shopify's token endpoint, or the shop not found) stops the request before it's sent — instead of a generic {:error, {401, body}} or a raised error. Add a clause for it wherever you pattern-match Shopifex.API.graphql/3's error tuples.

Shopifex.Shops.delete_webhook/2 now takes a GraphQL id (a GID string, not a REST webhook id) and returns {:ok, id} | {:error, errors}. get_current_webhooks/1 returns %{id, topic} maps with GraphQL enum topics (e.g. "ORDERS_CREATE", not "orders/create").

9. LiveView

The LiveView session key changed from "current_shop" (2.x) to "shop_url" and "session_token". If you read the raw session map anywhere (rather than socket.assigns.current_shop), update the key.

For embedded apps, prefer the :embedded on_mount hook over the default :assign_shop_to_socket: it reads the shop from the Phoenix session set during the HTTP request instead of requiring tokens in the URL or LiveSocket connect params, and redirects to /auth (respecting path_prefix) if no shop is found:

live_session :embedded,
  on_mount: [{ShopifexWeb.LiveSession, :embedded}],
  session: {ShopifexWeb.LiveSession, :put_shop_in_session, []} do
  live "/", MyAppLive
end

(ShopifexWeb.Routes.shopifex_live_session/3 keeps the 2.x-style :assign_shop_to_socket hook; use a plain live_session as above to opt into :embedded.)

@session_token is nil under :embedded — don't rely on it for navigation; use a plain <.link navigate={...}> between LiveViews in the same live_session.

10. Backfill legacy shops onto expiring tokens (optional)

Shops installed before expiring offline tokens existed have nil expiry columns. They keep working on their non-expiring access token, but they are not upgraded automatically — Shopifex.Plug.ManagedInstall treats a nil token_expires_at as fresh, so an embedded load does not re-exchange them (unless the shop's stored scope lacks a configured scope, in which case the scope re-exchange also yields an expiring pair). To move them onto expiring tokens (and gain background refresh), back-fill with Shopifex.Auth.migrate_to_expiring_token/1, or have the merchant reinstall.

The exchange is one-way and never retried — Shopify destroys the non-expiring token as it issues the expiring pair. Idempotence lives in the selection, not the call: a shop that already has a token_expires_at returns {:error, :already_expiring}.

import Ecto.Query

MyApp.Repo.all(from s in MyApp.Shop, where: is_nil(s.token_expires_at))
|> Enum.each(fn shop ->
  case Shopifex.Auth.migrate_to_expiring_token(shop) do
    {:ok, _migrated} -> :ok
    {:error, reason} -> MyApp.report_migration_failure(shop, reason)
  end
end)

Run it as a one-off (e.g. from bin/my_app remote), not on the hot request path. See Shopifex.Auth.migrate_to_expiring_token/1 for the full list of {:error, reason} values.

11. Smoke-test checklist after upgrading

  • Install a fresh dev store end-to-end (/auth → managed installation → landing page loads with @current_shop set).
  • Token refresh — wait past the ~1h access-token TTL (or force it by editing token_expires_at in the DB) and confirm the next embedded load or background API call re-exchanges/refreshes without an error.
  • Webhook delivery — trigger a subscribed topic from the dev store and confirm your handle_topic/3 clause fires; confirm app/uninstalled, shop/redact, customers/redact, customers/data_request are all still registered.
  • App proxy, if used — hit the proxy URL from the storefront and confirm Shopifex.Plug.current_shop/1 resolves the shop.
  • Billing — select a plan, approve the test charge in Shopify, and confirm /payment/complete creates a Grant and unblocks the guarded route (not just that Shopify redirects back with a 200).
  • Uninstall webhook — uninstall the dev store's app and confirm the shop record (and any dependent data) is cleaned up.
  • Iframe reload — open an app page from the admin, wait longer than hmac_timestamp_tolerance_seconds and the one-minute id_token lifetime, and reload only the app iframe. Confirm the page renders again and select_store.html does not appear.