Metadata-Version: 2.4
Name: django_shopify_app
Version: 2.18.1
Summary: A django app with all the tools required to make a Shopify app
Author: Santiago Fernandez
License-Expression: MIT
Project-URL: Homepage, http://pypi.python.org/pypi/django_shopify_app/
Classifier: Framework :: Django
Classifier: Framework :: Django :: 5.2
Classifier: Framework :: Django :: 6.0
Classifier: Framework :: Django :: 6.1
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: Django<7,>=5.2
Requires-Dist: djangorestframework>=3.14
Requires-Dist: PyJWT>=2.0
Requires-Dist: django-crm-events
Requires-Dist: cryptography>=42.0.0
Requires-Dist: requests>=2.25
Provides-Extra: sentry
Requires-Dist: sentry-sdk>=2.0; extra == "sentry"

# django-shopify-app

A reusable Django package for building Shopify apps. Handles OAuth, token exchange, webhook management, session token validation (JWT), and Shopify API interactions.

## Installation

```bash
pip install django-shopify-app
```

Supports Python 3.10+ and Django 5.2 LTS through 6.1. The floor tracks the oldest Django branch that still receives security fixes, so expect it to move when a branch reaches end of life.

The package is safe under Gunicorn's `gthread` worker and doesn't depend on ShopifyAPI (the `shopify` Python library). If your app uses that library, install it yourself, and don't use its sessions (`shopify.Session.setup()`, `Session.temp()`, `ShopifyResource.activate_session()`) while serving requests. The library keeps the active shop and the app's API key and secret in class attributes that every thread of a process shares, so one request can pick up another request's shop or credentials. Use the shop's API helpers below instead.

Add the app in settings.py:

```python
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'shopify_app',
    'shops',
]
```

## Settings

```python
# Required
SHOPIFY_API_KEY = config('SHOPIFY_API_KEY')
SHOPIFY_API_SECRET = config('SHOPIFY_API_SECRET')
SHOPIFY_APP_HOST = 'https://your-app.com'
SHOPIFY_SHOP_MODEL = 'shops.Shop'              # Must inherit from ShopBase
SHOPIFY_WEBHOOK_CALLBACK = 'shops.webhooks.webhook_entry'
SHOPIFY_GDPR_WEBHOOK_CALLBACK = 'shops.webhooks.gdpr_webhook_entry'
SHOPIFY_TOKEN_DB_ALIAS = 'shopify_tokens'       # DATABASES alias for token writes; see
                                               #   "Token database connection" below
CACHES = {'default': {...}}                    # Shared backend (Redis, Memcached, DB); see
                                               #   "Webhook deduplication" below

# Optional
SHOPIFY_APP_SCOPES = ['read_products', 'read_orders']
SHOPIFY_WEBHOOK_TOPICS = ['products/update', 'app/uninstalled']
SHOPIFY_WEBHOOK_HOST = 'https://your-app.com'  # Defaults to SHOPIFY_APP_HOST
SHOPIFY_API_VERSION = '2026-07'                # Pin this; see note below

# Token exchange (recommended for embedded apps)
SHOPIFY_TOKEN_EXCHANGE = False                 # Default: False
SHOPIFY_DASHBOARD_PATH = '/dashboard'          # Default: '/dashboard'

# Expiring offline access tokens (Shopify, Dec 2025)
SHOPIFY_EXPIRING_TOKENS = False                # Default: False — opt into expiring
                                               #   offline tokens + refresh rotation
SHOPIFY_TOKEN_REFRESH_SKEW = 300               # Default: 300s — refresh this many
                                               #   seconds before access-token expiry
SHOPIFY_HTTP_TIMEOUT = (5, 30)                 # Default: (connect, read). Applies to ALL
                                               #   outbound Shopify calls. Read is generous so
                                               #   a processed refresh isn't abandoned.
SHOPIFY_ENCRYPT_ACCESS_TOKENS = False          # Default: False — write shopify_token
                                               #   encrypted. Turn it on once every
                                               #   process runs 2.16.0 or later. See
                                               #   "Token encryption".
SHOPIFY_TOKEN_ENCRYPTION_KEY = config('SHOPIFY_TOKEN_ENCRYPTION_KEY')
                                               # Required. Fernet key (or a list, to
                                               #   rotate) encrypting shopify_token and
                                               #   refresh_token at rest. See "Token
                                               #   encryption".
                                               #   May be a list of keys for rotation.
                                               # Generate: python -c "from cryptography.fernet
                                               #   import Fernet; print(Fernet.generate_key().decode())"

# Per-shop credential overrides (replaces DB overwrite fields)
SHOPIFY_CREDENTIALS_OVERRIDES = {              # Default: {}
    'shop.myshopify.com': {
        'api_key': '...',
        'api_secret': '...',
    },
}

# Staff bypass
SHOPIFY_STAFF_BYPASS = False                   # Default: False
SHOPIFY_STAFF_BYPASS_METHODS = ['GET', 'HEAD', 'OPTIONS']  # Default; None allows all methods
SHOPIFY_STAFF_SHOP_ATTR = 'admin_shop'         # Default: 'admin_shop'

# Sentry (shopify_app.sentry; see "Sentry" below)
SHOPIFY_SENTRY_SHOP_DOMAIN_ARGUMENTS = ('shopify_domain',)  # Default. Task parameters
                                               #   holding the shop's domain or bare name
SHOPIFY_SENTRY_SHOP_ID_ARGUMENTS = ('shop_id',)  # Default. Task parameters holding a Shop pk
```

