> For the complete documentation index, see [llms.txt](https://docs.snapfix.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.snapfix.com/engineering-reference/api/billing.md).

# Billing API

{% hint style="info" %}
Draft, written by an agent and not yet checked by a person ([how to read these docs](https://docs.snapfix.com/how-to-read.md)). [Source on GitHub](https://github.com/snapfix/docs/blob/main/spec/api/billing.md).
{% endhint %}

Site packages and their permissions, the apps' in-app plan list, Stripe customers, subscriptions and billing portal sessions, the Stripe webhooks, and a site's billing and invoice addresses. The staff admin app's package and Stripe tools are in [Staff](https://docs.snapfix.com/engineering-reference/api/staff.md) ([related routes](#related-routes)).

* **Services:** `api_php_live_v2` at `https://z4.snapfix.com` (`/v1/app`); `php-apis` at `https://z1.snapfix.com/api/snapfix/index.php`; `apipy` at `https://z2.snapfix.com`; `authpy` at `https://z3.snapfix.com`. Only Android swaps hosts per site ([Services and hosts](https://docs.snapfix.com/engineering-reference/api.md#services-and-hosts)).
* **Auth:** api\_php\_live\_v2: user token (authpy JWT in `Authorization: Bearer`); the billing portal route also needs a site admin. php-apis: the dispatcher checks a Bearer JWT for every action except its no-login list, and only while `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]. Four actions here are on that list: `check_stripe_tax_ids`, `create_stripe_subscription_v3_guest`, `fb_parent_subscription` and `read_stripe_product_v3`. They take the shared Basic login (`AUTH_USERNAME`) instead of a token. With `JWT_AUTH_ENABLED` off, every action takes the Basic login. A wrong login answers `200` with "You are not authorised to access this API." (php-apis @ 238ca4414e, `html/api/snapfix/index.php:355`, `:383-481`). Most actions act on the `user_uuid` in the request, not on the token's user; `paywall` reads the user from the token payload. apipy: `/v4/parent-pack` takes a user token and checks no staff flag; the two webhooks check the `Stripe-Signature` header instead. authpy: both routes take the shared app Basic login.
* **Used by:** web\_app\_v2 (the billing portal link), web\_payments (the payment page), iOS and Android (the in-app plan list, site packages and package permissions), webadmin\_angular (the staff paywall's Parents tab), apipy (Firebase usage counters), authpy (relays the payment page's guest subscription and package read to php-apis), Stripe (the two webhooks, external); 24 of the 41 endpoints have no known caller.
* **Answers and errors:** the api\_php\_live\_v2 envelope and the codes every `/v1/app` route can return are in [Tasks: common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors). php-apis, apipy and authpy answer HTTP `200` with `result` `false` and the message for their own errors ([Responses](https://docs.snapfix.com/engineering-reference/api.md#responses)); the webhooks answer `400`. Each section lists its own errors.
* **Logs:** api\_php\_live\_v2 writes each call to its request log, with the response when it is under about 100 KB; php-apis stores each request body and each response under about 100 KB in its daily request log. apipy's abuse check writes each `/v4/parent-pack` call to the daily `apilog_<date>` table, with the response when it is under about 100 KB, so each page of sites is copied there (apipy @ 0e83c85e5a, `model/t_log_ip_blocked_v3.py:1214-1242`); it also looks up the caller's IP address with an outside service. authpy logs each call of its two routes through its own abuse check. apipy stores every Stripe event in full in [`stripe_log`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_log.md) ([webhooks](#post-wh-production)).

| Method | Path                                                                                             | Service            | Purpose                                                           |
| ------ | ------------------------------------------------------------------------------------------------ | ------------------ | ----------------------------------------------------------------- |
| GET    | `/v1/app/package-permission/{uuid}`                                                              | api\_php\_live\_v2 | Get a package's permissions (no caller)                           |
| POST   | `/v1/app/parents/packages`                                                                       | api\_php\_live\_v2 | Get the package hash of each site named (no caller)               |
| GET    | [`/v1/app/parents/{uuid}/create-session`](#get-v1appparentsuuidcreate-session)                   | api\_php\_live\_v2 | Create a Stripe billing portal session for a site                 |
| ANY    | `?action=check_stripe_tax_ids`                                                                   | php-apis           | Check a Stripe customer's tax IDs (no caller)                     |
| POST   | [`?action=create_stripe_subscription_v3`](#post-actioncreate_stripe_subscription_v3)             | php-apis           | Create a Stripe subscription (v3)                                 |
| POST   | [`?action=create_stripe_subscription_v3_guest`](#post-actioncreate_stripe_subscription_v3_guest) | php-apis           | Create a Stripe subscription (v3) without a user token            |
| POST   | [`?action=fb_parent_subscription`](#post-actionfb_parent_subscription)                           | php-apis           | Update a site's usage counters in Firebase                        |
| ANY    | `?action=get_client_secret_key`                                                                  | php-apis           | Get a customer's client secret or stored Stripe event (no caller) |
| ANY    | `?action=get_parent_packages`                                                                    | php-apis           | Get a site's packages (no caller)                                 |
| ANY    | `?action=get_permission_details`                                                                 | php-apis           | Get package permissions (no caller)                               |
| POST   | [`?action=package_permissions`](#post-actionpackage_permissions)                                 | php-apis           | Get a package's permissions                                       |
| POST   | [`?action=parent_packages`](#post-actionparent_packages)                                         | php-apis           | Get the package hash of each site named                           |
| ANY    | `?action=parent_permissions`                                                                     | php-apis           | Get a site's package permissions (no caller)                      |
| ANY    | `?action=payment_business_stats`                                                                 | php-apis           | Read site stats for a payment (no caller)                         |
| ANY    | `?action=payment_business_user_detail`                                                           | php-apis           | Read site user details for a payment (no caller)                  |
| POST   | [`?action=paywall`](#post-actionpaywall)                                                         | php-apis           | List the caller's sites with their in-app purchase flag           |
| ANY    | `?action=prod_create_session`                                                                    | php-apis           | Create a Stripe session, live mode (no caller)                    |
| ANY    | `?action=prod_create_subscription`                                                               | php-apis           | Create a Stripe subscription, live mode (no caller)               |
| ANY    | `?action=prod_create_subscription_v2`                                                            | php-apis           | Create a Stripe subscription (v2), live mode (no caller)          |
| POST   | [`?action=prod_get_stripe_customer_id`](#post-actionprod_get_stripe_customer_id)                 | php-apis           | Get a site's Stripe customer ID, live mode                        |
| ANY    | `?action=prod_simulate_payment_method_id`                                                        | php-apis           | Simulate a card payment method, live mode (no caller)             |
| ANY    | `?action=read_parent_address_billing`                                                            | php-apis           | Read a site's billing address (no caller)                         |
| ANY    | `?action=read_parent_address_invoice`                                                            | php-apis           | Read a site's invoice address (no caller)                         |
| POST   | [`?action=read_stripe_product_v3`](#post-actionread_stripe_product_v3)                           | php-apis           | Read a package and its prices (v3)                                |
| ANY    | `?action=read_stripe_product_v3_1`                                                               | php-apis           | Read a Stripe product (v3), with a user token (no caller)         |
| ANY    | `?action=refresh_stripe_subscription`                                                            | php-apis           | Refresh Stripe subscriptions (no caller)                          |
| ANY    | `?action=sandbox_create_session`                                                                 | php-apis           | Create a Stripe session, sandbox (no caller)                      |
| ANY    | `?action=sandbox_create_subscription`                                                            | php-apis           | Create a Stripe subscription, sandbox (no caller)                 |
| ANY    | `?action=sandbox_create_subscription_v2`                                                         | php-apis           | Create a Stripe subscription (v2), sandbox (no caller)            |
| POST   | [`?action=sandbox_get_stripe_customer_id`](#post-actionsandbox_get_stripe_customer_id)           | php-apis           | Get a site's Stripe customer ID, sandbox                          |
| ANY    | `?action=sandbox_simulate_payment_method_id`                                                     | php-apis           | Simulate a card payment method, sandbox (no caller)               |
| ANY    | `?action=save_parent_address_billing`                                                            | php-apis           | Save a site's billing address (no caller)                         |
| ANY    | `?action=save_parent_address_invoice`                                                            | php-apis           | Save a site's invoice address (no caller)                         |
| ANY    | `?action=save_stripe_tax_number`                                                                 | php-apis           | Save a Stripe customer's VAT ID (no caller)                       |
| POST   | [`?action=snapfix_package`](#post-actionsnapfix_package)                                         | php-apis           | Get a package price by its ID                                     |
| GET    | [`/v4/parent-pack`](#get-v4parent-pack)                                                          | apipy              | List sites with their package                                     |
| PUT    | [`/v4/parent-pack`](#put-v4parent-pack)                                                          | apipy              | Change a site's package                                           |
| POST   | [`/wh-production`](#post-wh-production)                                                          | apipy              | Stripe webhook, live mode                                         |
| POST   | [`/wh-sandbox`](#post-wh-sandbox)                                                                | apipy              | Stripe webhook, sandbox                                           |
| POST   | [`/create-stripe-subscription-v3`](#post-create-stripe-subscription-v3)                          | authpy             | Create a Stripe subscription (v3), relayed to php-apis            |
| POST   | [`/read-package-v3`](#post-read-package-v3)                                                      | authpy             | Read a package and its prices (v3), relayed to php-apis           |

Notes on the table:

* The php-apis dispatcher accepts any method except `OPTIONS` (php-apis @ 238ca4414e, `html/api/snapfix/index.php:231-237`). The table shows the method the callers send, and `ANY` where no client calls the action. Five rows that the stub had as `ANY` have a caller and show `POST`: `create_stripe_subscription_v3`, `paywall`, `prod_get_stripe_customer_id`, `sandbox_get_stripe_customer_id` and `snapfix_package`.
* Rows marked "(no caller)" have no caller in any client clone or service, and get no section. Whether to remove them is open \[[ASK-11](https://github.com/snapfix/docs/blob/main/ASK.md#ask-11-which-unused-api-endpoints-are-still-needed)].
* The two api\_php\_live\_v2 rows: the web's only call to them is commented out as "Disabled for now" (web\_app\_v2 @ 0989b8e685, `src/app/components/side-menu/account-list-menu/account-list-menu.component.ts:298-301`), and the apps use the php-apis actions instead. Whether to keep them is open \[[ASK-11](https://github.com/snapfix/docs/blob/main/ASK.md#ask-11-which-unused-api-endpoints-are-still-needed)]. `POST /v1/app/parents/packages` takes any list of sites with no membership check and runs queries for each package row of a list with no size limit. Its copy step runs only when the server package is missing, so it never copies a package into `package_client`, and it fails with an error when the package is missing (api\_php\_live\_v2 @ ef3c4319f6, `app/Services/PackagePermissionService.php:164-194`). `GET /v1/app/package-permission/{uuid}` returns any package's permissions to any signed-in user.
* The `prod_` actions use the live Stripe account and the `sandbox_` actions the test account; the other Stripe actions here choose by the server's `MODE` (`index.php:1438-1485`, `:2197-2321`). The live payment page calls `prod_get_stripe_customer_id`, and its staging and development builds call `sandbox_get_stripe_customer_id`.
* What the uncalled php-apis actions can do:
  * `prod_create_session` and `sandbox_create_session` return a Stripe billing portal URL for a site's customer. They check only that the body's `user_uuid` has a site row, of any role, on the body's `parent_uuid`, so any signed-in user who knows a customer ID and a member's user ID can open the portal. The four `*_create_subscription*` actions make the same check before they create a subscription (`htmlphp/api/snapfix/class/stripe.functions.php:541-554`, `:619-631`, `:723-735`).
  * `get_client_secret_key` returns, for any customer ID, the client secret of a pending payment or a stored Stripe event. It reads the whole `stripe_log` table on each call, and in one branch answers with the debug text `hi` instead (`stripe.functions.php:1162`).
  * `payment_business_user_detail` returns any user's sign-in email and mobile number for any site. `payment_business_stats` returns any site's user and group counts.
  * `save_stripe_tax_number` adds, replaces or deletes the VAT ID of any site's Stripe customer.
  * `refresh_stripe_subscription` starts a Stripe sync of every site's package, for any signed-in user.
  * `read_parent_address_billing` and `read_parent_address_invoice` return any site's billing or invoice address. `save_parent_address_billing` and `save_parent_address_invoice` write them with no check.
  * `check_stripe_tax_ids` returns every tax ID of any Stripe customer to the shared Basic login, as raw JSON outside the usual answer (`stripe.functions.php:1869-1884`).
  * `prod_simulate_payment_method_id` and `sandbox_simulate_payment_method_id` create a test card payment method at Stripe for any signed-in caller and write nothing to the database (`stripe.functions.php:500-539`).

## Related routes

* **Site details:** `GET /v1/app/parents/{uuid}` returns a site's Stripe customer ID and subscription, and its admins, to any signed-in user. It is in [Console](https://docs.snapfix.com/engineering-reference/api/console.md#get-v1appparentsuuid). The payment page reads the user's admin sites and a site's details with `webcust_parent_list` and `webcust_parent_detail`, also in [Console](https://docs.snapfix.com/engineering-reference/api/console.md#post-actionwebcust_parent_detail).
* **Staff packages and paywall:** the admin API's `/v1/admin/payment/packages`, `/v1/admin/payment/paywall-packages`, `/v1/admin/payment/paywall-parents`, `/v1/admin/sales/stripe-customer` and `/v1/admin/sales/company-stripe-checkout`, and the php-apis package actions `admin_packages`, `admin_create_package`, `admin_delete_package`, `snapfix_packages`, `create_snapfix_package`, `update_package_schema` and `download_packages`, are in [Staff](https://docs.snapfix.com/engineering-reference/api/staff.md). The staff paywall's Parents tab uses this group's [`/v4/parent-pack`](#get-v4parent-pack).
* **Subscription status:** a site's subscription comes from [`stripe_subscription`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_subscription.md) rows. Only the sandbox webhook writes them; no live route or webhook does \[[ASK-142](https://github.com/snapfix/docs/blob/main/ASK.md#ask-142-who-records-live-stripe-subscriptions)].
* **Screens:** [Billing screens](https://docs.snapfix.com/how-the-apps-work/screens/billing.md) (the payment page, the Site Console's subscription tab and the iOS plan screen) and the staff [Paywall](https://docs.snapfix.com/how-the-apps-work/screens/staff/paywall.md) page.

## GET /v1/app/parents/{uuid}/create-session

Creates a Stripe billing portal session for a site and returns its URL. In the portal the customer sees the invoice history, changes the payment method and cancels the subscription. The Site Console's subscription tab opens it.

* **Auth:** user token. The caller must be a site admin: their newest live site row must have `user_type` `admin`, otherwise `403` (api\_php\_live\_v2 @ ef3c4319f6, `app/Policies/ParentPolicy.php:19-32`, `app/Http/Controllers/v1/Versions/v1_0/App/ParentController.php:530-555`). `blocked` is not checked, so a blocked admin still passes.
* **Used by:** web (`AccountHttpService.getAccountSubscriptionSessionUrl`, cached per site; web\_app\_v2 @ 0989b8e685, `src/app/services/account/account-http/account-http.service.ts:119-128`). The subscription tab asks for the link only when the site's `hasSubscribed` is set, and goes to the site's details page when the call fails (`src/app/pages/account-settings/account-settings-subscription/account-settings-subscription.component.ts:47-70`).

**Request**

| Name      | In     | Type   | Required | Rules                                                                                                                          |
| --------- | ------ | ------ | -------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `uuid`    | path   | string | yes      | The site                                                                                                                       |
| `Referer` | header | string | no       | The portal's return link; without it, the server's `app.return_url` (`app/Services/StripeService.php:65-72`). Browsers send it |

**Response** `200`: `data.url` is the portal session URL (`app/Http/Resources/v1/CreateSessionResource.php`).

```json
{
  "status": "success",
  "message": "Operation was successful",
  "data": { "url": "https://billing.stripe.com/session/example123" }
}
```

**Errors:** [common errors](https://docs.snapfix.com/engineering-reference/api/tasks.md#common-errors), and:

* `404` "Resource not found" for an unknown or deleted site. The site is loaded before the admin check.
* `403` "Access denied" when the caller is not a site admin.
* `400` "Account does not have a customer id" when the site has no Stripe customer ID.
* `400` "Failed to create session" when Stripe returns no session ID.
* `400` "Something went wrong" for other errors, Stripe API errors included, because the exception handler treats them as not fatal (`app/Exceptions/Handler.php:78-84`, `:117-123`; stripe/stripe-php v14.10.0 in `composer.lock`, not in the clone). With `APP_DEBUG` on, the answer carries the exception text instead. PHP errors and runtime or logic exceptions get `500` "An unexpected error occurred. Please try again later.".

**Side effects:** nothing in the database. Each call creates a new billing portal configuration at Stripe (invoice history, payment method update and subscription cancellation, with the privacy and terms links), then the session for the site's Stripe customer (`app/Services/StripeService.php:43-73`).

## POST ?action=create\_stripe\_subscription\_v3

Creates a Stripe subscription, or a one-off invoice, on a site's Stripe customer: the payment page's path for packages without a Stripe customer of their own. A package with its own customer goes through the [guest flow](#post-actioncreate_stripe_subscription_v3_guest) instead.

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action acts on the `user_uuid` in the form, not on the token's user. That user needs any [`tPri_UserParent`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_userparent.md) row on `parent_uuid`, of any role, deleted rows included. The message says "invalid parent admin!", but there is no admin check (php-apis @ 238ca4414e, `htmlphp/api/snapfix/class/stripe.functions.php:1488-1497`). `customer_id` must belong to some site, but not to `parent_uuid`, so a member of one site can charge another site's customer. When `package_id` names a package with its own Stripe customer, the action passes the whole request to the guest flow before these checks, so no user is checked at all (`:1459-1468`).
* **Used by:** web\_payments (`PaymentService.createSubscription` with `useGuestAPI` false, when the package has no Stripe customer; web\_payments @ 7c2c3ddffd, `src/app/services/payment/payment.service.ts:34-41`, `src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:248-252`). It sends multipart form fields with the user's token (`src/app/services/auth/auth-interceptor/auth.interceptor.ts:48-66`).

**Request** (form fields; the action reads `$_POST`)

| Name                         | In   | Type         | Required | Rules                                                                                                                                                                                                                                                                                                                        |
| ---------------------------- | ---- | ------------ | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customer_id`                | body | string       | yes      | A site's `stripe_customer_id`, deleted sites included; otherwise "invalid customer\_id". Not checked against `parent_uuid`                                                                                                                                                                                                   |
| `payment_method_id`          | body | string       | yes      | The Stripe payment method the payer made on the page, a card or a SEPA Direct Debit. Attached to the customer and used as the default for the subscription or invoice                                                                                                                                                        |
| `parent_uuid`                | body | string       | yes      | The site the user must have a row on                                                                                                                                                                                                                                                                                         |
| `user_uuid`                  | body | string       | yes      | A user with any row on `parent_uuid`; otherwise "invalid parent admin!". Also the creator of the address rows                                                                                                                                                                                                                |
| `accept_tc`                  | body | string       | yes      | Must not be blank; the value is not checked. The page sends `1`                                                                                                                                                                                                                                                              |
| `price_items`                | body | JSON string  | yes      | A non-empty array of `{ "id", "qty" }`, both required in each item. Each `id` is a price UUID in [`package_server_pricing`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_pricing.md), deleted prices included; one unknown ID gives "invalid price id". Prices with the interval `na` are one-off |
| `package_id`                 | body | string       | no       | A live `package_server` UUID; otherwise "invalid package". A package with its own Stripe customer sends the request to the guest flow                                                                                                                                                                                        |
| `invoice_address`            | body | JSON string  | no       | `address_1`, `address_2`, `city`, `state`, `country`, `postal_code`. Saved as the site's invoice address, and set as the Stripe customer's address. The customer's name becomes the user's first and last name, with the name of the site that owns `customer_id` in brackets. The country `IE` turns on automatic tax       |
| `billing_address`            | body | JSON string  | no       | The same keys. Saved as the site's billing address only. The page sends the invoice address, or the site's own billing address when it has one                                                                                                                                                                               |
| `vat_id`                     | body | string       | no       | See below                                                                                                                                                                                                                                                                                                                    |
| `po_id`, `promo_id`          | body | string       | no       | Stored in the invoice's or subscription's metadata, with `vat_id`                                                                                                                                                                                                                                                            |
| `subscription_start_date_ts` | body | integer (ms) | no       | A past date backdates the subscription. A future date anchors the billing cycle there, with no proration and an incomplete first payment allowed. `0` or missing starts now (`stripe.functions.php:1692-1846`)                                                                                                               |

How `vat_id` and tax work (`stripe.functions.php:1557-1608`):

* When the site that owns `customer_id` already has a `stripe_vat_id`, a blank or missing `vat_id` deletes that tax ID at Stripe and clears the site's value (`:469-498`); a sent one keeps it.
* When that site has none and `vat_id` is sent, the customer's last existing tax ID is reused, or an `eu_vat` tax ID is created, whatever the buyer's country. Its ID is saved as that site's `stripe_vat_id`.
* Automatic tax is on when a VAT ID is in use or the invoice address's country is `IE`.

**Response** `200`: a [subscription result object](#subscription-result-object). Only one-off prices make an invoice instead of a subscription, and `subscription_id` is then empty (`stripe.functions.php:1650-1690`).

```json
{
  "result": true,
  "message": "Success",
  "serverTs": 1794387595000,
  "data": {
    "subscription_id": "sub_example123",
    "client_secret": "pi_example123_secret_example",
    "subscriptionDetail": { "id": "sub_example123", "object": "subscription", "status": "incomplete" }
  }
}
```

**Errors:** `200` with `result` `false` and one of these messages:

* "Data cannot be blank!" (no form fields; `html/api/snapfix/index.php:1462-1473`).
* "`<names>` must be mentioned in the request!", naming the missing fields among `customer_id`, `payment_method_id`, `parent_uuid`, `user_uuid` and `accept_tc`, or `id` and `qty` in a price item (`stripe.functions.php:193-205`).
* "invalid package", "invalid price\_items", "invalid customer\_id", "invalid parent admin!", "invalid price id".
* "Failed to attach payment method with customer", "Failed to create tax id for the customer".
* For a one-off invoice: "Error while creating invoice", "Error while finalizing Invoice", "Error while fetching payment\_intent". For a subscription: "Failed to create subscription".
* Stripe's own message, unchanged. The page shows its own VAT format help when the message contains `_vat` (`pay-package-payment.component.ts:253-265`).

Single-price payment links always get "invalid package". The page keeps no package for them, so it sends `package_id` as the text "undefined", and the action looks that package up (web\_payments @ 7c2c3ddffd, `src/app/pages/auth/pay/pay.component.ts:38`, `src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:335`, `src/app/services/helper/helper.service.ts:39-52`).

**Side effects:**

* Writes a [`tPri_Address`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_address.md) row and a [`tPri_ParentAddress`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_parentaddress.md) row for each of `invoice_address` and `billing_address` sent, with `user_uuid` as the creator (`stripe.functions.php:1513-1515`, `:1541-1543`).
* Sets or clears `stripe_vat_id` on [`tPri_Parent`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_parent.md), as above.
* Stripe: updates the customer's name and address, attaches the payment method, adds or deletes the tax ID, and creates invoice items and a finalized invoice for one-off prices only, or the subscription, with any one-off prices as pending invoice items (`:1527`, `:1550-1555`, `:1650-1846`).
* Writes no [`stripe_subscription`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_subscription.md) row and no package link; the live webhook does not either \[[ASK-142](https://github.com/snapfix/docs/blob/main/ASK.md#ask-142-who-records-live-stripe-subscriptions)].

## POST ?action=create\_stripe\_subscription\_v3\_guest

Creates a Stripe subscription, or a one-off invoice, on any Stripe customer, for a package that has a customer of its own: the payment page's guest path, through authpy's [`/create-stripe-subscription-v3`](#post-create-stripe-subscription-v3).

* **Auth:** the shared Basic login only: the action is on the no-login list (php-apis @ 238ca4414e, `html/api/snapfix/index.php:355`, `:434-457`). It checks no user, no site and no link between the customer and the package; the site and user checks are commented out (`htmlphp/api/snapfix/class/stripe.functions.php:1919-1931`). Anyone with the login can attach a card to any Stripe customer whose ID they know, change its address, add a VAT ID, and create an invoice or a subscription on it. Site customer IDs reach any signed-in user through [GET /v1/app/parents/{uuid}](https://docs.snapfix.com/engineering-reference/api/console.md#get-v1appparentsuuid) and [prod\_get\_stripe\_customer\_id](#post-actionprod_get_stripe_customer_id); a package's own customer ID is in the answer of [read\_stripe\_product\_v3](#post-actionread_stripe_product_v3).
* **Used by:** authpy (`/create-stripe-subscription-v3` posts the form as `data`, with its own Basic login; authpy @ 5d5758661c, `model/feature_php_api.py:173-177`). [create\_stripe\_subscription\_v3](#post-actioncreate_stripe_subscription_v3) also passes requests here for packages with a customer.

**Request** (JSON body with a `data` object; the action reads `$data['data']`)

| Name                         | In   | Type         | Required | Rules                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ---------------------------- | ---- | ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `customer_id`                | data | string       | yes      | Any Stripe customer ID, not checked against a site or the package. The payment page sends the chosen site's customer when the site has one, and the package's own customer only otherwise (web\_payments @ 7c2c3ddffd, `src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:161-174`, `:333`) \[[ASK-225](https://github.com/snapfix/docs/blob/main/ASK.md#ask-225-which-stripe-customer-should-a-signed-in-buyer-of-a-package-with-its-own-customer-be-charged-on)] |
| `payment_method_id`          | data | string       | yes      | Attached to `customer_id` and used as the default for the subscription or invoice                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `accept_tc`                  | data | string       | yes      | Must not be blank                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `package_id`                 | data | string       | yes      | A live `package_server` UUID; otherwise "invalid package" (`stripe.functions.php:1887-1895`)                                                                                                                                                                                                                                                                                                                                                                                                            |
| `price_items`                | data | JSON string  | yes      | As for [create\_stripe\_subscription\_v3](#post-actioncreate_stripe_subscription_v3)                                                                                                                                                                                                                                                                                                                                                                                                                    |
| `invoice_address`            | data | JSON string  | no       | Set as the Stripe customer's address; not saved. The country `IE` turns on automatic tax                                                                                                                                                                                                                                                                                                                                                                                                                |
| `billing_address`            | data | JSON string  | no       | Read but not used                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `vat_id`                     | data | string       | no       | Reuses the customer's last tax ID, or creates an `eu_vat` one whatever the country, and turns on automatic tax. Nothing is saved, and a missing `vat_id` deletes nothing (`:2006-2036`)                                                                                                                                                                                                                                                                                                                 |
| `parent_uuid`                | data | string       | no       | Stored in the metadata as `login_parent_uuid`; `none` when missing                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| `po_id`, `promo_id`          | data | string       | no       | Stored in the metadata                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  |
| `subscription_start_date_ts` | data | integer (ms) | no       | As for [create\_stripe\_subscription\_v3](#post-actioncreate_stripe_subscription_v3)                                                                                                                                                                                                                                                                                                                                                                                                                    |

The invoice's or subscription's metadata also carries the package's own `metadata_json` values: `hubspot_deal_id`, `hubspot_company_id`, `hubspot_contact_id` and `parent_uuid` (`stripe.functions.php:1990-1993`, `:2093`).

**Response** `200`: a [subscription result object](#subscription-result-object). When the new subscription comes back without a client secret, the action reads the subscription again, then the upcoming invoice, and as a last resort creates and finalizes an invoice for the subscription. Those branches add `subscriptionTemp` and `clientSecretError`, and the last one `invoice` and `finalizedInvoice` (`stripe.functions.php:2283-2337`).

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no `data`; `index.php:1474-1485`), "`<names>` must be mentioned in the request!", "invalid package", "invalid price\_items", "invalid price id", "Failed to attach payment method with customer", "Failed to create tax id for the customer", the invoice and subscription messages of [create\_stripe\_subscription\_v3](#post-actioncreate_stripe_subscription_v3), or Stripe's own message. A wrong Basic login gets "You are not authorised to access this API."; through authpy, see [`/create-stripe-subscription-v3`](#post-create-stripe-subscription-v3).

**Side effects:** Stripe only: the customer's address, the payment method, the tax ID, and the invoice or subscription, plus the extra invoice of the last-resort branch. No database row is written: the address and VAT saves are commented out (`stripe.functions.php:1944-1946`, `:1971-1973`, `:2032-2033`), and no [`stripe_subscription`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_subscription.md) row is written \[[ASK-142](https://github.com/snapfix/docs/blob/main/ASK.md#ask-142-who-records-live-stripe-subscriptions)].

## POST ?action=fb\_parent\_subscription

Adds to, or rewrites, a site's usage counters in the Firebase Realtime Database: the usage node that the apps also read. apipy calls it when a group is created or a user joins a group.

* **Auth:** the shared Basic login only: the action is on the no-login list (php-apis @ 238ca4414e, `html/api/snapfix/index.php:355`). It checks no site and no caller, so anyone with the login can reset or raise any site's counters.
* **Used by:** apipy (`FeaturePhpApi.postFirebaseUsageUpdate`, with its Basic login; apipy @ 0e83c85e5a, `model/feature_php_api.py:87-89`). It sends `group_count` `1` when a group is created (`model/feature_group.py:113`), and `user_count` `1` when a user is added to a group (`model/feature_group.py:332`, `:396`, `:806`, `:872`; `model/t_group_invite.py:310`).

**Request** (JSON body)

| Name                                 | In   | Type    | Required | Rules                                                                                                                                                                                                               |
| ------------------------------------ | ---- | ------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `parent_uuid`                        | body | string  | yes      | The site, used as the node's key. Blank or missing: "bad request". Removed from the body before the write                                                                                                           |
| `user_count`                         | body | integer | no       | On an existing node, replaced by a fresh count of the distinct users in the site's groups. The value sent is stored only when the node is created or rewritten. The count puts `parent_uuid` into the SQL unescaped |
| `force_rewrite`                      | body | integer | no       | `1` replaces the whole node with the body                                                                                                                                                                           |
| Any other key, such as `group_count` | body | number  | no       | Added to the stored value, or stored as sent when the node has no such key                                                                                                                                          |

**Response** `200`

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000
}
```

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (empty body; `index.php:1872-1878`); "bad request" (no `parent_uuid`; `htmlphp/api/snapfix/class/firebase.functions.php:101`).

**Side effects:** writes the node `tParentPackUsage/<parent_uuid>`, or `tParentPackUsage_test` outside live mode (`firebase.functions.php:51-99`). A missing node, or `force_rewrite` `1`, gets the body with `created_ts`, `modified_ts` and `status` `1`; otherwise only the keys sent change. The `user_count` query reads [`tPri_UserBusiness`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_userbusiness.md) and `tPri_Business`, deleted rows included (`:73-85`). Nothing is written to MySQL.

## POST ?action=package\_permissions

Returns the stored permission set of one package. The apps read it after [parent\_packages](#post-actionparent_packages) gives them each site's pack hash.

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action checks nothing about the caller, so any signed-in user can read any package's permissions by its hash (php-apis @ 238ca4414e, `html/api/snapfix/index.php:1798-1804`). The permissions describe the plan and hold no site or personal data.
* **Used by:** iOS (`BusinessListingVC.getPermission`, once for each pack hash that `parent_packages` returns; ios @ aa31967ac8, `SnapFix/BusinessListingVC.swift:636`, `:692-707`) and Android (`PaywallUtils.callPackagePermissionAPI`; android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/utils/PaywallUtils.java:97-108`). Both send JSON by POST, and both resolve the registry name `package_permissions_v1` to this action (`APIManagers/ApiEndpointManager.swift:2015-2019`; `app/src/main/java/gmail/com/snapfixapp/utils/APIEndPointUtils.java:377`).

**Request** (JSON body)

| Name        | In   | Type   | Required | Rules                                                                                                                                                                                   |
| ----------- | ---- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `pack_hash` | body | string | yes      | The package's UUID in [`package_client`](https://docs.snapfix.com/engineering-reference/db/tables/package_client.md), as `parent_packages` returns it. Missing: "Data cannot be blank!" |

**Response** `200`: `data` is the package's stored permission JSON, decoded (`htmlphp/api/snapfix/class/paypack.functions.schema-v1.php:133-148`): `paywall_version` and `permission`, with limits and switches such as `task`, `user`, `group`, `apps` and `nfc_enabled`.

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": {
    "paywall_version": 1,
    "permission": {
      "apps": { "ios": { "enabled": true, "free_trial_days": 14, "free_trial_days_warning": 11 } },
      "task": { "limit": 100, "limit_warning": 90 },
      "user": { "limit": 5, "limit_warning": 4 },
      "group": { "limit": 25 },
      "nfc_enabled": false
    }
  }
}
```

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no body, or no `pack_hash`); "invalid package hash" (no `package_client` row with that UUID).

**Side effects:** none.

## POST ?action=parent\_packages

Returns each named site's current pack hash, and copies a site's current server package into the client tables when the site's copy is missing or older. The apps then read the permissions with [package\_permissions](#post-actionpackage_permissions).

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action does not check that the caller belongs to the sites named, so any signed-in user can name any site and make the server write rows for it (php-apis @ 238ca4414e, `html/api/snapfix/index.php:1791-1797`).
* **Used by:** iOS (`BusinessListingVC.getAllPermissions`, with the sites of the user's groups, after the app downloads a site's group data; ios @ aa31967ac8, `SnapFix/BusinessListing+ParentSwither.swift:237`, `SnapFix/BusinessListingVC.swift:584-602`) and Android (`PaywallUtils.callGetParentPackagesAPI`, with the user's sites from the local database, when the group list opens; android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/fragment/GroupListingFragment.java:310`, `app/src/main/java/gmail/com/snapfixapp/utils/PaywallUtils.java:44-58`). Both send JSON by POST and resolve the registry name `parent_packages_v1` to this action (`APIManagers/ApiEndpointManager.swift:2007-2012`; `app/src/main/java/gmail/com/snapfixapp/utils/APIEndPointUtils.java:376`).

**Request** (JSON body)

| Name           | In   | Type             | Required | Rules                                                                             |
| -------------- | ---- | ---------------- | -------- | --------------------------------------------------------------------------------- |
| `parent_uuids` | body | array of strings | yes      | The sites, any number. Missing: "Data cannot be blank!"; empty: "invalid parents" |

**Response** `200`: one item per site, in the order sent, with `parent_uuid` and `pack_hash` (`htmlphp/api/snapfix/class/paypack.functions.schema-v1.php:276-285`). `pack_hash` is the package of the site's newest current client link. A site without one gets the dispatcher's default package (`starterPackageUUID`, `html/api/snapfix/index.php:225`), which a code comment calls the unlimited package (`paypack.functions.schema-v1.php:21-23`).

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": [ { "parent_uuid": "123", "pack_hash": "4f6b2a10-9c3e-4d7a-8b21-5e0c7d3f9a64" } ]
}
```

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no body, or no `parent_uuids`); "invalid parents" (an empty list).

**Side effects:** for each live, active and current [`package_server_parent`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_parent.md) row of the sites named that is newer than the site's current client link, or for a site with no client link, the action copies the server package into [`package_client`](https://docs.snapfix.com/engineering-reference/db/tables/package_client.md) when it is not there yet, and adds a [`package_client_parent`](https://docs.snapfix.com/engineering-reference/db/tables/package_client_parent.md) row copied from the server link (`paypack.functions.schema-v1.php:160-273`). Unlike the uncalled `POST /v1/app/parents/packages`, it does copy the package. Reads and writes run on the writer connection.

## POST ?action=paywall

Lists the caller's sites with the caller's in-app purchase flag for each: the apps' in-app plan screen and the subscription card of their settings.

* **Auth:** user token. The user comes from the token payload (`getUserUUIDFromToken`), whose signature only the dispatcher checks, and only while `JWT_AUTH_ENABLED` is on (php-apis @ 238ca4414e, `htmlphp/api/snapfix/class/class.functions.php:39896-39899`).
* **Used by:** iOS (`APIManager.PAYWALL`, POST with an empty body, from the in-app plan screen `IAPPlanVC.checkSubscriptionStatus`, the settings' subscription section and the profile settings; ios @ aa31967ac8, `SnapFix/IAPPlanVC.swift:178`, `SnapFix/MySettingsVC+Subscription.swift:80`, `SnapFix/New Profile/Profile Settings/View Model/ProfileSettingViewModel.swift:189`) and Android (POST with an empty JSON object, from the profile's subscription card in `MyProfileActivity`; `InAppPlanActivity` calls it too, but nothing opens that screen, because its openers in the group list and the chat are commented out; android @ 86068bfeea, `app/src/main/java/gmail/com/snapfixapp/activity/InAppPlanActivity.kt:209-216`, `app/src/main/java/gmail/com/snapfixapp/activity/BusinessListingActivity.java:958-966`, `app/src/main/java/gmail/com/snapfixapp/fragment/JobChatFragment.java:5085-5091`, `:10537-10543`, `app/src/main/java/gmail/com/snapfixapp/activity/MyProfileActivity.kt:595`, `:2521-2528`, `app/src/main/java/gmail/com/snapfixapp/network/ApiService.java:399-401`).

**Request** (JSON body; the apps send it empty)

| Name          | In   | Type   | Required | Rules                                                                    |
| ------------- | ---- | ------ | -------- | ------------------------------------------------------------------------ |
| `parent_uuid` | body | string | no       | Only this site. A site the caller has no link to gives "invalid params!" |

**Response** `200`: one item per site, with `parent_id` (the site's row ID), `parent_uuid`, `name`, `fCustomerType`, `image` and `inapp_purchase` (`class.functions.php:39994-40004`).

* The sites are those where the caller has a live membership of a live group in a live site, and those where the caller has a live, unblocked admin site row (`:39906-39943`).
* `inapp_purchase` is the caller's newest live [`tPri_UserPaywall`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_userpaywall.md) flag for the site, and `1` when there is none. A live paywall row of the caller also adds its site to the list when the caller has no other link to it (`:39954-39977`) \[[ASK-144](https://github.com/snapfix/docs/blob/main/ASK.md#ask-144-who-may-buy-an-in-app-plan-for-a-site-and-who-sets-the-in-app-purchase-switch)].

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": [ { "parent_id": 42, "parent_uuid": "123", "name": "Riverside Hotel", "fCustomerType": "paying_customer", "image": null, "inapp_purchase": 1 } ]
}
```

**Errors:** `200` with `result` `false`: "invalid access!" (no user in the token); "invalid params!" (no site to list).

**Side effects:** none.

## POST ?action=prod\_get\_stripe\_customer\_id

Returns a site's Stripe customer ID in the live Stripe account, and creates the customer first when the site has none. The payment page calls it when it opens for a site and the package has no customer of its own.

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action does not check that the caller belongs to the site, so any signed-in user gets any site's customer ID, and can make the server create one (php-apis @ 238ca4414e, `html/api/snapfix/index.php:2270-2278`).
* **Used by:** web\_payments in the production build (`PaymentService.getStripeCustomerId` posts `${stripeMode}_get_stripe_customer_id`, and `stripeMode` is `prod`; web\_payments @ 7c2c3ddffd, `src/app/services/payment/payment.service.ts:26-32`, `src/environments/environment.prod.ts:7`). The payment component calls it on load, unless the site details already hold a customer ID or the package has its own (`src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:82`, `:161-186`).

**Request** (form fields)

| Name          | In   | Type   | Required | Rules                                                                                      |
| ------------- | ---- | ------ | -------- | ------------------------------------------------------------------------------------------ |
| `parent_uuid` | body | string | yes      | Any site, deleted ones included. Missing: "parent\_uuid must be mentioned in the request!" |

**Response** `200`

```json
{
  "result": true,
  "message": "Success",
  "serverTs": 1794387595000,
  "data": { "stripe_customer_id": "cus_example123" }
}
```

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no form fields); the missing-field message; "invalid parent" (no such site); "Failed to create stripe customer"; Stripe's own message (`htmlphp/api/snapfix/class/stripe.functions.php:259-357`).

**Side effects:** when the site has no `stripe_customer_id` (`stripe.functions.php:268-353`):

* The action looks for a Stripe customer whose email is the site's UUID at `snapfix.com`, and otherwise creates one.
* The new customer's name is the first and last name of the user on the site's newest live site row, of any role, with the site's name in brackets; with no such user, it is built from the site's name and free-text address. The email is that user's sign-in email, or an address made from the site's UUID. The site's newest basic address goes with it, and the site's UUID is the description. So a read sends a member's name and email to Stripe.
* It writes the ID to `stripe_customer_id` on [`tPri_Parent`](https://docs.snapfix.com/engineering-reference/db/tables/tpri_parent.md).

## POST ?action=read\_stripe\_product\_v3

Returns a package and its prices: the payment page's multi-price links, through authpy's [`/read-package-v3`](#post-read-package-v3).

* **Auth:** the shared Basic login only: the action is on the no-login list (php-apis @ 238ca4414e, `html/api/snapfix/index.php:355`). It checks no user and no site, so every holder of the login gets the same answer, the package's own Stripe customer ID included.
* **Used by:** authpy (`/read-package-v3` posts `{ "data": … }`; authpy @ 5d5758661c, `model/feature_php_api.py:167-171`).

**Request** (JSON body with a `data` object)

| Name         | In   | Type   | Required | Rules                                                                         |
| ------------ | ---- | ------ | -------- | ----------------------------------------------------------------------------- |
| `package_id` | data | string | yes      | A live package UUID. Missing: "package\_id must be mentioned in the request!" |

**Response** `200`: `message` "Success!" and `data`, a [package object](#package-object) (`htmlphp/api/snapfix/class/stripe.functions.php:1405-1452`).

**Errors:** `200` with `result` `false`: "Data cannot be blank!" (no `data`; `index.php:1438-1449`); the missing-field message; "no packages found!" (no live package with that UUID).

**Side effects:** none. The read runs on the writer connection.

## POST ?action=sandbox\_get\_stripe\_customer\_id

Returns a site's Stripe customer ID in the Stripe test account: the twin of [prod\_get\_stripe\_customer\_id](#post-actionprod_get_stripe_customer_id) (php-apis @ 238ca4414e, `html/api/snapfix/index.php:2306-2314`).

* **Auth:** as for the live action, with no membership check.
* **Used by:** web\_payments in the staging and development builds, through the same call as the live action, with `stripeMode` `sandbox` (web\_payments @ 7c2c3ddffd, `src/environments/environment.staging.ts:11`, `src/environments/environment.ts:11`).
* **Request, response, errors and side effects:** as for [prod\_get\_stripe\_customer\_id](#post-actionprod_get_stripe_customer_id), in the test account.

## POST ?action=snapfix\_package

Returns one price with its package's name: the payment page's single-price links.

* **Auth:** user token (Bearer JWT, if `JWT_AUTH_ENABLED` is on \[[ASK-12](https://github.com/snapfix/docs/blob/main/ASK.md#ask-12-which-settings-do-the-production-api-servers-use)]). The action checks no site, so any signed-in user can read any price's package name and amount by its UUID.
* **Used by:** web\_payments (`PaymentService.getPackagePrice`, POST JSON `{ "price_id" }`; web\_payments @ 7c2c3ddffd, `src/app/services/payment/payment.service.ts:43-47`). The page calls it for a single-price link only once the payer is signed in (`src/app/pages/auth/pay/pay.component.ts:241-243`, `:309-321`).

**Request** (JSON body)

| Name       | In   | Type   | Required | Rules                                                                                                                                                                                                     |
| ---------- | ---- | ------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `price_id` | body | string | yes      | A price UUID in [`package_server_pricing`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_pricing.md). Missing: "Data cannot be blank!" (`html/api/snapfix/index.php:1784-1790`) |

**Response** `200`: `data` has `package_name`, `uuid` (the price), `amount`, `currency`, `interval` and `uuid_package_server` (`htmlphp/api/snapfix/class/paypack.functions.schema-v1.php:110-120`). `amount` is in the currency's smallest unit; the page divides it by 100 (`src/app/pages/auth/pay/components/package-prices/package-prices.component.html:17`). `interval` is `na` for a one-off price. The lookup checks neither the price's nor the package's deleted flag, nor the package's dates.

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": { "package_name": "Starter", "uuid": "price-123", "amount": 4900, "currency": "gbp", "interval": "month", "uuid_package_server": "package-123" }
}
```

**Errors:** `200` with `result` `false`: "Data cannot be blank!"; "invalid package" (no such price).

**Side effects:** none.

## GET /v4/parent-pack

Lists sites with their counts and current package, one page at a time: the Parents tab of the staff admin app's paywall page.

* **Auth:** user token (`@jwt_required()`). The route checks no staff flag and no membership, so any signed-in user can page through every site's details and package (apipy @ 0e83c85e5a, `app.py:3353-3371`).
* **Used by:** webadmin\_angular (`AccountService.getPaywallAccounts`, from the Parents tab's table, on load and on each page, sort or search change; webadmin\_angular @ db972390b8, `src/app/services/account/account.service.ts:189-204`, `src/app/pages/paywall/components/paywall-accounts-table/paywall-accounts-table.component.ts:43-85`, `src/app/pages/paywall/paywall.component.html:46-52`).

**Request** (query string; [paging](https://docs.snapfix.com/engineering-reference/api.md#paging))

| Name         | In    | Type    | Required | Rules                                                                                                                       |
| ------------ | ----- | ------- | -------- | --------------------------------------------------------------------------------------------------------------------------- |
| `offset`     | query | integer | no       | The first row, default `0`. The table sends `(page - 1) × page size`                                                        |
| `limit`      | query | integer | no       | Rows per page, default `50`, with no maximum. The table offers 10, 50, 100, 200 and 500                                     |
| `search`     | query | string  | no       | Part of the site name, ignoring case. Empty means no filter                                                                 |
| `type`       | query | string  | no       | The site's customer type, matched exactly. The table does not send it                                                       |
| `sort_field` | query | string  | no       | A column of the answer, default `parent_created_ts`. The table sends `parent_name`, `parent_address` or `parent_created_ts` |
| `sort_type`  | query | string  | no       | `-1` sorts descending, the default; any other value ascending. The table sends `0` or `-1`                                  |

`offset`, `limit` and `sort_field` go into the SQL text unchecked, so a crafted value can run its own SQL (`model/v4/t_parent.py:488`). `search` and `type` are bound parameters.

**Response** `200`: `data` is `{ "total_count", "parent" }` (`model/v4/t_parent.py:445-588`). Each item has the site's `parent_uuid`, `parent_name`, `timezone_name`, `parent_address`, `customer_type`, `customer_type_ts`, `fRiskScore`, `fRiskScoreTs`, `fNextRenewalDateTs`, `fFirstInvoiceDateTs` and `parent_created_ts`; the counts `group_count`, `user_count` and `job_count`; and its current package: `package_server_uuid`, `package_name`, `marketing_bundle_name`, `package_schema` (the package's permission JSON), `package_start_ts`, `package_end_ts` and `package_associated_ts`.

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": {
    "total_count": 1,
    "parent": [
      {
        "parent_uuid": "123",
        "timezone_name": "Europe/London",
        "parent_name": "Riverside Hotel",
        "parent_address": "1 Quay Street",
        "customer_type": "paying_customer",
        "parent_created_ts": 1690000000000,
        "group_count": 3,
        "user_count": 12,
        "job_count": 27,
        "marketing_bundle_name": "Basic bundle",
        "package_server_uuid": "package-123",
        "package_name": "Starter",
        "package_start_ts": 1794387595000,
        "package_end_ts": 1825923595000,
        "package_schema": { "paywall_version": 1, "permission": { "task": { "limit": 100 }, "nfc_enabled": false } }
      }
    ]
  }
}
```

* Only sites with at least one group that has a member row are listed, but `total_count` counts every site that matches `search` and `type` (`model/v4/t_parent.py:472-478`, `:576-587`).
* Nothing filters deleted rows: deleted sites, groups, member rows and tasks are listed and counted.
* `user_count` counts distinct users. `group_count` counts member rows, not groups, because it counts group IDs over the join with the member rows (`:471-472`).
* The package is the site's newest live [`package_server_parent`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_parent.md) row whose package has a marketing bundle (`:522-545`). A site with no such row gets a built-in "Unlimited Package", with `package_start_ts` `null` and the end under `package_end_ms` instead of `package_end_ts` (`:562-573`) \[[ASK-150](https://github.com/snapfix/docs/blob/main/ASK.md#ask-150-what-plan-does-a-site-without-a-package-row-have)].
* The job count and package lookups pass the page's site IDs to `IN (%s)` as one joined string. The connector quotes it as a single value, so on a page with two or more sites they match nothing: every site shows the built-in package and a `job_count` of `0`. With one site on the page they work (`:515-516`, `:544-545`; `model/utils.py:109-130`). Seen in code, not run.

**Errors:** `200` with `result` `false` and "record(s) not found" when the page is empty (`config/constant.py:157`, `model/v4/t_parent.py:494-495`). `401` without a valid token. A blocked caller gets the abuse check's answer (`app.py:3360-3362`). Other errors, such as a bad `sort_field`, are not caught by the route and give HTTP `500`.

**Side effects:** none on the data.

## PUT /v4/parent-pack

Gives a site a package for a period and marks the site's other package rows deleted: the "Update parent package" dialog of the staff paywall.

* **Auth:** user token (`@jwt_required()`). The route checks no staff flag and no membership, and it does not compare `user_uuid` with the token's user, so any signed-in user can give any site any package for any period (apipy @ 0e83c85e5a, `app.py:3353-3354`, `:3372-3384`).
* **Used by:** webadmin\_angular (`AccountService.updatePaywallParentPackage`, from the dialog's "Save" button; the dialog opens from the edit button of a table row, and it sends the signed-in staff user's UUID; webadmin\_angular @ db972390b8, `src/app/services/account/account.service.ts:206-208`, `src/app/pages/paywall/components/paywall-account-modal/paywall-account-modal.component.ts:59-78`, `src/app/pages/paywall/components/paywall-account-modal/paywall-account-modal.component.html:2`, `:37`, `src/app/pages/paywall/components/paywall-accounts-table/paywall-accounts-table.component.html:45`).

**Request** (form fields; the admin app sends multipart, `src/app/services/http/http.service.ts:38`, and apipy reads `request.form`)

| Name                  | In   | Type         | Required | Rules                                                                                                                   |
| --------------------- | ---- | ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------- |
| `parent_uuid`         | body | string       | yes      | The site. Missing: "invalid parent\_uuid"; unknown: "invalid parent". A deleted site is accepted                        |
| `package_server_uuid` | body | string       | yes      | The package. Missing: "invalid package\_server\_uuid"; unknown: "invalid package server". A deleted package is accepted |
| `user_uuid`           | body | string       | yes      | Saved as the row's creator and modifier. Missing: "invalid user\_uuid". Not checked against the caller or any user      |
| `start_ts`            | body | integer (ms) | no       | Default: now. Stored as sent. The admin app does not send it                                                            |
| `end_ts`              | body | integer (ms) | no       | Default: 365 days from now. Stored as sent, so any period is accepted. The admin app does not send it                   |

**Response** `200`, with no `data`:

```json
{
  "result": true,
  "message": "parent package updated successfully",
  "serverTs": 1794387595000
}
```

**Errors:** `200` with `result` `false` and the first failed message above (`model/v4/t_parent.py:592-617`). `401` without a valid token. A blocked caller gets the abuse check's answer (`app.py:3375-3377`). Other errors are not caught by the route.

**Side effects:**

* Adds a [`package_server_parent`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_parent.md) row for the site, with the package and its `type`, `stripe_subscription_id` `default`, the start and end, and `user_uuid` as creator and modifier (`model/v4/t_parent.py:627-642`).
* Marks every other `package_server_parent` row of the site deleted, with `user_uuid` as the modifier (`:644`). The apps pick up the new package at their next [parent\_packages](#post-actionparent_packages) call.
* No Stripe call.

## POST /wh-production

Receives Stripe's live-mode events and stores each one.

* **Auth:** the Stripe signature, not a token. `stripe.Webhook.construct_event` checks the `Stripe-Signature` header with the live webhook secret, `PROD_WEBHOOK_SECRET` in the server's settings (apipy @ 0e83c85e5a, `app.py:400-412`). A missing or wrong signature is refused before anything is stored. A missing secret gives HTTP `500`: the settings reader raises `KeyError` and never returns its default (`model/utils.py:298-302`). The handler catches `stripe.error.SignatureVerificationError`; the pinned `stripe==10.2.0` (`requirements.txt:129`) is not in the clone, so that name is unchecked \[[ASK-151](https://github.com/snapfix/docs/blob/main/ASK.md#ask-151-does-stripe-1020-still-have-stripeerrorsignatureverificationerror)].
* **Used by:** Stripe, external (the live-mode webhook endpoint).

**Request:** the raw event body, with the `Stripe-Signature` header.

**Response** `200`: `data` is the stored [`stripe_log`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_log.md) row: `uuid`, `webhook_name` (the event type), `stripe_json` (the whole event) and `fCreatedTs` (`app.py:413-418`, `model/t_stripe_log.py:61-81`).

```json
{
  "result": true,
  "message": "success",
  "serverTs": 1794387595000,
  "data": { "uuid": "log-123", "webhook_name": "invoice.paid", "stripe_json": "{ ... the Stripe event ... }", "fCreatedTs": 1794387595000 }
}
```

**Errors:** `400` with `result` `false`: "Bad payload" (the body does not decode), "Bad signature" (the signature check fails), "Bad Request" (any other `ValueError`, a failed insert included) (`app.py:407-420`).

**Side effects:** inserts one `stripe_log` row with the event type and the whole event (`model/t_stripe_log.py:93-125`). The insert builds its SQL from the event text, so an apostrophe anywhere in the event, such as in a customer's name, makes it fail with "Bad Request". Nothing else is written: no `stripe_subscription` row and no package link \[[ASK-142](https://github.com/snapfix/docs/blob/main/ASK.md#ask-142-who-records-live-stripe-subscriptions)]. The uncalled `get_client_secret_key` reads these rows back.

## POST /wh-sandbox

Receives Stripe's test-mode events: it stores each one like [`/wh-production`](#post-wh-production), and also records subscriptions and payments.

* **Auth:** the Stripe signature, checked with the sandbox secret `SB_WEBHOOK_SECRET` as on the live endpoint (apipy @ 0e83c85e5a, `app.py:430-442`).
* **Used by:** Stripe, external (the test-mode webhook endpoint).

**Request** and **response:** as on [`/wh-production`](#post-wh-production) (`app.py:472`).

**Errors:** as on [`/wh-production`](#post-wh-production), and, after the event is stored:

* `400` "Bad Request" when no live site has the event's customer, or, for a payment, when that site has no subscription row still in the created state (`model/t_stripe_subscription.py:35-45`, `:128-153`).
* `400` "Bad Request" for a new subscription whose price matches a Snapfix price, because the package link insert fails (below).
* HTTP `500` when a `customer.subscription.created` event has no `plan`: the error is not caught (`app.py:449-455`).

**Side effects:**

* Every event: one `stripe_log` row, as on the live endpoint.
* `customer.subscription.created`: inserts a [`stripe_subscription`](https://docs.snapfix.com/engineering-reference/db/tables/stripe_subscription.md) row for the live site with that Stripe customer. It holds the site, the subscription ID and the event name as `subscription_status`, with `admin` as the creator; the customer, the price and the period are not stored in it (`model/t_stripe_subscription.py:31-69`).
* Then, when the subscription's price matches a `stripe_pricing_id` in `package_server_pricing`, the handler tries to add a [`package_server_parent`](https://docs.snapfix.com/engineering-reference/db/tables/package_server_parent.md) row for the site with the event's period. The insert always fails: its `VALUES` clause is filled with the subscription row's ten values for twelve columns, and its twelve parameters have no placeholders, which the database connector refuses. The webhook answers `400` with the subscription row already written, and each resend of the event adds another `stripe_log` and `stripe_subscription` row (`model/t_stripe_subscription.py:73-113`, `model/utils.py:275-292`).
* `payment_intent.succeeded`: sets `subscription_status` to `payment_intent.succeeded` on the newest `stripe_subscription` row of the live site with that customer whose status is still `customer.subscription.created` (`app.py:464-470`, `model/t_stripe_subscription.py:124-171`).
* The `customer.subscription.updated` branch is commented out (`app.py:456-463`).

## POST /create-stripe-subscription-v3

Checks the shared Basic login and passes the payment page's form on to php-apis [create\_stripe\_subscription\_v3\_guest](#post-actioncreate_stripe_subscription_v3_guest): the guest path for packages with their own Stripe customer.

* **Auth:** the shared app Basic login, which `verifyBasicAuth` compares with the settings' `BasicAuth_UserName` and `BasicAuth_Password` (authpy @ 5d5758661c, `auth.py:22-31`, `app.py:1393-1396`). No user token, and no check of the customer.
* **Used by:** web\_payments (`PaymentService.createSubscription` with `useGuestAPI` true, when the package has its own Stripe customer; it sends multipart form fields with the Basic login; web\_payments @ 7c2c3ddffd, `src/app/services/payment/payment.service.ts:34-41`, `src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:248-252`, `src/app/services/auth/auth-interceptor/auth.interceptor.ts:31-56`).

**Request** (form fields): the fields of [create\_stripe\_subscription\_v3\_guest](#post-actioncreate_stripe_subscription_v3_guest). authpy sends them on as `data`, with its own Basic login (`app.py:1398`, `model/feature_php_api.py:173-177`). The page also sends `user_uuid`, which the guest flow ignores.

**Response** `200`: php-apis's answer, unchanged, a [subscription result object](#subscription-result-object) on success (`app.py:1404-1409`). A blocked caller gets the abuse check's fake answer (`app.py:1399-1402`).

**Errors:** a wrong or missing login should get `200` with "invalid authentication" (`config/constant.py:137`), but the failure branch uses a variable that only the success branch sets, so the route fails with HTTP `500` (`app.py:1410-1412`). Other errors are php-apis's.

**Side effects:** those of [create\_stripe\_subscription\_v3\_guest](#post-actioncreate_stripe_subscription_v3_guest).

## POST /read-package-v3

Checks the shared Basic login and passes a package ID on to php-apis [read\_stripe\_product\_v3](#post-actionread_stripe_product_v3): the payment page's multi-price links.

* **Auth:** the shared app Basic login, as above (authpy @ 5d5758661c, `app.py:1370-1374`). No user token; every holder of the login gets the same answer.
* **Used by:** web\_payments (`PaymentService.getPackage`, POST JSON with the Basic login, for a multi-price link, before the payer signs in too; web\_payments @ 7c2c3ddffd, `src/app/services/payment/payment.service.ts:49-53`, `src/app/pages/auth/pay/pay.component.ts:267-310`).

**Request** (JSON body)

| Name         | In   | Type   | Required | Rules                                     |
| ------------ | ---- | ------ | -------- | ----------------------------------------- |
| `package_id` | body | string | yes      | The package. Sent on as `data.package_id` |

**Response** `200`: php-apis's answer, unchanged: `message` "Success!" and a [package object](#package-object) in `data` (`app.py:1384-1387`). The page refuses a package whose start is still to come or whose end has passed (`pay.component.ts:277-287`).

**Errors:** those of [read\_stripe\_product\_v3](#post-actionread_stripe_product_v3). A wrong or missing login gives HTTP `500` instead of "invalid authentication", as above (`app.py:1388-1390`).

**Side effects:** none.

## Package object

A package with its live prices, as [read\_stripe\_product\_v3](#post-actionread_stripe_product_v3) and [`/read-package-v3`](#post-read-package-v3) return it (php-apis @ 238ca4414e, `htmlphp/api/snapfix/class/stripe.functions.php:1405-1449`).

| Field                                          | Type            | Meaning                                                                                                                                                                                                                                                                                                                                            |
| ---------------------------------------------- | --------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `package_uuid`, `package_name`                 | string          | The package's ID and name                                                                                                                                                                                                                                                                                                                          |
| `created_at`                                   | integer         | When the package was created, in ms                                                                                                                                                                                                                                                                                                                |
| `fStartTs`, `fEndTs`                           | integer         | The package's validity, in ms. The payment page refuses a package outside it                                                                                                                                                                                                                                                                       |
| `subscription_start_date_ts`                   | integer or null | When set, the page fixes the subscription's start date to it                                                                                                                                                                                                                                                                                       |
| `days_past_permitted`, `days_future_permitted` | integer or null | Otherwise, how many days before and after today the page lets the payer pick as the start date (web\_payments @ 7c2c3ddffd, `src/app/pages/auth/pay/components/pay-package-payment/pay-package-payment.component.ts:306-322`)                                                                                                                      |
| `card_eft`                                     | string or null  | The payment methods the page offers, comma-separated: `card` and `sepa_debit`. With `sepa_debit` alone, the page opens on SEPA Direct Debit (`pay-package-payment.component.ts:153-158`, `src/app/shared/enums.ts:12-15`)                                                                                                                          |
| `stripe_customer_id`                           | string or null  | The package's own Stripe customer. When it is set, the page uses the guest path and charges this customer, unless a signed-in buyer's chosen site has a customer of its own \[[ASK-225](https://github.com/snapfix/docs/blob/main/ASK.md#ask-225-which-stripe-customer-should-a-signed-in-buyer-of-a-package-with-its-own-customer-be-charged-on)] |
| `price_items`                                  | array           | The prices: `uuid` (sent back as `price_items[].id`), `name` (the price's description), `mandatory`, `recurring` (the interval, `na` for a one-off price), `currency`, `amount` (in the currency's smallest unit), `qty_editable`, `qty_default`, `qty_min` and `qty_max`                                                                          |

```json
{
  "result": true,
  "message": "Success!",
  "serverTs": 1794387595000,
  "data": {
    "package_uuid": "package-123",
    "package_name": "Starter",
    "created_at": 1790000000000,
    "fStartTs": 1790000000000,
    "fEndTs": 1900000000000,
    "subscription_start_date_ts": null,
    "days_past_permitted": 0,
    "days_future_permitted": 30,
    "card_eft": "card",
    "stripe_customer_id": null,
    "price_items": [
      { "uuid": "price-123", "name": "Monthly", "mandatory": 1, "recurring": "month", "currency": "gbp", "amount": 4900, "qty_editable": 1, "qty_default": 1, "qty_min": 1, "qty_max": 10 }
    ]
  }
}
```

## Subscription result object

What the subscription calls return in `data`: [create\_stripe\_subscription\_v3](#post-actioncreate_stripe_subscription_v3), [create\_stripe\_subscription\_v3\_guest](#post-actioncreate_stripe_subscription_v3_guest) and [`/create-stripe-subscription-v3`](#post-create-stripe-subscription-v3) (php-apis @ 238ca4414e, `htmlphp/api/snapfix/class/stripe.functions.php:1685`, `:1855-1859`, `:2114`, `:2283-2337`).

| Field                                                                  | Type             | Meaning                                                                                                                            |
| ---------------------------------------------------------------------- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `subscription_id`                                                      | string           | The Stripe subscription ID; `""` for a one-off invoice                                                                             |
| `client_secret`                                                        | string or null   | The secret of the first payment's intent, which the page confirms with Stripe.js                                                   |
| `subscriptionDetail`                                                   | object           | The whole Stripe subscription object, for subscriptions only. The guest route returns it to any holder of the login                |
| `subscriptionTemp`, `clientSecretError`, `invoice`, `finalizedInvoice` | object or string | Guest route only, when the first answer had no client secret (see [its response](#post-actioncreate_stripe_subscription_v3_guest)) |


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.snapfix.com/engineering-reference/api/billing.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