**API version.** Shopify supports each stable API version for 12 months. Set `SHOPIFY_API_VERSION` explicitly and bump it on a schedule; the package default (`ShopifyAppConfig.DEFAULT_API_VERSION`) is only updated with package releases. The `shopify_app.W001` system check, run by `manage.py check`, `runserver` and `migrate`, warns when the configured version has reached end of life.

## ShopBase model

Your app must define a Shop model that inherits from `ShopBase`:

```python
from shopify_app.models import ShopBase

class Shop(ShopBase):
    # Add your custom fields
    plan_name = models.CharField(max_length=50, default='')

    def installed(self, request=None):
        """Called when the app is installed on a shop for the first time."""
        self.update_webhooks()
        self.crm_on_install()

    def token_reacquired(self, request=None):
        """Called instead of installed() when a shop whose rejected token was cleared
        gets a new one: the store reopened, or the app was reinstalled after a lost
        app/uninstalled webhook. Defaults to installed(); override it to skip install
        work that shouldn't run twice."""
        self.update_webhooks()

    def on_user_login(self, user_data, request=None):
        """Called when a Shopify user opens the app.

        user_data contains: id, first_name, last_name, email,
        email_verified, account_owner, locale, collaborator
        """
        self.crm_on_login(user_data)
```

### Fields

| Field | Type | Description |
|-------|------|-------------|
| `shopify_domain` | CharField | The shop's `.myshopify.com` domain. Unique; a subclass that redeclares the field must keep `unique=True` |
| `shopify_token` | EncryptedCharField | Offline access token. Written encrypted while `SHOPIFY_ENCRYPT_ACCESS_TOKENS` is on; rows written in plaintext are still read |
| `access_scopes` | CharField | Granted OAuth scopes |
| `seen_users` | JSONField | Tracks user logins `{user_id: {last_login: ...}}` |
| `refresh_token` | EncryptedCharField | Refresh token for expiring offline tokens (encrypted at rest). Empty unless `SHOPIFY_EXPIRING_TOKENS` is on |
| `token_expires_at` | DateTimeField | When the offline access token expires (expiring tokens only) |
| `refresh_token_expires_at` | DateTimeField | When the refresh token expires — 90-day window (expiring tokens only) |
| `refresh_token_rejected_at` | DateTimeField | When Shopify first rejected the shop's stored token: the refresh token (dead token or app uninstalled; the token is kept; also set, without calling Shopify, on a refresh attempt after `refresh_token_expires_at`), or a permanent token it refused to migrate (the token is cleared). Cleared when a new token is stored. Read it through `shop.reauth_required` |

### Token encryption

`refresh_token` is always encrypted in the database with Fernet, and `shopify_token` is while `SHOPIFY_ENCRYPT_ACCESS_TOKENS` is on, so a database or backup leak doesn't hand out Admin API access. The key is `SHOPIFY_TOKEN_ENCRYPTION_KEY`, and every app needs it: without it no token can be saved, so the `shopify_app.E003` system check stops the app at startup.

```bash
python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
```

```python
SHOPIFY_ENCRYPT_ACCESS_TOKENS = True  # Default: False
```

`SHOPIFY_ENCRYPT_ACCESS_TOKENS` is off by default, and the `shopify_app.W002` system check warns while it is. The field reads plaintext and encrypted tokens alike, whatever the setting; the setting only decides how a token is written. It exists because a process on a version below 2.16.0 can't read an encrypted token: it would send the ciphertext to Shopify and get a 401. So turn it on once every web process and worker runs 2.16.0 or later, then encrypt the tokens already stored:

```bash
python manage.py encrypt_shop_tokens
```

- **Keep the key in a secret and back it up.** Losing it loses every stored token: each shop gets a new one only when a merchant opens the app.
- **To rotate**, set a list: the first key encrypts, all are tried when decrypting.
- **Reads go through the field**, so `shop.shopify_token` is the token as before. Empty values (`None`, `""`) are stored as they are, so `shopify_token__isnull` and the token state filters below work.
- **A lookup by token value never matches an encrypted row** (`Shop.objects.filter(shopify_token=token)`): the same token encrypts to a different value each time.
- **Don't redeclare `shopify_token`** in your Shop model as a plain field: the `shopify_app.E004` system check refuses it.

> **Note:** `refresh_token`, `token_expires_at` and `refresh_token_expires_at` were added in 2.4.0, `refresh_token_rejected_at` in 2.7.0. Because `ShopBase` is abstract, run `makemigrations` in your app to add the columns to your concrete Shop model.

### Saving a shop

Since 2.11.0, a plain `shop.save()` (no `update_fields`) of an existing shop leaves out the token fields: `shopify_token`, `refresh_token`, `token_expires_at`, `refresh_token_expires_at` and `refresh_token_rejected_at` (`shopify_app.models.TOKEN_FIELDS`). Another worker may refresh the token between your load and your save, and writing the old refresh token back (Shopify has already retired it) would make the next refresh fail.

To write token fields, name the ones you changed, for example when your uninstall handler clears the token:

```python
shop.shopify_token = None
shop.refresh_token_rejected_at = None
shop.save(write_tokens=["shopify_token", "refresh_token_rejected_at"])
```

- `write_tokens` adds the named token fields to an otherwise normal save. `update_fields` works as in Django. `write_tokens=True` writes every loaded column, stale token fields included.
- Admin, ModelForm and serializer edits of token fields go through a plain save, so they are dropped too. `ShopTokenAdminMixin` shows them read-only in the admin (see [Admin helpers](#admin-helpers)).
- Inserts and `force_insert` write every field. The package's own token writes save exactly the fields they set.
- The plain save passes `update_fields`, so saving a shop whose row was deleted raises `DatabaseError` instead of inserting it again, and save signal receivers get that field set instead of `None`.

### Querying by token state

Since 2.12.0, `ShopBase.objects` is built from `ShopQuerySet`, which filters shops by the state of their offline token:

```python
Shop.objects.with_token()       # holds an access token (not None or "")
Shop.objects.reachable()        # holds a token Shopify hasn't rejected, refresh token not expired (see shop.reauth_required)
Shop.objects.permanent_token()  # holds a permanent (non-expiring) token: no refresh token stored
Shop.objects.expiring_token()   # holds an expiring token: a refresh token is stored
```

The same filters are `Q` objects in `shopify_app.models`, for conditions inside expressions (conditional aggregates, `Case`/`When`) and for apps whose manager isn't a `ShopQuerySet`:

| `Q` object | Matches |
|---|---|
| `HAS_TOKEN` | `shopify_token` is neither `None` (uninstall handlers, a rejected migration) nor `""` (the field default) |
| `NO_REFRESH_TOKEN` | `refresh_token` is `None` or `""`. An encrypted refresh token can't be filtered on, but empty values are stored unencrypted |
| `PERMANENT_TOKEN` | `HAS_TOKEN & NO_REFRESH_TOKEN` |
| `EXPIRING_TOKEN` | `HAS_TOKEN & ~NO_REFRESH_TOKEN` |
| `REFRESH_TOKEN_EXPIRED` | `~NO_REFRESH_TOKEN` and `refresh_token_expires_at` is past, by the database clock when the query runs (`Now()`). Shopify won't refresh these. The queryset form of `shop.refresh_token_expired` |
| `REACHABLE` | `HAS_TOKEN`, `refresh_token_rejected_at` is null, and not `REFRESH_TOKEN_EXPIRED`. A store that stays closed drops out once its refresh token expires (90 days); permanent tokens have no expiry and stay in |

```python
from django.db.models import Count
from shopify_app.models import EXPIRING_TOKEN, PERMANENT_TOKEN

Shop.objects.aggregate(
    permanent=Count("pk", filter=PERMANENT_TOKEN),
    expiring=Count("pk", filter=EXPIRING_TOKEN),
)
```

The manager adds no migration: Django doesn't record it (`use_in_migrations` is off). If your Shop model declares its own `objects`, it replaces this one; build yours from a `ShopQuerySet` subclass to keep the methods:

```python
from shopify_app.models import ShopBase, ShopQuerySet

class MyShopQuerySet(ShopQuerySet):
    def on_paid_plan(self):
        return self.exclude(plan_name="")

class Shop(ShopBase):
    objects = MyShopQuerySet.as_manager()
```

The package's own code filters with the `Q` objects, so it works with any manager.

### API methods

All REST methods replace `api_version` in the path automatically. The path must start with `/`, and a GraphQL `api_version` must be `YYYY-MM` or `unstable`; anything else raises `ValueError` before a request is sent, so the access token only ever goes to the shop's own host:

```python
# REST API
shop.get('/admin/api/api_version/products.json')
shop.post('/admin/api/api_version/products.json', data={...})
shop.put('/admin/api/api_version/products/123.json', data={...})
shop.patch('/admin/api/api_version/products/123.json', data={...})
shop.delete_request('/admin/api/api_version/products/123.json')

# GraphQL
response = shop.graphql(query='{ shop { name } }')
response = shop.graphql(query=mutation, variables={...}, api_version='2025-04')
# A document with several operations: pick the one to run
response = shop.graphql(query=document, variables={...}, operation_name='GetShop')
```

The helpers return the `requests` response and don't raise on an error status. Call `response.raise_for_status()` or check `response.status_code` before reading `response.json()`.

### Webhook management

```python
shop.update_webhooks()     # Deactivate all + reactivate from SHOPIFY_WEBHOOK_TOPICS
shop.activate_webhooks()   # Alias for update_webhooks()
shop.deactivate_webhooks() # Remove all registered webhooks
```

### CRM events

Built-in hooks for CRM lifecycle events (via `django-crm-events`):

```python
shop.crm_on_install()
shop.crm_on_uninstall(users=[])
shop.crm_on_login(user_data)
shop.crm_on_billing_plan_change(plan_price)
```

### Other properties

```python
shop.shopify_app_api_key      # Returns per-shop override or global setting
shop.shopify_app_api_secret   # Returns per-shop override or global setting
shop.api_version              # From SHOPIFY_API_VERSION setting
shop.host                     # Base64-encoded admin URL for App Bridge
shop.get_shop_data()          # Fetch shop details from Shopify REST API
shop.valid_access_token()     # Access token, auto-rotated if expiring + stale
shop.reauth_required          # True when Shopify rejected the refresh token or it expired (see below)
shop.refresh_token_expired    # True when the refresh token is past refresh_token_expires_at
```

All REST/GraphQL helper methods (`get`/`post`/`put`/`patch`/`delete_request`/`graphql`) send `valid_access_token()`. With `SHOPIFY_EXPIRING_TOKENS` enabled, that proactively rotates a near-expiry token, and the helpers also refresh-and-retry once on a `401`. With the flag off, the token is returned as-is.

### HMAC validation

```python
shop.app_proxy_request_is_valid(request)     # Validate app proxy HMAC
shop.request_shopify_hmac_is_valid(request)   # Validate standard Shopify HMAC
```

`app_proxy_request_is_valid` also requires the signed `timestamp` to be at most five minutes old (`shopify_app.models.APP_PROXY_MAX_AGE`), so a signed query string taken from a log can't be replayed later. Both methods return `False` when the signature parameter is missing.

## Authorization

The package supports two authorization flows: **token exchange** (recommended for embedded apps) and **authorization code grant** (legacy / non-embedded apps).

### Token exchange (recommended)

Token exchange eliminates OAuth redirects. The backend exchanges the session token from App Bridge for an access token via a server-side POST to Shopify. No page reloads or flicker.

Scopes are managed via `shopify.app.toml` and deployed with Shopify CLI (`shopify app deploy`). Shopify handles installation and scope updates automatically.

Add to settings.py:

```python
SHOPIFY_TOKEN_EXCHANGE = True           # Enable token exchange
SHOPIFY_DASHBOARD_PATH = '/dashboard'   # Where to redirect from app root
```

Set up your URLs:

```python
from django.urls import path, include
from shopify_app.views import AppRootView

urlpatterns = [
    path('', AppRootView.as_view()),
    path('shopify/', include('shopify_app.urls')),
    # your dashboard urls...
]
```

When a merchant opens your app, `AppRootView` redirects to the dashboard, forwarding only the `shop`, `host`, `locale` and `embedded` query parameters. The `id_token`, `hmac`, `signature`, `session` and `timestamp` values Shopify appends to the app URL are dropped so they never appear in the dashboard URL or in access logs. The first API request from the dashboard triggers token exchange automatically via `ShopSessionMixin` / `shop_session`, storing the access token for subsequent requests.

User login tracking is handled automatically: on the first request from a new user (or after 24 hours), an online token exchange fetches user details and fires `shop.on_user_login()`. It runs once per user even when the dashboard sends several requests at once: the first request records the login in `seen_users` under a lock on the shop row (on `SHOPIFY_TOKEN_DB_ALIAS`), and the others skip it. If the online token exchange fails, `on_user_login()` isn't called and the next attempt comes after the 24 hours, so the hook always receives the full user details. If `on_user_login()` raises, the request fails and the user stays seen until the next 24 hours.

### Authorization code grant (legacy)

For non-embedded apps or apps that don't use Shopify managed installation.

```python
from django.urls import path
from shopify_app.views import AppRootView, EndTokenRequestView

app_name = 'my_shopify_app'

urlpatterns = [
    path(
        '',
        AppRootView.as_view(
            redirect_path_name='my_shopify_app:end-token-request',
        ),
    ),
    path(
        'confirm/',
        EndTokenRequestView.as_view(
            redirect_path_name='embed_admin:dashboard',
        ),
        name='end-token-request'
    ),
]
```

With `SHOPIFY_TOKEN_EXCHANGE = False` (default), `AppRootView` falls back to the OAuth authorization code grant flow. The `shop` query parameter is validated as a `*.myshopify.com` domain before the OAuth URL is built and again on the callback; anything else gets a 400. The authorize URL and the callback's HMAC check use that shop's credentials (its `SHOPIFY_CREDENTIALS_OVERRIDES` entry, or the global ones), and a callback more than a day old is rejected.

Each authorization request carries a random `state` nonce, which the package also keeps in a signed cookie (`shopify_app_oauth_state`: `HttpOnly`, `SameSite=Lax`, one hour, scoped to the callback path). `EndTokenRequestView` returns `400 "Invalid OAuth state"` unless the callback's `state` matches the cookie, so a callback URL opened in another browser does nothing. The cookie has to be first-party, so an embedded load first opens the same view on `SHOPIFY_APP_HOST` at the top level and goes to Shopify from there. To start the flow from your own view, return `shopify_app.views.redirect_to_authorize(shop_domain, callback_path)` on a top-level response.

If you override the `shopify_app/index.html` template, keep the `redirect` value escaped with `escapejs`.

### Expiring offline access tokens

As of December 2025 Shopify supports expiring offline access tokens (60-minute access token + a 90-day refresh token), and requires them for new public apps from April 1, 2026. Enable them with:

```python
SHOPIFY_EXPIRING_TOKENS = True
SHOPIFY_TOKEN_ENCRYPTION_KEY = config('SHOPIFY_TOKEN_ENCRYPTION_KEY')  # required
SHOPIFY_TOKEN_REFRESH_SKEW = 300  # optional, seconds before expiry to refresh
```

When enabled:

- **Acquisition** — token exchange and the authorization code grant request `expiring=1`, so the response includes a `refresh_token`. Tokens are stored via `refresh_token` / `token_expires_at` / `refresh_token_expires_at`.
- **Rotation** — `valid_access_token()` refreshes a token within `SHOPIFY_TOKEN_REFRESH_SKEW` seconds of expiry; REST/GraphQL helpers also refresh-and-retry once on a `401`. Refresh is concurrency-safe (`select_for_update`), so parallel workers never double-spend the one-time-use refresh token. A failed refresh raises; see "Refresh failures" below.
- **Migration** — a legacy non-expiring token is replaced by an expiring one the next time a merchant opens the app (the session token is exchanged; the permanent token is never sent), or in bulk:

```bash
python manage.py migrate_offline_tokens            # migrate all non-expiring shops
python manage.py migrate_offline_tokens --shop example.myshopify.com
python manage.py migrate_offline_tokens --dry-run  # preview only
```

The admin can also migrate selected shops; see [Admin helpers](#admin-helpers).

> Migration is **irreversible** — Shopify revokes the original non-expiring token on success.

When Shopify rejects the stored token (`400 invalid_subject_token`) or the store is unavailable (`404` closed or deleted, `402` frozen, `423` locked), the bulk migration clears the token and sets `refresh_token_rejected_at`, logging a WARNING. A permanent token is never kept for a store that might reopen: from January 1, 2027, Shopify delists public apps that still use them. The cleared shop drops out of later runs and gets a new token when a merchant opens the app again, which calls `shop.token_reacquired()` instead of `installed()`. Other failures (`429`, `5xx`, credential errors) keep the token and log an ERROR.

With `SHOPIFY_EXPIRING_TOKENS = False` (default), behaviour is unchanged: non-expiring offline tokens and no refresh. The encryption key is still required, for `shopify_token`.

#### Refresh failures

A failed refresh raises one exception per response type, all in `shopify_app.exceptions`. Nothing is logged alongside them; the exception message carries the shop domain, status code and OAuth error code (`error_code`). The response body is on the exception as `body` but never in the message, because Shopify can echo request parameters in it. Because `valid_access_token()` raises, the API helpers (`get`/`post`/…/`graphql`) raise **before** sending a request with an expired token. The `401` retry raises the same way.

| Response from Shopify's token endpoint | Exception | What it means |
|---|---|---|
| no refresh token stored | `RefreshTokenMissing` | Nothing to refresh with |
| `401 {"error": "invalid_request"}` | `RefreshTokenInvalid` | The refresh token is dead: expired, replaced, revoked, or the app was uninstalled. Shopify doesn't say which. Sets `refresh_token_rejected_at` |
| not called: `refresh_token_expires_at` has passed | `RefreshTokenExpired` | A `RefreshTokenInvalid` raised without calling Shopify, which would answer `401 invalid_request`. Sets `refresh_token_rejected_at`; `status_code` is `None` |
| `404`, `402` or `423` (any body) | `ShopUnavailable` | The store is unavailable: usually closed or deleted (`404`), frozen for non-payment (`402`) or locked (`423`). It can come back, so the refresh token is kept and nothing is flagged. `ShopNotFound` is an alias |
| `429` | `TokenRefreshRateLimited` | Rate limited |
| `5xx` | `TokenRefreshUnavailable` | Shopify is unavailable; safe to retry later. Also a `requests.RequestException`, so `autoretry_for=RequestException` retries it |
| any other non-200 | `UnexpectedTokenRefreshResponse` | e.g. a `401` with a different `error`, a `400` or a `403` |
| shop row stayed locked (Postgres, 10 s) | `TokenRefreshLockTimeout` | The calling transaction most likely holds the shop row; see "Token database connection" |

- **Shared base class.** All of them subclass `TokenRefreshError`, which subclasses `ShopifyRequestException`, so existing `except ShopifyRequestException` handlers keep working. Timeouts and connection errors still raise the `requests` exceptions.
- **`shop.reauth_required`** is `True` once Shopify has rejected the shop's refresh token, or once the refresh token is past `refresh_token_expires_at`. A rejected refresh token is still sent on later calls; an expired one isn't. The flag is cleared when a new token is stored: the merchant opening the app (token exchange) or reinstalling. Use it to find shops that need the merchant to open the app.

#### Token database connection

Shopify rotates the token as soon as it answers a refresh or token exchange. If the new pair were saved inside your `transaction.atomic()` block and the block rolled back (say, the GraphQL call that follows fails), it would be lost from your database. So token refreshes, self-heals and migrations lock the shop row and save the new tokens through their own database connection, named by `SHOPIFY_TOKEN_DB_ALIAS`. That connection commits on its own, whatever your transaction does. It's required from 2.8.0 (system check `shopify_app.E001`):

```python
# settings.py
DATABASES["shopify_tokens"] = {
    **DATABASES["default"],
    "CONN_MAX_AGE": 0,
    "TEST": {"MIRROR": "default"},  # no separate test database
}
SHOPIFY_TOKEN_DB_ALIAS = "shopify_tokens"

# test settings
SHOPIFY_TOKEN_DB_ALIAS = "default"
```

- **Connections:** the package opens the alias connection only for a token write and closes it right after. Workers that aren't refreshing hold no extra connection, and at most one is open per refresh in flight.
- **Your shop object** stays on its own database. The new token values are copied onto it, and your later `shop.save()` calls stay in your transaction.
- **Token writes don't call `save()`.** The package writes the token fields (and the `seen_users` login claim) with a queryset update, so your `Shop.save()` override and `pre_save`/`post_save` receivers don't run for them. They would run inside the token transaction: a `transaction.on_commit()` callback registered on `default` would run at once, and a task it starts would read the shop before the new token commits. Put work that needs the token in `installed()` / `token_reacquired()`, which run after it commits.
- **Tests:** a separate connection can't see rows your tests create inside their transaction, so point token writes back at `default` in test settings. `"default"` means token writes share the caller's transaction (the behaviour before 2.8.0).
- **Don't save or lock the shop and then call Shopify in the same transaction.** The token connection would wait for a row lock that your transaction holds until it ends. On Postgres it gives up after 10 seconds with `TokenRefreshLockTimeout` instead of hanging. Save the shop after the API call, or in a separate transaction.
- **The OAuth code grant** writes the token on `default`: it runs in a view, outside any transaction.

### Webhook URLs

Include the package URLs for webhook and GDPR endpoints:

```python
from django.urls import path, include

urlpatterns = [
    path('shopify/', include('shopify_app.urls')),
]
```

This registers:
- `shopify/webhooks` — Main webhook receiver
- `shopify/gdpr-webhooks/customer-data-request` — GDPR customer data request
- `shopify/gdpr-webhooks/customer-data-erasure` — GDPR customer data erasure
- `shopify/gdpr-webhooks/shop-data-erasure` — GDPR shop data erasure

#### Webhook deduplication

Shopify can deliver the same webhook more than once (a retry after its 5-second timeout), and a captured, HMAC-valid delivery can be replayed: a replayed `app/uninstalled` would clear a live token. So both receivers deduplicate on `X-Shopify-Webhook-Id`, which Shopify keeps stable across retries of one delivery. The ID is claimed in Django's default cache (`cache.add`, 48-hour TTL, key `shopify_app:webhook:<id>`) before your callback runs; a duplicate gets a `200` and an INFO log line and your callback is not called. If your callback raises, the ID is released and the view answers `500`, so Shopify's retry is processed. Your callback still receives the ID in `attributes['webhook_id']` (now also for the GDPR callback), but it no longer needs its own dedupe.

This needs a cache every process can see. The `shopify_app.E002` system check stops `check`, `migrate`, `runserver` and `manage.py test` when `CACHES['default']` is `DummyCache` or `LocMemCache` (Django's fallback when `CACHES` is unset):

```python
# settings.py
CACHES = {
    "default": {
        "BACKEND": "django.core.cache.backends.redis.RedisCache",
        "LOCATION": "redis://redis:6379/1",
    }
}
```

Test settings may keep `LocMemCache` if they silence the check, since `manage.py test` runs system checks (pytest-django does not):

```python
# settings_test.py
CACHES = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}
SILENCED_SYSTEM_CHECKS = ["shopify_app.E002"]
```

Deliveries without `X-Shopify-Webhook-Id` are rejected with `401` like any other missing Shopify header, so test fixtures that post to these endpoints must send it.

## ShopSessionMixin

A mixin that authenticates requests against a valid Shopify shop session (JWT). Use it with any `APIView` or DRF generic view:

```python
from rest_framework.views import APIView
from shopify_app.mixins import ShopSessionMixin

class MyView(ShopSessionMixin, APIView):
    def get(self, request, *args, **kwargs):
        shop = request.shop
        ...
```

### Staff bypass

Staff users can skip Shopify JWT validation if they have a shop associated with their user model. Enable it globally in settings:

```python
SHOPIFY_STAFF_BYPASS = True  # Default: False
SHOPIFY_STAFF_BYPASS_METHODS = ['GET', 'HEAD', 'OPTIONS']  # Default
SHOPIFY_STAFF_SHOP_ATTR = 'admin_shop'  # Default: 'admin_shop'
```

`SHOPIFY_STAFF_BYPASS_METHODS` lists the HTTP methods allowed through the bypass. By default only `GET`, `HEAD` and `OPTIONS` are: other methods (POST, PUT, PATCH, DELETE) require Shopify JWT validation even for staff users. A staff session is a cookie, which the browser also sends on requests another site triggers, so a bypassed write on a CSRF-exempt view could be forged. To let staff write through the bypass, list the methods or set it to `None` (all methods), and keep those views behind Django's CSRF check.

Or per-view:

```python
class MyView(ShopSessionMixin, APIView):
    allow_staff_bypass = True  # Overrides the global setting
```

When enabled, if the request user is authenticated, is staff, and has a truthy value on the configured attribute (`admin_shop` by default), the mixin sets `request.shop` from that attribute and skips JWT validation.

## Decorators

### @shop_session

Validates the Shopify session token (JWT) from the request. Injects `shop`, `shopify_domain`, and `shopify_user_id` into the view kwargs:

```python
from shopify_app.decorators import shop_session

@shop_session
def my_view(request, *args, **kwargs):
    shop = kwargs['shop']
    user_id = kwargs['shopify_user_id']
```

The token is read from, in order: the `Authorization: Bearer <token>` header (preferred) or the `ShopifyAuth: Bearer <token>` header (deprecated, kept for older frontends). New frontends should send the standard `Authorization` header. A token in the `id_token` query parameter is ignored here and gets a 401, because URLs end up in access logs. Only the app's first page load reads it (`AppRootView`, through `perform_token_exchange`), since App Bridge appends it to that URL.

#### Error tracking

Session tokens are short-lived but replayable, so keep them out of your error tracker. Sentry and similar tools scrub `Authorization` and `Cookie` headers by default but capture custom headers and raw query strings verbatim, and Sentry sends `Authorization` too once `send_default_pii` is on. With Sentry, pass `shopify_app.sentry.strip_session_tokens` as `before_send` (see [Sentry](#sentry)); with another tracker, filter the `Authorization` and `ShopifyAuth` headers and the `id_token` query parameter the same way.

### @shopify_embed

Sets the Content-Security-Policy `frame-ancestors` header for embedded app views. With a `shop` query parameter that is a `*.myshopify.com` domain, only that shop's admin may frame the response. Without one, nothing may (`frame-ancestors 'none'`), so always pass `shop` to a view that has to render inside the Shopify admin:

```python
from shopify_app.decorators import shopify_embed

@shopify_embed
def my_view(request, **kwargs):
    ...
```

### @known_shop_required

Loads the shop named by the `shop` parameter (query string or POST body) and injects it as `request.shop` and `kwargs['shop']`. Returns 401 unless it is a `*.myshopify.com` domain with a row in the database.

**This is not an access check.** No HMAC or session token is verified, so anyone who knows a shop's domain passes. Use it only for views that show nothing private, such as the page that loads the embedded app, and use `@shop_session` for anything that reads or changes shop data:

```python
from shopify_app.decorators import known_shop_required

@known_shop_required
def my_view(request, *args, **kwargs):
    shop = kwargs['shop']
```

### @app_proxy_view

Validates the HMAC and the age of the signed `timestamp` (five minutes at most) for Shopify app proxy requests; anything else gets a 401. Fetches the shop from the database:

```python
from shopify_app.decorators import app_proxy_view

@app_proxy_view
def my_proxy_view(request, *args, **kwargs):
    shop = kwargs['shop']                          # Shop model instance (from DB)
    domain = kwargs['shopify_domain']              # e.g. 'example.myshopify.com'
    customer_id = kwargs['logged_in_customer_id']  # Customer ID or None
```

### @app_proxy_view_lite

Runs the same checks without hitting the database. Use this when you don't need the full shop record:

```python
from shopify_app.decorators import app_proxy_view_lite

@app_proxy_view_lite
def my_proxy_view(request, *args, **kwargs):
    domain = kwargs['shopify_domain']              # e.g. 'example.myshopify.com'
    customer_id = kwargs['logged_in_customer_id']  # Customer ID or None
    # No kwargs['shop'] — use get_shop() if you need the DB record
```

### @latest_access_scopes_required

Checks if the shop's stored scopes match the configured scopes. Sets `scope_changes_required=True` in kwargs if they differ:

```python
from shopify_app.decorators import latest_access_scopes_required

@shop_session
@latest_access_scopes_required
def my_view(request, *args, **kwargs):
    if kwargs.get('scope_changes_required'):
        # handle scope update
```

## Utilities

```python
from shopify_app.utils import (
    get_shop_model,          # Resolve shop model from SHOPIFY_SHOP_MODEL setting
    get_shop,                # Get shop by domain (raises DoesNotExist)
    webhook_request_is_valid, # Validate webhook HMAC
    claim_webhook_id,        # Record a webhook delivery ID; False if already processed
    release_webhook_id,      # Forget a delivery ID so Shopify's retry is processed
    liquid_render,           # Render template with Liquid content-type
    app_proxy_url_builder,   # Build a URL behind the shop's app proxy (ValueError unless on *.myshopify.com)
    app_proxy_redirect,      # Redirect to that URL
    app_bridge_redirect,     # Redirect, through App Bridge when embedded (takes the API key)
)
from shopify_app.services.auth import (
    get_shopify_credentials, # API key and secret for a shop domain, from settings (no DB query)
)
```

## Admin helpers

`ShopBase` is abstract, so the package registers no admin. `shopify_app.admin` (2.12.0) has helpers for your own Shop admin:

```python
from django.contrib import admin
from shopify_app.admin import (
    ShopTokenAdminMixin,
    ShopWebhooksAdminMixin,
    TokenTypeFilter,
)

from .models import Shop

@admin.register(Shop)
class ShopAdmin(ShopTokenAdminMixin, ShopWebhooksAdminMixin, admin.ModelAdmin):
    list_filter = [TokenTypeFilter]
```

- **`TokenTypeFilter`** is a list filter with two choices, Permanent and Expiring. Shops without a token match neither.
- **`ShopTokenAdminMixin`** goes before `ModelAdmin`. It:
  - never shows `shopify_token` or `refresh_token`: the admin shows "Set" or "Not set" instead, also where your admin names them in `fields`, `fieldsets`, `readonly_fields` or `list_display`.
  - shows the other `TOKEN_FIELDS` read-only and keeps all of them out of the form. A plain save drops edits to them (see [Saving a shop](#saving-a-shop)), and saving them by name from a form opened before a refresh would write the retired refresh token back.
  - adds the action "Migrate to expiring Shopify token (irreversible)". It runs `migrate_offline_token` on the selected shops that hold a permanent token, skips the others, and reports how many were migrated or skipped and which failed or were cleared (Shopify rejected the token, as in the `migrate_offline_tokens` command). The action needs change permission and is only offered while `SHOPIFY_EXPIRING_TOKENS` is on: with the flag off the app doesn't refresh the new tokens, which expire after an hour.
- **`ShopWebhooksAdminMixin`** goes before `ModelAdmin`. It adds a "Webhooks" section at the end of the shop's change page, with the shop's webhook subscriptions read from Shopify each time the page loads: topic, callback URL, API version, format and last update. Subscriptions at another URL than the app's callback URL (`SHOPIFY_WEBHOOK_HOST` plus the package's webhooks path) are flagged, and the section names the `SHOPIFY_WEBHOOK_TOPICS` with no subscription at it. Subscriptions declared in `shopify.app.toml` aren't listed: Shopify's API returns only the ones created through it. A shop without a token, or an error from Shopify, shows a message in the section instead of failing the page. The same data is available in code: `list_webhook_subscriptions(shop)` and `unregistered_webhook_topics(subscriptions)` in `shopify_app.services.webhooks`.

## Sentry

`shopify_app.sentry` (2.18.1) puts the shop on your Sentry events and keeps session tokens out of them. Install the extra, which pulls in `sentry-sdk`:

```bash
pip install "django-shopify-app[sentry]"
```

Nothing is on by default. Each part is opt-in:

```python
# settings.py
from shopify_app.sentry import strip_session_tokens

MIDDLEWARE = [
    "shopify_app.sentry.SentryShopContextMiddleware",  # anywhere in the list
    # ...
]

sentry_sdk.init(
    ...,
    send_default_pii=True,
    before_send=strip_session_tokens,
    # Sampled traces are sent as transaction events, which skip before_send.
    before_send_transaction=strip_session_tokens,
)
```

```python
# your Celery module (e.g. project/celery.py)
from celery.signals import task_prerun
from shopify_app.sentry import tag_task_shop

task_prerun.connect(tag_task_shop)
```

An event about a shop gets the shop's myshopify domain as its **user**, so an issue's user count is the number of shops it affected, and as the **`shop` tag**, to search and alert by shop. The **`shop_id` tag** is added when the shop's pk is known.

- **`SentryShopContextMiddleware`** reads the shop when an event is captured, since `request.shop` is set by the view's decorator or mixin after every middleware has run. Without `request.shop`, a webhook's `X-Shopify-Shop-Domain` header names the shop. It never queries the database. The shop replaces any user Sentry took from the request, a staff member on the staff bypass included.
- **`tag_task_shop`** is a `task_prerun` receiver. It binds the task's arguments to its signature, so positional arguments count, and reads the parameters named in `SHOPIFY_SENTRY_SHOP_DOMAIN_ARGUMENTS` (a domain or bare shop name, normalized to `<name>.myshopify.com`) and `SHOPIFY_SENTRY_SHOP_ID_ARGUMENTS` (a Shop pk). With only a pk, it reads the shop's domain from the database once per process. Sentry's Celery integration runs each task in its own isolation scope and `task_prerun` is sent inside it, so the tags stay with that task. It does nothing without an active Sentry client, so local runs and tests make no extra query. Tasks with none of those parameters get no shop.
- **`strip_session_tokens`** replaces the `Authorization` and `ShopifyAuth` headers and the `id_token` query parameter's value with `[Filtered]`. Sentry Logs don't go through `before_send`, so don't log tokens.

The `shopify_app.E005` system check fails when either `SHOPIFY_SENTRY_*_ARGUMENTS` setting isn't a list or tuple of parameter names: a plain string would be read one character at a time and match nothing.

In tests that need an active client, create it without integrations, `sentry_sdk.Client(default_integrations=False, auto_enabling_integrations=False)`, inside `sentry_sdk.isolation_scope()`. A plain `sentry_sdk.Client()` patches Django and Celery for the rest of the test run. With Sentry's Celery integration on, read a task's tags from inside the task: the task runs in its own isolation scope.

## Management commands

```bash
# Activate webhooks for a shop by subdomain
python manage.py activate_shop_webhooks <shopify_subdomain>
# e.g. activate_shop_webhooks example-store → targets example-store.myshopify.com

# Migrate shops from non-expiring to expiring offline tokens (irreversible).
# Tokens Shopify rejects (closed, deleted or uninstalled stores) are cleared.
python manage.py migrate_offline_tokens [--shop <domain>] [--dry-run]

# Encrypt the access tokens still stored in plaintext (written while
# SHOPIFY_ENCRYPT_ACCESS_TOKENS was off). Refuses to run with the setting off. Safe to
# re-run.
python manage.py encrypt_shop_tokens
python manage.py encrypt_shop_tokens --check     # count plaintext / encrypted; fails if any is plaintext
python manage.py encrypt_shop_tokens --decrypt   # back to plaintext, before rolling back below 2.16.0
```
