# Events API reference > **Who this is for:** developers who send events to App Store Operator from their own code or server, and the AI coding agents they hand this page to. It is the whole HTTP contract on one page, with a curl quickstart. To add tracking to an app, start from the platform guide instead ([§11](#11-platform-guides)): it has ready-made tracker code built on this API. --- ## For AI coding agents: read this first You are calling the App Store Operator Events API: `POST https://api.app-store-operator.com/v1/events` and `POST https://api.app-store-operator.com/v1/identify`, authenticated by the header `X-Write-Key`. **Rules** - **The write key.** If this page still contains `YOUR_WRITE_KEY`, ask the developer for their key (Dashboard → their app → Events → Setup; it starts with `aso_wk_`). Never invent a key or leave the placeholder in code. - **Adding tracking to an iOS, Flutter or React Native app?** Use the platform guide in [§11](#11-platform-guides) and its tracker code, unchanged. Write your own client from this page only when no guide fits (a server, a game engine, another language). - **Every event gets its own `event_id`** (a UUID), created when the event happens, not when it is sent. Retries reuse it, so nothing is counted twice. - **Retry only on a network failure, `429` and `5xx`**, keeping the batch and its `event_id`s; on `429` wait the `Retry-After` seconds. Drop the batch on every other status ([§7](#7-errors)). - **Property values are flat:** string, number, boolean or `null`. No nested objects or arrays. - **Never send** names, emails, phone numbers, precise location, the IDFA or text a user typed, in event names, properties or `user_id`. - **Check your work against the live API.** Send one event with the [§3](#3-quickstart-send-one-event) curl command and confirm the response is `accepted: 1`, then confirm your own code gets the same response. Ask the developer to check the events under Dashboard → Events → Live with the environment filter on **All builds**. The write key is public by design: it can only write events for one app, so it may live in app code. --- ## 1. Quick facts | | | |---|---| | Base URL | `https://api.app-store-operator.com/v1` | | Auth | Header `X-Write-Key: ` | | Send events | `POST /v1/events`, a batch of 1–100 events, body up to 1 MB | | Link a user | Automatic when an event carries both `anonymous_id` and `user_id`; or `POST /v1/identify` | | Content type | `application/json`, UTF-8 | | Rate limits | 10,000 events a minute per write key (500 on the Free plan), and 300 a minute per install (`anonymous_id`) ([§9](#9-rate-limits)) | | Monthly events | Counted per account across all its apps, reset on the 1st (UTC). Free: 25,000 a month. Past 110% of your plan's limit, new events are refused until the next month | | Event names | Up to 500 different names per app | | Data retention | 13 months | ## 2. Get your write key 1. Open the App Store Operator dashboard → **Apps** → your app → **Events** → **Setup**. 2. Copy the write key. It starts with `aso_wk_`. Each app has its own key; use it only for that app's events. Anyone in your workspace can see it there. ## 3. Quickstart: send one event Run this from a terminal (macOS or Linux). It creates a new `event_id` and the current time on every run, so you can run it again: ```bash curl -sS https://api.app-store-operator.com/v1/events \ -H "Content-Type: application/json" \ -H "X-Write-Key: YOUR_WRITE_KEY" \ -d '{ "events": [{ "event_id": "'"$(uuidgen)"'", "name": "integration_test", "anonymous_id": "curl-test", "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'", "properties": { "source": "curl" } }] }' ``` Expected response: ```json { "accepted": 1, "rejected": [], "clamped": [] } ``` The event appears in the dashboard under **Events → Live** within a few seconds. It carries no environment, so it shows in the default view; find it by its `anonymous_id`, `curl-test`. Why fresh values: a repeated `event_id` is stored only once, so a second run with the same ID shows nothing new, and a time more than 7 days old is replaced by the time we received it. ## 4. Read the response `POST /v1/events` answers `200 OK` whenever the batch itself is valid, even if some events in it were rejected: ```json { "accepted": 2, "rejected": [ { "index": 2, "event_id": "9a1c0d7e-2b4f-4c55-9f0e-7d3a1b2c4e5f", "code": "invalid_name", "message": "Event name must match ^[A-Za-z0-9_.:-]{1,64}$" } ], "clamped": [ { "index": 0, "event_id": "0b6f6a3e-3c3e-4d8a-8f6e-1f9b8a2c7d10" } ] } ``` - `accepted`: events stored, including repeats of an `event_id` that was already stored. - `rejected`: events that were not stored. `index` is the event's position in your `events` array (from 0), `event_id` is `null` when the event had no readable one, and `code` says why ([§7.1](#71-per-event-rejection-codes)). Do not retry them unchanged. - `clamped`: events whose `occurred_at` was out of range and was replaced by the time we received them. They are stored and counted in `accepted`. All three fields are always present; `rejected` and `clamped` may be empty. Any other status is an error for the whole request ([§7](#7-errors)): nothing in it was stored. ## 5. The event object The body of `POST /v1/events` is `{ "events": [ ... ] }` with 1 to 100 event objects. Unknown fields, in the body or in an event, are ignored. | Field | Type | Required | Rules | |---|---|---|---| | `event_id` | string (UUID) | yes | Unique per event. Create it when the event happens, not when it is sent, so a retried batch is not counted twice. | | `name` | string | yes | `^[A-Za-z0-9_.:-]{1,64}$`. A `$` followed by 1–63 of those characters (e.g. `$session_start`) is reserved for App Store Operator. Use `snake_case` `object_action`, e.g. `paywall_viewed`. Names are case-sensitive. | | `anonymous_id` | string | yes | 1–128 chars. Stable per install (or per device or browser on other clients). | | `user_id` | string or null | no | 1–128 chars. Your own stable user ID. Never an email or phone number. | | `occurred_at` | string | yes | ISO 8601 with timezone, e.g. `2026-10-23T12:00:00.123Z`. Accepted from 7 days in the past to 5 minutes in the future; outside that, it is replaced by the receive time (`clamped`). | | `properties` | object | no | Flat object, at most 50 keys. Key: 1–64 chars. Value: string (≤ 1024 chars), number, boolean or `null`. No nested objects or arrays. | | `context` | object | no | Device and build details, below. The dashboard filters and breaks funnels down by them. | **`context`** | Field | Example | Notes | |---|---|---| | `app_version` | `"2.4.0"` | The marketing version | | `build` | `"412"` | The build number | | `os_version` | `"18.1"` | | | `device_model` | `"iPhone16,2"` | Hardware identifier, not a marketing name | | `locale` | `"en_US"` | The device locale, `language_REGION` | | `environment` | `"app_store"` | `"debug"`, `"testflight"` or `"app_store"`. The dashboard shows only `app_store` events (and events without it) unless you choose **All builds** | Every `context` value is a string of at most 64 characters. A value that breaks this, and any key not in this table, is dropped without rejecting the event. The server adds the `country` from the request's network location. The IP address itself is never stored. A serialized event must be at most **8 KB**, and the whole body at most **1 MB**. **A full event** ```json { "event_id": "0b6f6a3e-3c3e-4d8a-8f6e-1f9b8a2c7d10", "name": "purchase_completed", "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723", "occurred_at": "2026-10-23T12:04:31.512Z", "properties": { "product_id": "pro_yearly", "price": 39.99, "currency": "USD", "trial": true, "coupon": null }, "context": { "app_version": "2.4.0", "build": "412", "os_version": "18.1", "device_model": "iPhone16,2", "locale": "en_US", "environment": "app_store" } } ``` ## 6. Link a user: `POST /v1/identify` Links an anonymous ID to a user ID without sending an event. You rarely need it: any event that carries both IDs does the same. Use it when the link is known on your server. ```bash curl -sS -i https://api.app-store-operator.com/v1/identify \ -H "Content-Type: application/json" \ -H "X-Write-Key: YOUR_WRITE_KEY" \ -d '{ "anonymous_id": "curl-test", "user_id": "u_81723" }' ``` Both fields are required, each a string of 1–128 chars. The response is `204 No Content` with no body. The first link for an anonymous ID wins; later different user IDs for the same anonymous ID are ignored. Errors use the same codes as `/v1/events` ([§7](#7-errors)): `400 invalid_body` when the body is not JSON or either ID is missing or not a 1–128 char string, `401 invalid_write_key`, `413 payload_too_large`, and `429 rate_limited`, because each call counts as one event against the write key's rate limit. ## 7. Errors Every error has the body `{ "code": "…", "message": "…" }` and means nothing in the request was stored. | Status | `code` | Meaning | What to do | |---|---|---|---| | 400 | `invalid_body` | The body is not valid JSON or not `{ "events": [...] }`, or it has 0 or more than 100 events | Fix the code; do not retry | | 401 | `invalid_write_key` | The key is missing, unknown or revoked. `/v1/events` also answers it when the app was removed from App Store Operator, its App Store Connect connection was deleted, or the workspace's account was disabled | Do not retry; drop the batch and check the key in Setup | | 403 | `quota_exceeded` | The account has used 110% of its monthly event limit | Do not retry; drop the batch. Sending resumes on the 1st (UTC) or after an upgrade | | 413 | `payload_too_large` | The body is over 1 MB | Send smaller batches | | 429 | `rate_limited` | Over a rate limit ([§9](#9-rate-limits)). The `Retry-After` header gives the seconds to wait | Keep the batch; retry after `Retry-After` seconds | | 5xx | `server_error` | Our fault | Keep the batch; retry with backoff (for example 30 s, 60 s, 120 s… up to 10 minutes) | **Retry rule in one line:** retry on a network failure, `429` and `5xx`, keeping the same `event_id`s; drop on every other status. ### 7.1 Per-event rejection codes These come inside a `200` response, in `rejected`. Only that event is skipped; the rest of the batch is stored. | Code | When | |---|---| | `invalid_event` | The item in `events` is not a JSON object | | `invalid_name` | `name` missing, or not matching `^[A-Za-z0-9_.:-]{1,64}$` | | `reserved_name` | `name` is `$` followed by 1–63 characters from `[A-Za-z0-9_.:-]` | | `invalid_id` | `event_id` missing or not a UUID; `anonymous_id` missing or not a 1–128 char string; `user_id` present but not a 1–128 char string or `null` | | `invalid_timestamp` | `occurred_at` missing, unparseable, or without a timezone. (Out of range is not a rejection: see `clamped`) | | `invalid_properties` | `properties` not a flat object; a key outside 1–64 chars; a nested object or array; a string over 1,024 chars | | `too_many_properties` | More than 50 properties | | `event_too_large` | The serialized event is over 8 KB | | `too_many_event_names` | The app already has 500 different event names and this one is new. Reuse a name and put the detail in a property | ## 8. Limits | Limit | Value | |---|---| | Events per request | 1–100 | | Request body | 1 MB | | One event, serialized | 8 KB | | Event name | 1–64 chars from `A–Z a–z 0–9 _ . : -` | | Properties per event | 50; key 1–64 chars; string value up to 1,024 chars | | `anonymous_id`, `user_id` | 1–128 chars | | `occurred_at` | 7 days in the past to 5 minutes in the future, else replaced by the receive time | | Different event names per app | 500 | | Property keys listed per event name in the dashboard's catalog | 200 (later keys are stored but not listed) | | Monthly events per account | Your plan's limit (Free: 25,000), counted across all apps and reset on the 1st (UTC). We email you at 80%, 100% and 110%; from 110% new events get `403 quota_exceeded` | | Retention | 13 months, then deleted automatically | ## 9. Rate limits Two limits apply at once, each refilling continuously over a minute: - **Per write key: 10,000 events a minute** (**500 on the Free plan**), from all installs together. It counts every event in every request, **rejected ones included**, and each `/v1/identify` call as one (identify calls always have the 10,000 limit). - **Per install: 300 events a minute** for one `anonymous_id`. It counts that install's accepted events. A request that would go over either limit gets `429 rate_limited` with a `Retry-After` header in seconds, and nothing in it is stored or counted. Keep the batch and send it again after that many seconds. Batching events (up to 100 a request) does not change how many events count, but it keeps the number of requests low. ## 10. Rotate the key Rotate the key only if it is being abused, for example if someone is sending fake events with it. The key is public, so being visible in your app is not a reason to rotate. 1. Setup → **Rotate key**. Any member of the workspace can do this, and it is recorded. 2. Put the new key in your app and ship an update. 3. The old key keeps working for **30 days**, so your users have time to update. After that, requests with the old key get `401 invalid_write_key`. 4. If the old key is still being abused, Setup → **Revoke old key now** ends its 30 days at once. 5. While an old key is in its 30 days, **Rotate key** is disabled. To rotate again, revoke the old key first or wait until its 30 days end. ## 11. Platform guides Step-by-step integration with a ready-made tracker (batching, retries, offline queue, consent switch), what to track, privacy and the App Store privacy label: - iOS (Swift): https://app-store-operator.com/docs/events/ios - Flutter: https://app-store-operator.com/docs/events/flutter - React Native: https://app-store-operator.com/docs/events/react-native Each guide is also served as plain Markdown for AI coding agents: add `.md` to its address, for example https://app-store-operator.com/docs/events/ios.md. Privacy questions and deletion requests: `privacy@app-store-operator.com`. --- # MCP server > **Who this is for:** App Store Operator users who want to read and manage their App Store apps from an AI app (Claude, ChatGPT, Cursor, Claude Code, VS Code and others that support MCP), and the AI agents they hand this page to. It covers connecting, what the AI app can see and do, the tools, limits, revoking and troubleshooting. --- ## For AI coding agents: read this first You are connecting an AI app to App Store Operator's MCP server, or using its tools. - **Server URL:** `https://api.app-store-operator.com/mcp` (Streamable HTTP). Sign-in is OAuth in the browser: the user approves the connection on App Store Operator's own page. There is no API key or token to paste; never ask the user for their password or App Store Connect key. - **Setup:** use the snippet for the user's AI app in [§3](#3-connect-your-ai-app). If the user's app is not listed, add the URL as a remote MCP server with OAuth. - **Live App Store changes take two calls** ([§6](#6-live-app-store-changes-two-steps)). The first call returns a preview and a confirm code and changes nothing. Show the preview to the user and call again with `confirm` only after they say yes. Never confirm on your own. - **Figures** are exactly what the user's dashboard shows; each tool's description gives the units. Do not invent data the tools did not return (search volumes, rankings). - **Check your work end to end:** after connecting, call `whoami` and tell the user which account, workspace and access (read only, or read and change) the connection has. Then call `list_apps` to show the connection works. - **Errors** are plain English sentences: relay them to the user in their language ([§11](#11-troubleshooting)). --- ## 1. Quick facts | | | |---|---| | Server URL | `https://api.app-store-operator.com/mcp` | | Transport | Streamable HTTP, stateless (`POST` only) | | Sign-in | OAuth 2.1 with PKCE and dynamic client registration; you approve each connection on App Store Operator's consent page | | Access | **Read only** or **Read and change**, chosen by you on the consent page | | Tools | 40: apps, metadata, versions, review submission, reviews, screenshots, analytics, events and funnels ([§7](#7-tools)) | | Saved prompts | `aso_audit`, `reply_to_reviews`, `weekly_report` ([§8](#8-prompts)) | | Limits | 120 tool calls a minute and 30 live App Store changes an hour, per connection ([§9](#9-limits)) | | Manage connections | Dashboard → **Settings** → **AI apps** | ## 2. Before you start - An App Store Operator account, with at least one App Store Connect connection if you want the AI app to see apps. - An AI app that supports remote MCP servers with OAuth sign-in. - The server URL. It is also in the dashboard under **Settings** → **AI apps**, with a **Copy** button. ## 3. Connect your AI app Add the server URL to your AI app as below. The first time the AI app uses it, it opens App Store Operator in your browser to approve the connection ([§4](#4-approve-the-connection)). ### 3.1 Claude In Claude (web or desktop): **Settings** → **Connectors** → **Add custom connector**, paste `https://api.app-store-operator.com/mcp` and add it. Then select **Connect** on the new connector to sign in. ### 3.2 ChatGPT In ChatGPT: **Settings** → **Connectors**, add a custom connector and paste `https://api.app-store-operator.com/mcp`. Custom connectors are not available on every ChatGPT plan; if you don't see the option, check OpenAI's help for your plan. ### 3.3 Claude Code Run this in a terminal: ```bash claude mcp add --transport http app-store-operator https://api.app-store-operator.com/mcp ``` Add `--scope user` to use it in every project, not only the current one. Then, inside Claude Code, run `/mcp`, choose `app-store-operator` and sign in. The saved prompts appear as slash commands, for example `/mcp__app-store-operator__weekly_report`. ### 3.4 Cursor Add the server to `mcp.json`: `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` in one project. ```json { "mcpServers": { "app-store-operator": { "url": "https://api.app-store-operator.com/mcp" } } } ``` Cursor then shows the server in its MCP settings; sign in from there when it asks. ### 3.5 VS Code Add the server to `.vscode/mcp.json` in your project (or to your user MCP configuration), then start it from the file or the MCP server list and sign in when asked: ```json { "servers": { "app-store-operator": { "type": "http", "url": "https://api.app-store-operator.com/mcp" } } } ``` ### 3.6 Other AI apps Any AI app that supports remote MCP servers over HTTP with OAuth can connect: add `https://api.app-store-operator.com/mcp` as the server URL. App Store Operator registers the app automatically during sign-in; there is no client ID or secret to set up. ## 4. Approve the connection When the AI app connects, your browser opens App Store Operator's consent page. Sign in to the dashboard if asked. The page shows: - the AI app's name and the address it will send you back to; - your account and the workspace the connection will use; - the access to give: **Read only** or **Read and change** ([§5](#5-what-the-ai-app-can-see-and-do)). Select **Allow** to connect, or cancel to connect nothing. After **Allow**, go back to your AI app. We also email you that an AI app was connected, with a link to **Settings** → **AI apps**, so you notice a connection you did not make. Only allow AI apps you trust. Each connection works in one workspace, the one shown on the consent page. To use another workspace, connect again while that workspace is selected in the dashboard. ## 5. What the AI app can see and do **Read only** - Your account's email address and name, and your workspace. - Your apps, their metadata, versions, drafts and change history. - Customer reviews, including reviewers' nicknames and text. - App Store analytics, with Apple's sales and proceeds estimates. - Events data and funnels, including the identifiers and device details your apps send. - The status of your App Store Connect connections (never the key itself). **Read and change**: everything in Read only, plus: - In App Store Operator only: edit metadata drafts, restore a past value into a draft, discard a draft, create, edit and delete funnels, start syncs, and recheck a connection. - In App Store Connect: create a new version (not visible to App Store users until it is submitted and released). - **On the live App Store**, each with the two-step confirm ([§6](#6-live-app-store-changes-two-steps)): push metadata, submit a version for review or remove it from review, reply to a review or delete a reply, reorder or delete screenshots. An AI app never receives your App Store Connect key or your password. It cannot add or remove App Store Connect connections or delete your account, and it works only within the permissions your role in the workspace gives you. In **History**, a change made through an AI app is marked with the app's name (for example "via Claude"). What the AI app reads goes to the company that provides it, which handles it under its own terms and may process it outside your country. Our privacy policy explains this: https://app-store-operator.com/privacy ## 6. Live App Store changes: two steps Tools that change what App Store users see (`push_draft`, `submit_for_review`, `cancel_submission`, `reply_to_review`, `delete_review_reply`, `reorder_screenshots`, `delete_screenshot`) never act on the first call: 1. The AI app calls the tool. App Store Operator changes nothing and returns `status: "not_changed_yet"`, a **preview** of the change and a **confirm code**. 2. The AI app shows you the preview and asks you. 3. Only after you agree, it calls the same tool again with the same input plus the confirm code. Then the change is made. A confirm code works once, for 10 minutes, for that tool with exactly that input. If the input changes or the code expires, the AI app must ask for a new preview. Metadata pushes are kept in **History**, so you can restore an earlier value; review replies and screenshot changes cannot be undone from App Store Operator. ## 7. Tools **Access**: *read* tools work on every connection; *change* tools change App Store Operator (or start work in App Store Connect) and need **Read and change**; *live* tools also change the live App Store and use the two-step confirm. A read-only connection does not list change and live tools at all. | Tool | Access | What it does | |---|---|---| | `whoami` | read | The account and workspace this connection acts for, and its access | | `list_apps` | read | Your apps across every App Store Connect connection, with their ids | | `get_app` | read | One app's overview: versions and their states, ratings, setup state | | `list_versions` | read | An app's live version and any in progress, with draft edit counts | | `get_metadata` | read | A version's store listing per locale: live value, draft value, editable or not | | `preview_draft` | read | What pushing the draft would change, diffed against live App Store Connect values | | `get_push_status` | read | Progress of a push, per locale and field | | `get_submission` | read | Whether a version can be sent to App Review, the blocking issues and the builds to choose from | | `list_history` | read | Changes to store listings, newest first, with previous and new values | | `get_sync_run` | read | Status of a background sync, version creation or submission | | `sync_app` | change | Re-reads an app's versions and metadata from App Store Connect | | `create_version` | change | Creates a new iOS App Store version in App Store Connect | | `update_draft` | change | Saves values into a version's draft; nothing reaches the App Store until a push | | `discard_draft` | change | Deletes a version's unpushed draft | | `restore_change` | change | Puts a past value from History back into the draft | | `push_draft` | live | Sends the draft's values to App Store Connect | | `submit_for_review` | live | Attaches a build and submits the version to App Review | | `cancel_submission` | live | Takes a version waiting for App Review back out of review | | `list_reviews` | read | An app's written reviews with any developer reply, filterable by rating and reply state | | `get_analytics` | read | App Store analytics for a period: totals, previous period, daily figures, sources, territories | | `get_visuals` | read | An app's versions and the newest version's screenshots in the primary locale | | `list_screenshots` | read | A version's screenshots in one locale, read live from App Store Connect | | `list_connections` | read | Your App Store Connect connections, their status and last error | | `revalidate_connection` | change | Checks a connection's API key with Apple again | | `sync_reviews` | change | Fetches an app's newest reviews from App Store Connect | | `reply_to_review` | live | Publishes or replaces a developer reply to a review | | `delete_review_reply` | live | Deletes the developer reply to a review | | `reorder_screenshots` | live | Puts one screenshot set in a new order | | `delete_screenshot` | live | Deletes one screenshot from an editable version | | `get_event_catalog` | read | Every event name an app has sent, with property keys and counts | | `get_event_trends` | read | How often events happened over time, as event counts or distinct people | | `get_recent_events` | read | The newest 100 raw events, as on the Live view | | `get_event_usage` | read | Your account's events this month against its plan limit | | `list_funnels` | read | An app's saved funnels | | `get_funnel` | read | One saved funnel's definition | | `run_funnel` | read | A saved funnel's result over a date range | | `preview_funnel` | read | An unsaved funnel's result, to try it before saving | | `create_funnel` | change | Saves a new funnel, shared with the workspace | | `update_funnel` | change | Changes a saved funnel | | `delete_funnel` | change | Deletes a saved funnel; its events are kept | ## 8. Prompts ### 8.1 Saved prompts The server offers three saved prompts. Your AI app lists them where it shows MCP prompts (in Claude Code, as slash commands): | Prompt | Arguments | What it does | |---|---|---| | `aso_audit` | `appId`, optional `locale` | Audits an app's listing against ASO best practice and gives prioritised changes. Changes nothing unless you ask | | `reply_to_reviews` | `appId`, optional `rating` (e.g. `1,2`) | Drafts replies to unanswered reviews in each review's language and sends only the ones you approve | | `weekly_report` | optional `appId` | A short report of the last 7 days against the 7 before: traffic, conversion, downloads, proceeds, reviews, changes, a funnel and 3 actions. Read only | ### 8.2 Example prompts You can also just ask. For example: - "Which of my apps had the most impressions last month, and how did their conversion change?" - "Show the unanswered 1- and 2-star reviews of Barmly from the last two weeks and draft replies. Don't send anything yet." - "Compare the English and German subtitles and keywords of my newest app, and suggest better ones with character counts." - "Put the new What's New text into the draft for every locale, then show me the diff before pushing." - "Is version 2.4 ready to submit for review? What is blocking it?" - "Build a funnel from onboarding_started to purchase_completed with a one-day window and show last week's result. Don't save it." - "How many events have we used this month, and which app sends the most?" ## 9. Limits Each connection can make: - **120 tool calls a minute**, and - **30 live App Store changes an hour** (counted when a change is confirmed, not at the preview). Apple allows each App Store Connect API key about 3,500 calls an hour, shared with your dashboard's syncs; these limits keep one AI app from using them all up. Over a limit, the tool answers "Limit reached" with the seconds to wait. ## 10. Revoke a connection Dashboard → **Settings** → **AI apps** → **Connected apps** lists each connection with its access, when it was connected and when it was last used. Select **Revoke** to end one: the AI app loses access at once. To use it again, connect it again from the AI app. A connection also ends on its own: - after **90 days** without use; - when you reset your password (every connection ends); - when your account is deleted or disabled. Signing out of the dashboard does not end a connection, and removing App Store Operator in the AI app may not end it on our side. To be sure, revoke it in **Settings** → **AI apps**. Revoking stops further access but does not remove data the AI app's provider already received; ask the provider for that. ## 11. Troubleshooting | Symptom | Cause and fix | |---|---| | The AI app says "Sign in to App Store Operator again" or asks to re-authenticate | The connection ended (revoked, 90 days unused, password reset) or its sign-in expired. Reconnect from the AI app | | "This AI app isn't registered with App Store Operator" on the consent page | Remove App Store Operator from your AI app and add it again | | "This connection request doesn't match the AI app that started it" or "This connection link doesn't work" | The sign-in link was changed or is incomplete. Start the connection again from your AI app | | "This connection can only read" | The connection is Read only. Revoke it in **Settings** → **AI apps**, reconnect and choose **Read and change** | | The change tools are missing | Same cause: a read-only connection does not list them | | "Limit reached: this connection can make…" | Over a limit ([§9](#9-limits)). Wait the seconds the message gives | | "This confirm code is invalid, already used, expired, or was given for a different change" | The AI app must call the tool again without `confirm`, show you the new preview and ask you again | | `list_apps` returns nothing | The workspace has no App Store Connect connection yet, or the connection is in another workspace. Check `whoami` and the dashboard | | A tool reports an error from Apple | Check the connection with `list_connections`; after fixing the key in the dashboard, run `revalidate_connection` | | An app or figure looks out of date | Run `sync_app` (metadata, versions) or `sync_reviews` (reviews). Apple's analytics run about two days behind | | "Something went wrong on App Store Operator's side" | Try again in a moment. If it keeps happening, contact support with the request ID from the message | ## 12. Technical details for MCP client developers - **Protected resource metadata** (RFC 9728): `https://api.app-store-operator.com/.well-known/oauth-protected-resource/mcp`. A request without a valid token gets `401` with a `WWW-Authenticate: Bearer resource_metadata="…"` header pointing to it. - **Authorization server metadata** (RFC 8414): `https://api.app-store-operator.com/.well-known/oauth-authorization-server`. - **Dynamic client registration** (RFC 7591): `POST https://api.app-store-operator.com/oauth/register`. Public clients only (`token_endpoint_auth_method: none`). Redirect URIs must be `https`, `http` on a loopback address, or a private-use scheme with a dot (such as `cursor.app:`). - **Authorization**: `https://api.app-store-operator.com/oauth/authorize`, authorization code with PKCE `S256` only. The response includes `iss` (RFC 9207). - **Tokens**: `POST https://api.app-store-operator.com/oauth/token` with `authorization_code` or `refresh_token`. Access tokens last 1 hour. Refresh tokens rotate on every use; reusing one ends the whole connection. - **Endpoint**: `POST /mcp` with `Authorization: Bearer `. The server is stateless: there is no session and no server-sent event stream, so `GET` and `DELETE` answer `405`. - **Tool annotations**: read tools have `readOnlyHint: true`; live tools have `destructiveHint: true` and an extra optional `confirm` argument. --- # App Store Operator Events: integration guide for iOS (Swift) > **Who this is for:** iOS developers adding event tracking to a native Swift app (SwiftUI or UIKit), and the AI coding agents they hand this document to. It is self-contained: an agent can complete the integration from this file alone. --- ## For AI coding agents: read this first You are adding event tracking to an iOS app so its owner can build funnels in App Store Operator. The app will send events to `POST https://api.app-store-operator.com/v1/events` with the header `X-Write-Key`. **Steps, in order** 1. **Get the write key.** If this document still contains the text `YOUR_WRITE_KEY`, ask the developer for their key (Dashboard → their app → Events → Setup; it starts with `aso_wk_`). Never invent a key or leave the placeholder in code. 2. **Add the tracker.** Copy the file in [§5](#5-reference-implementation) into the **main app target** as `EventTracker.swift`, unchanged. Do not add it to app extensions (widgets, share, notification extensions). 3. **Wire it up** as in [§5.1](#51-wire-it-up): `configure(writeKey:)` once at launch, `EventTracker.flushInBackground()` when the app moves to background, and `app_opened` at launch and on every return from background. 4. **Add `track(...)` calls** for each event in [§6](#6-what-to-track) whose flow exists in this app. Skip events whose flow does not exist. 5. **Add `identify` and `reset`** only if the app has its own sign-in ([§5.2](#52-track-events)). 6. **Finish** with [§9 Done checklist](#9-done-checklist): report every item as done or not applicable, with the file and line that shows it. **Rules** - Do not change the behavior of `EventTracker.swift` (batching, retries, endpoint, queue). If it does not fit the app, report why instead of rewriting it. - Do not add a third-party dependency. - Do not send directly identifying data: names, emails, phone numbers, precise location, IDFA, or text the user typed ([§7](#7-privacy)). If the app is in the App Store Kids Category, stop and tell the developer: this tracker must not be added ([§7.8](#78-apps-for-children)). If the app asks users for consent to analytics, ask the developer whether tracking must wait for it ([§7.5](#75-your-privacy-policy-and-consent)). - Property values are flat: string, number or boolean. No nested objects or arrays ([§4.3](#43-event-object)). The API also accepts `null`, but `EventTracker.Value` has no null case: leave the key out instead. - Use the event names in §6 exactly as written. Ask the developer before naming an event for a flow §6 does not cover. - Call `identify` only with the app's own stable internal user ID, never an email, phone number or name. If you cannot tell which ID that is, ask. - **Check it end to end: the API is live.** Run the §3 curl test with this app's real key and confirm `accepted: 1`. Then run the app in a debug build (a simulator is fine), trigger a few events and send it to background: the Xcode console must show no `[EventTracker]` line for a rejected event or a dropped batch. Ask the developer to confirm the events under Dashboard → Events → Live with the environment filter on **All builds** ([§8](#8-verify-and-troubleshoot)). A `401` means the key is wrong; fix every other failure or report it, do not leave it for later. The write key is public by design (it can only write events for one app), so it may live in source code or `Info.plist`. --- ## 1. Quick facts | | | |---|---| | Base URL | `https://api.app-store-operator.com/v1` | | Auth | Header `X-Write-Key: ` (Dashboard → your app → Events → Setup) | | Send events | `POST /v1/events` (batch of 1–100) | | Link a user | Automatic when an event carries both `anonymous_id` and `user_id`; or `POST /v1/identify` | | Content type | `application/json`, UTF-8 | | Rate limit | 10,000 events per minute per write key (all installs together; 500 on the Free plan) and 300 per minute per install (`anonymous_id`) | | Monthly events | Counted per account across all its apps, reset on the 1st (UTC). Free: 25,000 a month. Past 110% of your plan's limit, new events are refused (`403 quota_exceeded`) until the next month | | Event names | Up to 500 different names per app; an event with a new name past that is rejected (`too_many_event_names`). The catalog lists up to 200 property keys per event name | | Minimum iOS for the reference code | iOS 15 (Swift concurrency, `URLSession` async API) | | Data retention | 13 months | ## 2. How it works 1. Your app creates a random **anonymous ID** on first launch and keeps it. 2. Every action you care about becomes an **event**: a name, a time, optional properties and some device context. 3. Events are queued on the device and sent in **batches**. If the device is offline, they wait and are sent later. 4. When the user signs in to *your* app, you may set a **user ID**. From then on events carry both IDs, and App Store Operator treats the earlier anonymous events and the later signed-in events as one person. 5. In the dashboard you see events arrive live, and you build **funnels** from them: ordered steps such as `onboarding_started → paywall_viewed → purchase_completed`, counted as unique people. ## 3. Get your write key 1. Open the App Store Operator dashboard → **Apps** → your app → **Events** → **Setup**. 2. Copy the write key (it starts with `aso_wk_`). 3. Test it from a terminal (macOS or Linux). The command creates a new `event_id` and the current time on every run, so you can run it again: ```bash curl -sS https://api.app-store-operator.com/v1/events \ -H "Content-Type: application/json" \ -H "X-Write-Key: YOUR_WRITE_KEY" \ -d '{ "events": [{ "event_id": "'"$(uuidgen)"'", "name": "integration_test", "anonymous_id": "curl-test", "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'", "properties": { "source": "curl" } }] }' ``` Expected response: `accepted` is `1` and `rejected` is empty. The event appears under **Events → Live** within a few seconds. Why fresh values: a repeated `event_id` is stored only once, so a second run with the same ID shows nothing new in Live, and a time more than 7 days old is replaced by the time we received it. ### 3.1 Rotating the key Rotate the key only if it is being abused, for example if someone is sending fake events with it. The key is public, so being visible in your app is not a reason to rotate. 1. Setup → **Rotate key**. Any member of the workspace can do this, and it is recorded. 2. Put the new key in your app and ship an update. 3. The old key keeps working for **30 days**, so your users have time to update. After that, builds that still use the old key get `401` and the reference code drops their events. People on those builds are not counted until they update. 4. If the old key is still being abused, Setup → **Revoke old key now** ends its 30 days at once. From then on, builds that use the old key are not counted. Any member of the workspace can do this, and it is recorded. 5. While an old key is in its 30 days, **Rotate key** is disabled. To rotate again, revoke the old key first or wait until its 30 days end. ## 4. API reference ### 4.1 `POST /v1/events` Send 1 to 100 events. **Headers** | Header | Required | Value | |---|---|---| | `Content-Type` | yes | `application/json` | | `X-Write-Key` | yes | your app's write key | **Body** ```json { "events": [ , ... ] } ``` The whole body must be at most **1 MB**. Unknown fields, in the body or in an event, are ignored. ### 4.2 Response `200 OK` whenever the batch itself is valid, even if some events were rejected: ```json { "accepted": 2, "rejected": [ { "index": 2, "event_id": "…", "code": "invalid_name", "message": "Event name must match ^[A-Za-z0-9_.:-]{1,64}$" } ], "clamped": [ { "index": 0, "event_id": "…" } ] } ``` - `accepted`: events stored, including duplicates that were already stored (see `event_id`). - `rejected`: events that were not stored and must not be retried unchanged. - `clamped`: events whose `occurred_at` was out of range and was replaced by the server's receive time. They are stored and counted in `accepted`. All three fields are always present; `rejected` and `clamped` may be empty. ### 4.3 Event object | Field | Type | Required | Rules | |---|---|---|---| | `event_id` | string (UUID) | yes | Unique per event. Generate it when the event is created, not when it is sent, so a retried batch is not counted twice. | | `name` | string | yes | `^[A-Za-z0-9_.:-]{1,64}$`. A `$` followed by 1–63 of those characters (e.g. `$session_start`) is reserved for App Store Operator and rejected with `reserved_name`; any other invalid name is `invalid_name`. Use `snake_case` `object_action`, e.g. `paywall_viewed`. | | `anonymous_id` | string | yes | 1–128 chars. Stable per install. | | `user_id` | string or null | no | 1–128 chars. Your own stable user ID. Never an email or phone number. | | `occurred_at` | string | yes | ISO 8601 with timezone, e.g. `2026-10-23T12:00:00.123Z`. Accepted from 7 days in the past to 5 minutes in the future. | | `properties` | object | no | Flat object, at most 50 keys. Key: 1–64 chars. Value: string (≤ 1024 chars), number, boolean or `null`. **No nested objects or arrays.** | | `context` | object | no | See below. Recommended: the dashboard filters and breaks funnels down by these fields. | **`context`** | Field | Example | Notes | |---|---|---| | `app_version` | `"2.4.0"` | `CFBundleShortVersionString` | | `build` | `"412"` | `CFBundleVersion` | | `os_version` | `"18.1"` | | | `device_model` | `"iPhone16,2"` | Hardware identifier, not a marketing name | | `locale` | `"en_US"` | The device locale, `language_REGION` | | `environment` | `"app_store"` | `"debug"`, `"testflight"` or `"app_store"`. The dashboard shows only `app_store` events (and events without it) unless you choose otherwise | Every `context` value is a string of at most 64 characters. A value that breaks this, and any key not in this table, is dropped without rejecting the event. The server adds `country` from the request's network location. The IP address itself is never stored. A serialized event must be at most **8 KB**. **Full example** ```json { "event_id": "0b6f6a3e-3c3e-4d8a-8f6e-1f9b8a2c7d10", "name": "purchase_completed", "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723", "occurred_at": "2026-10-23T12:04:31.512Z", "properties": { "product_id": "pro_yearly", "price": 39.99, "currency": "USD", "trial": true }, "context": { "app_version": "2.4.0", "build": "412", "os_version": "18.1", "device_model": "iPhone16,2", "locale": "en_US", "environment": "app_store" } } ``` ### 4.4 `POST /v1/identify` (optional) Links an anonymous ID to a user ID without sending an event. You rarely need it: any event that carries both IDs does the same. Use it when the link is known on your server. ```json { "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723" } ``` Response: `204 No Content`. The first link for an anonymous ID wins; later different user IDs for the same anonymous ID are ignored. Errors use the same body and codes as §4.5: `400 invalid_body` when the body is not JSON or either ID is missing or not a 1–128 char string, `401 invalid_write_key`, `413 payload_too_large`, and `429 rate_limited`, because each call counts as one event against the write key's rate limit. ### 4.5 Errors | Status | `code` | Meaning | Client action | |---|---|---|---| | 400 | `invalid_body` | Body is not valid JSON or not `{ "events": [...] }`, or 0 / more than 100 events | Fix the code; do not retry | | 401 | `invalid_write_key` | Missing, unknown or revoked key. `/v1/events` also answers it when the app was removed from App Store Operator, its App Store Connect connection was deleted, or the workspace's account was disabled | Do not retry; drop the batch and check the key | | 413 | `payload_too_large` | Body over 1 MB | Send smaller batches | | 403 | `quota_exceeded` | The account has used 110% of its monthly event limit. Nothing in the request was stored | Do not retry; drop the batch. Sending resumes on the 1st (UTC) or after an upgrade | | 429 | `rate_limited` | Over 10,000 events per minute for the key (500 on the Free plan), or 300 for one `anonymous_id`. The key's limit counts every event sent, rejected ones included, and each `/v1/identify` call as one; the `anonymous_id` limit counts accepted events. Nothing in the request was stored | Keep the batch; retry after `Retry-After` seconds | | 5xx | `server_error` | Our fault | Keep the batch; retry with backoff | Error body: `{ "code": "invalid_write_key", "message": "…" }`. **Per-event rejection codes** (inside a `200` response): | Code | When | |---|---| | `invalid_event` | The item in `events` is not a JSON object | | `invalid_name` | `name` missing, or not matching `^[A-Za-z0-9_.:-]{1,64}$` | | `reserved_name` | `name` is `$` followed by 1–63 characters from `[A-Za-z0-9_.:-]` | | `invalid_id` | `event_id` missing or not a UUID; `anonymous_id` missing or not a 1–128 char string; `user_id` present but not a 1–128 char string or `null` | | `invalid_timestamp` | `occurred_at` missing, unparseable, or without a timezone. (Out of range is not a rejection: see `clamped`) | | `invalid_properties` | `properties` not a flat object; a key outside 1–64 chars; a nested object or array; a string over 1,024 chars | | `too_many_properties` | More than 50 properties | | `event_too_large` | The serialized event is over 8 KB | | `too_many_event_names` | The app already has 500 different event names and this one is new. Reuse a name and put the detail in a property | **Retry rule in one line:** retry on network failure, `429` and `5xx`, keeping the same `event_id`s; drop on every other status. ## 5. Reference implementation One file, no dependencies, iOS 15+, builds in Swift 5 and Swift 6 language modes. Add it to the **main app target** as `EventTracker.swift` and use it unchanged. What it does: - Creates a random anonymous ID with the first tracked event and keeps it (in `UserDefaults`). `currentAnonymousId` returns it. - Has an on/off switch, `setEnabled(_:)`, remembered across launches and on by default. Turning it off deletes the IDs and every unsent event, and `track` does nothing until it is turned on again. - Saves every event to a queue on disk, so events survive the app being closed. - Sends the queue in batches of up to 100: every 30 seconds, when 20 or more events are waiting, and when you call `flush()`. - Offline or `5xx`: keeps the queue and waits before trying again: 30 seconds, then 60, 120… up to 10 minutes. `429`: keeps the queue and waits as long as the server's `Retry-After` says. Any other response: removes the batch from the queue. - Keeps at most 1,000 events; past that, the oldest are dropped. - Debug builds only: prints rejected and clamped events, and dropped batches, to the Xcode console as `[EventTracker] …`. Release builds print nothing. - Marks each event as `debug`, `testflight` or `app_store` (StoreKit, iOS 16+), so test runs stay out of your funnels. - `flushInBackground()` asks iOS for extra time, so the last events are sent even as the app is suspended. `track` works before `configure`; events wait in the queue until a key is set. **One app, one key.** Each app in the dashboard has its own write key. Use each key only in that app's binary. **Not in app extensions.** Extensions keep their own storage, so each would get its own anonymous ID and count as a separate person. Track from the main app only. ```swift import Foundation import StoreKit #if canImport(UIKit) import UIKit #endif /// Sends events to App Store Operator. Docs: https://app-store-operator.com/docs/events/ios public actor EventTracker { public static let shared = EventTracker() public enum Value: Codable, Sendable, ExpressibleByStringLiteral, ExpressibleByIntegerLiteral, ExpressibleByFloatLiteral, ExpressibleByBooleanLiteral { case string(String), int(Int), double(Double), bool(Bool) public init(stringLiteral value: String) { self = .string(value) } public init(integerLiteral value: Int) { self = .int(value) } public init(floatLiteral value: Double) { self = .double(value) } public init(booleanLiteral value: Bool) { self = .bool(value) } public init(from decoder: Decoder) throws { let c = try decoder.singleValueContainer() if let v = try? c.decode(Bool.self) { self = .bool(v) } else if let v = try? c.decode(Int.self) { self = .int(v) } else if let v = try? c.decode(Double.self) { self = .double(v) } else { self = .string(try c.decode(String.self)) } } public func encode(to encoder: Encoder) throws { var c = encoder.singleValueContainer() switch self { case .string(let v): try c.encode(v) case .int(let v): try c.encode(v) case .double(let v): try c.encode(v) case .bool(let v): try c.encode(v) } } } private struct Context: Codable, Sendable { let appVersion, build, osVersion, deviceModel, locale: String var environment: String? enum CodingKeys: String, CodingKey { case appVersion = "app_version", build, osVersion = "os_version", deviceModel = "device_model", locale, environment } } private struct Event: Codable, Sendable { let eventId, name, anonymousId: String let userId: String? let occurredAt: String let properties: [String: Value] var context: Context enum CodingKeys: String, CodingKey { case eventId = "event_id", name, anonymousId = "anonymous_id", userId = "user_id", occurredAt = "occurred_at", properties, context } } private struct Batch: Encodable { let events: [Event] } private let endpoint = URL(string: "https://api.app-store-operator.com/v1/events")! private let maxBatch = 100 private let maxQueue = 1_000 private let flushAt = 20 private let anonymousIdKey = "aso.events.anonymousId" private let userIdKey = "aso.events.userId" private let disabledKey = "aso.events.disabled" private let storeURL: URL private let context: Context private let timestamp: ISO8601DateFormatter private var writeKey: String? private var anonymousId: String? private var isEnabled: Bool private var userId: String? private var queue: [Event] private var isFlushing = false private var timer: Task? private var retryAt: Date? private var backoff: TimeInterval = 0 private var environment: String? private init() { let defaults = UserDefaults.standard isEnabled = !defaults.bool(forKey: disabledKey) anonymousId = defaults.string(forKey: anonymousIdKey) // created on the first tracked event userId = defaults.string(forKey: userIdKey) let dir = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true) storeURL = dir.appendingPathComponent("aso-events-queue.json") queue = (try? JSONDecoder().decode([Event].self, from: Data(contentsOf: storeURL))) ?? [] let info = Bundle.main.infoDictionary ?? [:] let os = ProcessInfo.processInfo.operatingSystemVersion var system = utsname() uname(&system) let model = withUnsafeBytes(of: &system.machine) { raw in String(decoding: raw.prefix { $0 != 0 }, as: UTF8.self) } context = Context( appVersion: info["CFBundleShortVersionString"] as? String ?? "", build: info["CFBundleVersion"] as? String ?? "", osVersion: "\(os.majorVersion).\(os.minorVersion).\(os.patchVersion)", deviceModel: model, locale: Locale.current.identifier, environment: nil // filled in when sent, see resolveEnvironment() ) timestamp = ISO8601DateFormatter() timestamp.formatOptions = [.withInternetDateTime, .withFractionalSeconds] } /// Call once at launch. public func configure(writeKey: String) { self.writeKey = writeKey guard timer == nil else { return } timer = Task { while !Task.isCancelled { try? await Task.sleep(nanoseconds: 30_000_000_000) await self.flush() } } } /// The ID of this install, or nil before the first tracked event and while tracking is off. /// Show it on a support screen so a user can ask for their data to be deleted. public var currentAnonymousId: String? { anonymousId } /// Turns tracking on or off, and remembers the choice across launches. Tracking is on by default. /// Turning it off deletes this install's IDs and every event not yet sent; `track` then does nothing. /// If your app needs the user's consent first, call `setEnabled(false)` at launch until they agree. public func setEnabled(_ enabled: Bool) { isEnabled = enabled let defaults = UserDefaults.standard defaults.set(!enabled, forKey: disabledKey) guard !enabled else { return } anonymousId = nil userId = nil queue.removeAll() defaults.removeObject(forKey: anonymousIdKey) defaults.removeObject(forKey: userIdKey) try? FileManager.default.removeItem(at: storeURL) } /// Records an event. Cheap; never blocks on the network. Does nothing while tracking is off. public func track(_ name: String, _ properties: [String: Value] = [:]) { guard isEnabled else { return } let anonymousId = anonymousId ?? newAnonymousId() queue.append(Event( eventId: UUID().uuidString, name: name, anonymousId: anonymousId, userId: userId, occurredAt: timestamp.string(from: Date()), properties: properties, context: context )) if queue.count > maxQueue { queue.removeFirst(queue.count - maxQueue) } persist() if queue.count >= flushAt { Task { await self.flush() } } } /// Call after the user signs in to your app. Use your own stable user ID, never an email. public func identify(userId: String) { guard isEnabled else { return } self.userId = userId UserDefaults.standard.set(userId, forKey: userIdKey) } /// Call on sign-out: later events belong to a new anonymous person. public func reset() { userId = nil anonymousId = nil UserDefaults.standard.removeObject(forKey: userIdKey) UserDefaults.standard.removeObject(forKey: anonymousIdKey) } private func newAnonymousId() -> String { let id = UUID().uuidString anonymousId = id UserDefaults.standard.set(id, forKey: anonymousIdKey) return id } /// Sends queued events. Does nothing while waiting out a retry delay. public func flush() async { guard isEnabled, !isFlushing, let writeKey, !queue.isEmpty else { return } if let retryAt, retryAt > Date() { return } isFlushing = true defer { isFlushing = false } let environment = await resolveEnvironment() while !queue.isEmpty { var batch = Array(queue.prefix(maxBatch)) for i in batch.indices where batch[i].context.environment == nil { batch[i].context.environment = environment } var request = URLRequest(url: endpoint) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue(writeKey, forHTTPHeaderField: "X-Write-Key") request.httpBody = try? JSONEncoder().encode(Batch(events: batch)) guard let (data, response) = try? await URLSession.shared.data(for: request) else { delayRetry(nil) // offline: keep the queue return } guard isEnabled else { return } // turned off while sending: the queue is already gone let http = response as? HTTPURLResponse let status = http?.statusCode ?? 0 if status == 429 || status >= 500 { let retryAfter = http?.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init) delayRetry(status == 429 ? retryAfter : nil) // keep the queue return } retryAt = nil backoff = 0 #if DEBUG report(status: status, body: data) #endif // 2xx: stored. Other 4xx: retrying the same batch cannot succeed. let sent = Set(batch.map(\.eventId)) queue.removeAll { sent.contains($0.eventId) } persist() } } /// Waits `seconds` when the server says so, otherwise 30 s, 60 s, 120 s… up to 10 minutes. private func delayRetry(_ seconds: TimeInterval?) { backoff = min(max(backoff * 2, 30), 600) retryAt = Date().addingTimeInterval(seconds ?? backoff) } private func persist() { try? JSONEncoder().encode(queue).write(to: storeURL, options: .atomic) } #if DEBUG /// Debug builds only: prints dropped batches and rejected or clamped events to the Xcode console. private func report(status: Int, body: Data) { let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:] guard (200..<300).contains(status) else { print("[EventTracker] HTTP \(status), batch dropped: \(json)") return } for key in ["rejected", "clamped"] { if let items = json[key] as? [Any], !items.isEmpty { print("[EventTracker] \(key): \(items)") } } } #endif /// "debug", "testflight" or "app_store". Release builds ask StoreKit (iOS 16+); on iOS 15 it stays unknown. private func resolveEnvironment() async -> String? { if let environment { return environment } #if DEBUG environment = "debug" #else if #available(iOS 16.0, macOS 13.0, *), let result = try? await AppTransaction.shared { switch result.unsafePayloadValue.environment { case .production: environment = "app_store" case .sandbox: environment = "testflight" case .xcode: environment = "debug" default: break } } #endif return environment } } #if canImport(UIKit) extension EventTracker { /// Sends the queue when the app moves to background, asking iOS for time to finish. @MainActor public static func flushInBackground() { let task = BackgroundTask() Task { await shared.flush() task.end() } } } @MainActor private final class BackgroundTask { private var id = UIBackgroundTaskIdentifier.invalid init() { id = UIApplication.shared.beginBackgroundTask { [weak self] in self?.end() } } func end() { guard id != .invalid else { return } UIApplication.shared.endBackgroundTask(id) id = .invalid } } #endif ``` ### 5.1 Wire it up ```swift import SwiftUI @main struct MyApp: App { @Environment(\.scenePhase) private var scenePhase @State private var wasInBackground = false init() { Task { await EventTracker.shared.configure(writeKey: "YOUR_WRITE_KEY") await EventTracker.shared.track("app_opened", ["source": "cold"]) } } var body: some Scene { WindowGroup { ContentView() } .onChange(of: scenePhase) { _, phase in // iOS 17+; on iOS 15–16 use `{ phase in }` switch phase { case .background: wasInBackground = true EventTracker.flushInBackground() case .active where wasInBackground: wasInBackground = false Task { await EventTracker.shared.track("app_opened", ["source": "warm"]) } default: break } } } } ``` **UIKit:** in `application(_:didFinishLaunchingWithOptions:)`, call `configure` and track `app_opened` with `source: "cold"` inside `Task { … }` as above. In `sceneDidEnterBackground(_:)` (or `applicationDidEnterBackground(_:)` without scenes), call `EventTracker.flushInBackground()`. In `sceneWillEnterForeground(_:)` (or `applicationWillEnterForeground(_:)`), track `app_opened` with `source: "warm"`. `app_opened` is sent on returning from background only, not on every `.active`: system alerts, Control Center and Face ID also make the app inactive and active again. ### 5.2 Track events ```swift await EventTracker.shared.track("paywall_viewed", ["placement": "onboarding"]) // From synchronous code (button actions, delegates): Task { await EventTracker.shared.track("onboarding_completed", ["duration_s": 42]) } // After sign-in / sign-out in your app: await EventTracker.shared.identify(userId: user.id) await EventTracker.shared.reset() // Consent or an in-app "Share analytics" toggle: call it at launch, before configure and the first track, // with the user's current choice, and again whenever the choice changes. await EventTracker.shared.setEnabled(userAllowsAnalytics) // Support screen: show this so a user can ask for their data to be deleted (nil if nothing was tracked yet). let installId = await EventTracker.shared.currentAnonymousId ``` If tracking waits for consent, call `setEnabled` before the launch `app_opened` in [§5.1](#51-wire-it-up); while tracking is off, that call does nothing and no ID is created. Literals (`"onboarding"`, `42`, `39.99`, `true`) convert to property values on their own. For variables, wrap them: `.string(name)`, `.int(count)`, `.double(amount)`, `.bool(flag)`. **Purchases with StoreKit 2.** Track purchases in the purchase flow, where the user taps buy. Do not track them in `Transaction.updates`, which also delivers renewals and purchases from other devices. ```swift import StoreKit func buy(_ product: Product, startsTrial: Bool) async { let base: [String: EventTracker.Value] = ["product_id": .string(product.id)] await EventTracker.shared.track("purchase_started", base) do { switch try await product.purchase() { case .success(.verified): await EventTracker.shared.track("purchase_completed", base.merging([ "price": .double(NSDecimalNumber(decimal: product.price).doubleValue), "currency": .string(product.priceFormatStyle.currencyCode), "trial": .bool(startsTrial), ]) { $1 }) if startsTrial { await EventTracker.shared.track("trial_started", base) } case .userCancelled: await EventTracker.shared.track("purchase_failed", base.merging(["reason": "cancelled"]) { $1 }) case .success(.unverified): await EventTracker.shared.track("purchase_failed", base.merging(["reason": "failed"]) { $1 }) case .pending: break // Ask to Buy or extra approval: not completed yet, track nothing @unknown default: break } } catch { await EventTracker.shared.track("purchase_failed", base.merging(["reason": "failed"]) { $1 }) } } ``` `startsTrial` is whatever your paywall already knows: true when this purchase starts a free trial. If the app buys through RevenueCat or another library, put the same calls around its purchase method. ## 6. What to track Funnels are only as good as the events behind them. Start with the steps below and add more as questions come up. **Naming rules** - `snake_case`, `object_action`, past tense: `paywall_viewed`, `purchase_completed`. - One name per action. Put variations in properties (`paywall_viewed` with `placement: "settings"`), not in the name (`settings_paywall_viewed`). - Never put IDs, dates or user data in the name. - Where you want to split a funnel by a property, give it a short list of fixed values (`plan: "yearly"`), not free text. The dashboard shows the top 10 values and groups the rest as "Other". - Names and property values are case-sensitive: `Paywall_Viewed` and `paywall_viewed` are two different events. **Recommended starter set** Track the events whose flow exists in your app; skip the rest. Properties marked *optional* can be left out. | Event | When | Properties | |---|---|---| | `app_opened` | App launch and every return from background (the [§5.1](#51-wire-it-up) wiring sends it) | `source` (`"cold"` launch, `"warm"` return) | | `onboarding_started` | First onboarding screen shown | | | `onboarding_completed` | Last onboarding step done | `duration_s` *optional* (number) | | `signup_completed` | Account created in your app | `method` (`"apple"`, `"google"`, `"email"`) | | `paywall_viewed` | Paywall shown | `placement` (where it was shown: `"onboarding"`, `"settings"`, `"feature_gate"`), `paywall_id` *optional* | | `purchase_started` | User taps buy | `product_id` | | `purchase_completed` | Purchase succeeded and verified, in the purchase flow ([§5.2](#52-track-events)). Includes purchases that start a free trial | `product_id`, `price` (number), `currency`, `trial` (boolean) | | `purchase_failed` | User cancelled, or the purchase failed. Ask to Buy (pending) is neither: track nothing | `product_id`, `reason` (`"cancelled"`, `"failed"`) | | `trial_started` | Sent **in addition to** `purchase_completed` when that purchase starts a free trial | `product_id` | | `purchase_restored` | Restore purchases found an active subscription | `product_id` *optional* | | Your core action | The one thing your app is for. Name it for that action: `scan_completed`, `workout_finished`, `photo_exported` | what describes it | **What events from the app cannot show.** Renewals, free trials that turn into paid subscriptions, cancellations and refunds happen at Apple, usually while your app is closed. The app never sees them, so they are not in these events, and funnels here end at the purchase or the trial start. **Example funnels these enable** | Funnel | Steps | Window | What it answers | |---|---|---|---| | First session | `onboarding_started → onboarding_completed → paywall_viewed (placement = onboarding) → purchase_completed` | 1 day | How many new users reach the paywall and buy | | Paywall conversion | `paywall_viewed → purchase_started → purchase_completed`, broken down by `placement` | 1 hour | Which paywall placement converts best, and whether people drop at the price or at Apple's sheet | | Activation | `onboarding_completed → scan_completed` (your core action) | 1 day | How many new users get to the point of the app | ## 7. Privacy This section is guidance, not legal advice. You know what your app sends and where your users are, so the final decisions are yours, ideally with your own counsel. Privacy contact for everything in this section: `privacy@app-store-operator.com`. ### 7.1 What App Store Operator receives - Event names and their properties. - `anonymous_id`: a random UUID the reference code creates with the first event tracked while tracking is on, and keeps for that install until tracking is turned off or `reset` is called. It is not the IDFA or any other identifier shared with other apps. - `user_id`, only if you call `identify`. - The device context in [§4.3](#43-event-object): app version, build, OS version, device model, locale and build environment. - The country, derived from the request's network location (see [§7.3](#73-ip-address-and-country)). **Never send** names, emails, phone numbers, precise location, the IDFA, or free text typed by the user, whether in event names, properties or `user_id`. `user_id` must be your app's own internal ID (for example a database key), not an email, a phone number, or an ID another company assigned. ### 7.2 Roles and service providers - **Roles.** For the events your app sends, you are the data controller (under KVKK, *veri sorumlusu*): you decide what is collected and why. Nefarius, which runs App Store Operator, processes the events on your behalf as your data processor (under KVKK, *veri işleyen*), to store them and show them to you in the dashboard. - **What we do not do.** We do not sell event data, use it for advertising, or share it with other customers. - **Service providers (subprocessors).** Like any hosted service, we rely on providers that handle event data only on our behalf: - **Cloudflare**: network delivery and security. Every request from your app passes through it. - **Our server hosting provider**: runs the servers and the database where events are stored. - **Locations.** Cloudflare operates worldwide, so a request may be handled outside your users' country. - **Data processing agreement (DPA).** If you need a DPA (for example under GDPR Article 28), the current list of service providers with their locations, or details of the safeguards for international transfers, write to the privacy contact above. ### 7.3 IP address and country Your app's requests reach us through Cloudflare, which needs the IP address to deliver them and looks up the country from it. App Store Operator keeps only the country (no city or region) and never stores or logs the IP address. ### 7.4 Retention and deletion requests - Events are kept for 13 months, then deleted automatically. - Deleting one person's events from the dashboard is not available yet. Until it is, when a user asks you to delete their data (for example under GDPR Article 17 or KVKK Article 11), email the privacy contact above from the address of a member of your App Store Operator workspace, with: - the app's name as shown in the dashboard; - the person's `user_id`, and/or their `anonymous_id`. A `user_id` also covers every `anonymous_id` linked to it. For users without an account, your app can show the `anonymous_id` from `EventTracker.shared.currentAnonymousId`, for example on a support screen ([§5.2](#52-track-events)). Read it before calling `setEnabled(false)` or `reset()`: both delete it from the device, and without it we cannot find that install's events. - We delete every event with those IDs and confirm by email. Send requests promptly: you have your own deadline to answer the user (generally one month under GDPR, 30 days under KVKK). - Requests from anyone who is not a member of the workspace are not acted on; we refer the person to you. ### 7.5 Your privacy policy and consent - **Privacy policy.** Your app's privacy policy should say that you collect usage analytics, what data that includes (§7.1), that a service provider (App Store Operator, run by Nefarius) processes it for you, and that it is kept for 13 months. - **Legal basis and consent.** You choose the legal basis for analytics and whether you need your users' consent first. In the EU and UK, storing or reading an identifier on the device for analytics often requires consent; under KVKK you must at least inform users. If you need consent, call `EventTracker.shared.setEnabled(false)` at launch, before anything else, until the user agrees, then `setEnabled(true)` ([§5.2](#52-track-events)). While tracking is off, no ID or event is stored on the device (only the off setting itself) and nothing is sent. The tracker creates its `anonymous_id` only with the first event tracked while it is on. If the user later withdraws consent, `setEnabled(false)` stops tracking and deletes the IDs and unsent events on the device. It does not delete events already sent: if consent was your only legal basis, or the user asks for deletion, request it through [§7.4](#74-retention-and-deletion-requests), reading `currentAnonymousId` first. ### 7.6 App Tracking Transparency App Store Operator does not combine your events with data from other companies' apps, websites or offline sources for advertising or ad measurement, does not share them with data brokers, and does not use the device context to fingerprint devices. On its own, therefore, the integration is not tracking as Apple defines it and does not require the App Tracking Transparency (ATT) prompt. ATT is decided for your app as a whole, not per integration. If your app, or another SDK in it, links these events or your `user_id` with other companies' data for advertising or ad measurement, or shares them with a data broker, that is tracking: you need the user's ATT permission first, and your privacy label must say the data is used to track. See Apple's [User Privacy and Data Use](https://developer.apple.com/app-store/user-privacy-and-data-use/). ### 7.7 App Store privacy label and privacy manifest You answer Apple's privacy questions for the whole app, and Apple asks you to include data collected by third-party code you add, which includes this code. For the data App Store Operator receives, the typical answers are: | Apple data type | Declare when | Purpose | |---|---|---| | Usage Data → Product Interaction | Always | Analytics | | Identifiers → Device ID | Always: `anonymous_id` is a persistent per-install identifier | Analytics | | Location → Coarse Location | Always: the country is derived from the user's network location. It is coarser than Apple's examples, but declaring it is the safer answer | Analytics | | Purchases → Purchase History | If you track the purchase events in §6 | Analytics | | Identifiers → User ID | If you call `identify` or send `user_id` | Analytics | - **Linked to You.** If you send `user_id`, declare every row above as *Linked to You*: the events are joined to an account ID in your system. If you never send `user_id` and do not connect the events to an account or other identifying data anywhere else, the data is tied only to a random install ID and you may be able to answer *Not Linked to You*. When in doubt, answer *Linked to You*. - **Tracking.** *Not used to track you*, unless your app tracks as described in §7.6. - **Privacy manifest.** The reference code reads and writes `UserDefaults`, an API Apple requires a reason for. Your app's `PrivacyInfo.xcprivacy` must list `NSPrivacyAccessedAPICategoryUserDefaults` with reason `CA92.1` (many apps already do), and its collected data types should match your label. Apple's definitions: [App privacy details on the App Store](https://developer.apple.com/app-store/app-privacy-details/) and [Privacy manifest files](https://developer.apple.com/documentation/bundleresources/privacy-manifest-files). ### 7.8 Apps for children Apple's [App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) (1.3 and 5.1.4) do not allow third-party analytics in Kids Category apps, except in limited cases where the service collects no identifiable information about children, including device information. App Store Operator receives a persistent install ID, the device model and the country, so **do not add it to an app in the Kids Category**. For other apps aimed at children, check the rules that apply to you (for example COPPA in the US, or GDPR rules on children's consent) with your counsel before integrating. ## 8. Verify and troubleshoot 1. Run the app, trigger a few events, then send it to background (that sends the queue). 2. Dashboard → your app → **Events → Live**: your events appear within seconds. 3. **Events → Catalog** lists each event name with its property keys. Check the names and keys are the ones you meant. **Test builds.** Each app has one write key, used by test builds and App Store builds alike. The reference code marks every event as `debug`, `testflight` or `app_store`. By default the dashboard shows `app_store` events and events with no environment; to see your test runs, switch the environment filter to **All builds**. On iOS 15, release builds cannot tell TestFlight from the App Store, so their events count as App Store events. The curl test sends no environment, so it shows in the default view; find it by its `anonymous_id`, `curl-test`. | Symptom | Likely cause | |---|---| | Nothing in Live | Wrong key (`401`); `configure` never called; or fewer than 20 events queued and the app has not gone to background yet (wait 30 s) | | `401 invalid_write_key` | Key typo; the key was rotated more than 30 days ago; the old key was revoked ([§3.1](#31-rotating-the-key)); or the app or its App Store Connect connection was removed from App Store Operator | | Event missing, others present | Rejected. In a Debug build the Xcode console shows `[EventTracker] rejected: …` with the code ([§4.5](#45-errors)) | | Nothing in Live from a test build | The default view shows App Store events and events with no environment: switch the environment filter to **All builds** | | Events arrive late in bursts | Over a rate limit (`429`), or the server or network was down; the reference code keeps them and sends them later | | Wrong times | Device clock far off: times more than 7 days in the past or 5 minutes in the future are replaced by the time we received the event | | Same person counted twice in a funnel | `reset()` called when it should not be, or `identify` called with different IDs for one user | | Funnel step is zero | Step's event name or property filter does not match exactly (names and values are case-sensitive) | ## 9. Done checklist The integration is done when every line is true. When you report, give the file and line for each code item; mark an item *not applicable* with the reason. The API is live, so nothing is left pending: run the end-to-end check too. - [ ] `EventTracker.swift` is in the main app target only (no extensions), unchanged from §5, and the app builds. - [ ] `configure(writeKey:)` runs once at launch with this app's real key; the text `YOUR_WRITE_KEY` appears nowhere in the project. - [ ] `EventTracker.flushInBackground()` runs when the app moves to background. - [ ] `app_opened` is tracked at launch (`source: "cold"`) and on every return from background (`source: "warm"`). - [ ] Every §6 event whose flow exists in this app is tracked, with the listed properties. Report each one as `event → file:line`, and list the §6 events you skipped and why. - [ ] Purchase events are tracked in the purchase flow, not in `Transaction.updates`. - [ ] Every event name matches `^[A-Za-z0-9_.:-]{1,64}$` and follows the §6 naming rules. - [ ] No `track` call sends a name, email, phone number, precise location, IDFA or text the user typed. - [ ] If the app has accounts: `identify` is called after sign-in with the app's own user ID, and `reset` after sign-out. Otherwise neither is called. - [ ] *End to end:* the §3 curl test with this app's key returns `accepted: 1`; a debug run of the app shows no rejected events or dropped batches in the Xcode console; and its events appear in Dashboard → Events → Live (**All builds**). - [ ] *Developer:* the list of events and properties above was handed to the developer to check, against §7, the App Store privacy label, the `UserDefaults` entry in `PrivacyInfo.xcprivacy`, the app's privacy policy and any consent requirement. The app is not in the Kids Category. --- # App Store Operator Events: integration guide for Flutter > **Who this is for:** Flutter developers adding event tracking to the iOS build of a Flutter app, and the AI coding agents they hand this document to. It is self-contained: an agent can complete the integration from this file alone. App Store Operator covers iOS apps for now: the tracker sends nothing from Android, web or desktop builds (Android support is planned). --- ## For AI coding agents: read this first You are adding event tracking to a Flutter app so its owner can build funnels in App Store Operator. The app's iOS build will send events to `POST https://api.app-store-operator.com/v1/events` with the header `X-Write-Key`. On every other platform the tracker does nothing. **Steps, in order** 1. **Get the write key.** If this document still contains the text `YOUR_WRITE_KEY`, ask the developer for their key (Dashboard → their app → Events → Setup; it starts with `aso_wk_`). Never invent a key or leave the placeholder in code. 2. **Add the tracker.** Add the four packages listed in [§5](#5-reference-implementation) with `flutter pub add`, then copy the file in §5 into the app as `lib/event_tracker.dart`, unchanged. If the iOS app has native extensions (widgets, share, notification extensions), do not track from them. 3. **Wire it up** as in [§5.1](#51-wire-it-up): in `main()`, after `WidgetsFlutterBinding.ensureInitialized()`, call `configure(writeKey: ...)` once and track `app_opened`; then call `flush()` when the app moves to background, and track `app_opened` again on every return from background. 4. **Add `track(...)` calls** for each event in [§6](#6-what-to-track) whose flow exists in this app. Skip events whose flow does not exist. 5. **Add `identify` and `reset`** only if the app has its own sign-in ([§5.2](#52-track-events)). 6. **Finish** with [§9 Done checklist](#9-done-checklist): report every item as done or not applicable, with the file and line that shows it. **Rules** - Do not change the behavior of `lib/event_tracker.dart` (batching, retries, endpoint, queue, the iOS-only check). If it does not fit the app, report why instead of rewriting it. - Do not add any third-party dependency other than the four packages in §5 (`path_provider`, `shared_preferences`, `package_info_plus`, `device_info_plus`). If the app already uses one of them, keep it; `flutter pub add` reports a version conflict if there is one. - Do not make the tracker run on Android, web or desktop. App Store Operator counts iOS installs only for now. - Do not send directly identifying data: names, emails, phone numbers, precise location, IDFA, or text the user typed ([§7](#7-privacy)). If the app is in the App Store Kids Category, stop and tell the developer: this tracker must not be added ([§7.8](#78-apps-for-children)). If the app asks users for consent to analytics, ask the developer whether tracking must wait for it ([§7.5](#75-your-privacy-policy-and-consent)). - Property values are flat: `String`, `int`, `double`, `bool` or `null`. No nested maps or lists ([§4.3](#43-event-object)); the tracker drops any other value. - Use the event names in §6 exactly as written. Ask the developer before naming an event for a flow §6 does not cover. - Call `identify` only with the app's own stable internal user ID, never an email, phone number or name. If you cannot tell which ID that is, ask. - **Check it end to end: the API is live.** Run the §3 curl test with this app's real key and confirm `accepted: 1`. Then run the app's iOS build in a debug build (a simulator is fine), trigger a few events and send it to background: the Flutter console must show no `[EventTracker]` line for a rejected event or a dropped batch. Ask the developer to confirm the events under Dashboard → Events → Live with the environment filter on **All builds** ([§8](#8-verify-and-troubleshoot)). A `401` means the key is wrong; fix every other failure or report it, do not leave it for later. The write key is public by design (it can only write events for one app), so it may live in source code. --- ## 1. Quick facts | | | |---|---| | Base URL | `https://api.app-store-operator.com/v1` | | Auth | Header `X-Write-Key: ` (Dashboard → your app → Events → Setup) | | Send events | `POST /v1/events` (batch of 1–100) | | Link a user | Automatic when an event carries both `anonymous_id` and `user_id`; or `POST /v1/identify` | | Content type | `application/json`, UTF-8 | | Rate limit | 10,000 events per minute per write key (all installs together; 500 on the Free plan) and 300 per minute per install (`anonymous_id`) | | Monthly events | Counted per account across all its apps, reset on the 1st (UTC). Free: 25,000 a month. Past 110% of your plan's limit, new events are refused (`403 quota_exceeded`) until the next month | | Event names | Up to 500 different names per app; an event with a new name past that is rejected (`too_many_event_names`). The catalog lists up to 200 property keys per event name | | Minimum versions for the reference code | Dart 3.11 and Flutter 3.41 (required by the package versions in §5); iOS 13. Sends events from iOS only | | Data retention | 13 months | ## 2. How it works 1. Your app creates a random **anonymous ID** on first launch and keeps it. 2. Every action you care about becomes an **event**: a name, a time, optional properties and some device context. 3. Events are queued on the device and sent in **batches**. If the device is offline, they wait and are sent later. 4. When the user signs in to *your* app, you may set a **user ID**. From then on events carry both IDs, and App Store Operator treats the earlier anonymous events and the later signed-in events as one person. 5. In the dashboard you see events arrive live, and you build **funnels** from them: ordered steps such as `onboarding_started → paywall_viewed → purchase_completed`, counted as unique people. ## 3. Get your write key 1. Open the App Store Operator dashboard → **Apps** → your app → **Events** → **Setup**. 2. Copy the write key (it starts with `aso_wk_`). 3. Test it from a terminal (macOS or Linux). The command creates a new `event_id` and the current time on every run, so you can run it again: ```bash curl -sS https://api.app-store-operator.com/v1/events \ -H "Content-Type: application/json" \ -H "X-Write-Key: YOUR_WRITE_KEY" \ -d '{ "events": [{ "event_id": "'"$(uuidgen)"'", "name": "integration_test", "anonymous_id": "curl-test", "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'", "properties": { "source": "curl" } }] }' ``` Expected response: `accepted` is `1` and `rejected` is empty. The event appears under **Events → Live** within a few seconds. Why fresh values: a repeated `event_id` is stored only once, so a second run with the same ID shows nothing new in Live, and a time more than 7 days old is replaced by the time we received it. ### 3.1 Rotating the key Rotate the key only if it is being abused, for example if someone is sending fake events with it. The key is public, so being visible in your app is not a reason to rotate. 1. Setup → **Rotate key**. Any member of the workspace can do this, and it is recorded. 2. Put the new key in your app and ship an update. 3. The old key keeps working for **30 days**, so your users have time to update. After that, builds that still use the old key get `401` and the reference code drops their events. People on those builds are not counted until they update. 4. If the old key is still being abused, Setup → **Revoke old key now** ends its 30 days at once. From then on, builds that use the old key are not counted. Any member of the workspace can do this, and it is recorded. 5. While an old key is in its 30 days, **Rotate key** is disabled. To rotate again, revoke the old key first or wait until its 30 days end. ## 4. API reference ### 4.1 `POST /v1/events` Send 1 to 100 events. **Headers** | Header | Required | Value | |---|---|---| | `Content-Type` | yes | `application/json` | | `X-Write-Key` | yes | your app's write key | **Body** ```json { "events": [ , ... ] } ``` The whole body must be at most **1 MB**. Unknown fields, in the body or in an event, are ignored. ### 4.2 Response `200 OK` whenever the batch itself is valid, even if some events were rejected: ```json { "accepted": 2, "rejected": [ { "index": 2, "event_id": "…", "code": "invalid_name", "message": "Event name must match ^[A-Za-z0-9_.:-]{1,64}$" } ], "clamped": [ { "index": 0, "event_id": "…" } ] } ``` - `accepted`: events stored, including duplicates that were already stored (see `event_id`). - `rejected`: events that were not stored and must not be retried unchanged. - `clamped`: events whose `occurred_at` was out of range and was replaced by the server's receive time. They are stored and counted in `accepted`. All three fields are always present; `rejected` and `clamped` may be empty. ### 4.3 Event object | Field | Type | Required | Rules | |---|---|---|---| | `event_id` | string (UUID) | yes | Unique per event. Generate it when the event is created, not when it is sent, so a retried batch is not counted twice. | | `name` | string | yes | `^[A-Za-z0-9_.:-]{1,64}$`. A `$` followed by 1–63 of those characters (e.g. `$session_start`) is reserved for App Store Operator and rejected with `reserved_name`; any other invalid name is `invalid_name`. Use `snake_case` `object_action`, e.g. `paywall_viewed`. | | `anonymous_id` | string | yes | 1–128 chars. Stable per install. | | `user_id` | string or null | no | 1–128 chars. Your own stable user ID. Never an email or phone number. | | `occurred_at` | string | yes | ISO 8601 with timezone, e.g. `2026-10-23T12:00:00.123Z`. Accepted from 7 days in the past to 5 minutes in the future. | | `properties` | object | no | Flat object, at most 50 keys. Key: 1–64 chars. Value: string (≤ 1024 chars), number, boolean or `null`. **No nested objects or arrays.** | | `context` | object | no | See below. Recommended: the dashboard filters and breaks funnels down by these fields. | **`context`** | Field | Example | Notes | |---|---|---| | `app_version` | `"2.4.0"` | `CFBundleShortVersionString` | | `build` | `"412"` | `CFBundleVersion` | | `os_version` | `"18.1"` | | | `device_model` | `"iPhone16,2"` | Hardware identifier, not a marketing name | | `locale` | `"en_US"` | The device locale, `language_REGION` | | `environment` | `"app_store"` | `"debug"`, `"testflight"` or `"app_store"`. The dashboard shows only `app_store` events (and events without it) unless you choose otherwise | Every `context` value is a string of at most 64 characters. A value that breaks this, and any key not in this table, is dropped without rejecting the event. The server adds `country` from the request's network location. The IP address itself is never stored. A serialized event must be at most **8 KB**. **Full example** ```json { "event_id": "0b6f6a3e-3c3e-4d8a-8f6e-1f9b8a2c7d10", "name": "purchase_completed", "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723", "occurred_at": "2026-10-23T12:04:31.512Z", "properties": { "product_id": "pro_yearly", "price": 39.99, "currency": "USD", "trial": true }, "context": { "app_version": "2.4.0", "build": "412", "os_version": "18.1", "device_model": "iPhone16,2", "locale": "en_US", "environment": "app_store" } } ``` ### 4.4 `POST /v1/identify` (optional) Links an anonymous ID to a user ID without sending an event. You rarely need it: any event that carries both IDs does the same. Use it when the link is known on your server. ```json { "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723" } ``` Response: `204 No Content`. The first link for an anonymous ID wins; later different user IDs for the same anonymous ID are ignored. Errors use the same body and codes as §4.5: `400 invalid_body` when the body is not JSON or either ID is missing or not a 1–128 char string, `401 invalid_write_key`, `413 payload_too_large`, and `429 rate_limited`, because each call counts as one event against the write key's rate limit. ### 4.5 Errors | Status | `code` | Meaning | Client action | |---|---|---|---| | 400 | `invalid_body` | Body is not valid JSON or not `{ "events": [...] }`, or 0 / more than 100 events | Fix the code; do not retry | | 401 | `invalid_write_key` | Missing, unknown or revoked key. `/v1/events` also answers it when the app was removed from App Store Operator, its App Store Connect connection was deleted, or the workspace's account was disabled | Do not retry; drop the batch and check the key | | 413 | `payload_too_large` | Body over 1 MB | Send smaller batches | | 403 | `quota_exceeded` | The account has used 110% of its monthly event limit. Nothing in the request was stored | Do not retry; drop the batch. Sending resumes on the 1st (UTC) or after an upgrade | | 429 | `rate_limited` | Over 10,000 events per minute for the key (500 on the Free plan), or 300 for one `anonymous_id`. The key's limit counts every event sent, rejected ones included, and each `/v1/identify` call as one; the `anonymous_id` limit counts accepted events. Nothing in the request was stored | Keep the batch; retry after `Retry-After` seconds | | 5xx | `server_error` | Our fault | Keep the batch; retry with backoff | Error body: `{ "code": "invalid_write_key", "message": "…" }`. **Per-event rejection codes** (inside a `200` response): | Code | When | |---|---| | `invalid_event` | The item in `events` is not a JSON object | | `invalid_name` | `name` missing, or not matching `^[A-Za-z0-9_.:-]{1,64}$` | | `reserved_name` | `name` is `$` followed by 1–63 characters from `[A-Za-z0-9_.:-]` | | `invalid_id` | `event_id` missing or not a UUID; `anonymous_id` missing or not a 1–128 char string; `user_id` present but not a 1–128 char string or `null` | | `invalid_timestamp` | `occurred_at` missing, unparseable, or without a timezone. (Out of range is not a rejection: see `clamped`) | | `invalid_properties` | `properties` not a flat object; a key outside 1–64 chars; a nested object or array; a string over 1,024 chars | | `too_many_properties` | More than 50 properties | | `event_too_large` | The serialized event is over 8 KB | | `too_many_event_names` | The app already has 500 different event names and this one is new. Reuse a name and put the detail in a property | **Retry rule in one line:** retry on network failure, `429` and `5xx`, keeping the same `event_id`s; drop on every other status. ## 5. Reference implementation One Dart file. Add it to the app as `lib/event_tracker.dart` and use it unchanged. It needs four packages, and no others: ```bash flutter pub add path_provider shared_preferences package_info_plus device_info_plus ``` `flutter pub add` picks the latest versions. The code was tested with these (Flutter 3.44, Dart 3.12): ```yaml dependencies: path_provider: ^2.1.6 shared_preferences: ^2.5.6 package_info_plus: ^10.2.2 device_info_plus: ^13.3.0 ``` | Package | Used for | |---|---| | `path_provider` | The queue file, in the app support directory | | `shared_preferences` | The anonymous ID, the user ID and the on/off setting (`UserDefaults` on iOS) | | `package_info_plus` | `app_version` and `build` | | `device_info_plus` | `os_version` and `device_model` | Requests go through `HttpClient` from `dart:io`, so no HTTP package is needed. What it does: - **iOS only.** On Android, web and desktop every method returns at once and does nothing: no ID, no file, no request. App Store Operator covers iOS apps for now, and this keeps Android installs out of your App Store funnels. Android support is planned. - Creates a random anonymous ID (a version 4 UUID from `Random.secure()`) with the first tracked event and keeps it (in `shared_preferences`). `currentAnonymousId` returns it. - Has an on/off switch, `setEnabled(...)`, remembered across launches and on by default. Turning it off deletes the IDs and every unsent event, and `track` does nothing until it is turned on again. - Saves every event to a queue file on disk, so events survive the app being closed. - Sends the queue in batches of up to 100: every 30 seconds, when 20 or more events are waiting, and when you call `flush()`. - Offline or `5xx`: keeps the queue and waits before trying again: 30 seconds, then 60, 120… up to 10 minutes. `429`: keeps the queue and waits as long as the server's `Retry-After` says. Any other response: removes the batch from the queue. - Keeps at most 1,000 events; past that, the oldest are dropped. - Debug builds only (`kDebugMode`): prints rejected and clamped events, dropped batches, and property values it dropped, to the Flutter console with `debugPrint` as `[EventTracker] …`. Release builds print nothing. - Marks events from debug and profile builds as `debug`, so test runs stay out of your funnels. Release builds carry the `environment` you pass to `configure`, or none (see **Test builds** below). - `track` returns at once and never waits for the network. `configure`, `track`, `identify`, `reset` and `setEnabled` take effect in the order you call them, so you do not need to `await` them for that. `track` works before `configure`; events wait in the queue until a key is set. **One app, one key.** Each app in the dashboard has its own write key. Use each key only in that app's binary. **Not in app extensions.** If your iOS app has native extensions (widgets, share, notification extensions), do not track from them. Extensions keep their own storage, so each would get its own anonymous ID and count as a separate person. Track from the Flutter app only. **Test builds.** A Flutter release build cannot tell TestFlight from the App Store without native code. `configure` therefore takes an optional `environment`, `"testflight"` or `"app_store"` (any other value is ignored, and debug and profile builds are always `debug`). The [§5.1](#51-wire-it-up) code reads it from a build-time define: ```bash flutter build ipa --dart-define=ASO_ENV=testflight ``` Without the define, release events carry no environment and the dashboard counts them as App Store events, TestFlight testers included. Apple releases the same build you uploaded to TestFlight, so a build made with `ASO_ENV=testflight` keeps that mark if you later release it to the App Store, and its App Store users then disappear from the dashboard's default view. Use the define only for builds that will never be released, for example a separate internal testing build; otherwise leave it out. ```dart import 'dart:async'; import 'dart:convert'; import 'dart:io'; import 'dart:math'; import 'package:device_info_plus/device_info_plus.dart'; import 'package:flutter/foundation.dart'; import 'package:package_info_plus/package_info_plus.dart'; import 'package:path_provider/path_provider.dart'; import 'package:shared_preferences/shared_preferences.dart'; /// Sends events to App Store Operator. Docs: https://app-store-operator.com/docs/events/flutter /// /// iOS only: on Android, web and desktop every method does nothing. class EventTracker { EventTracker._(); static final EventTracker shared = EventTracker._(); static final Uri _endpoint = Uri.parse('https://api.app-store-operator.com/v1/events'); static const int _maxBatch = 100; static const int _maxQueue = 1000; static const int _flushAt = 20; static const String _anonymousIdKey = 'aso.events.anonymousId'; static const String _userIdKey = 'aso.events.userId'; static const String _disabledKey = 'aso.events.disabled'; static const Set _environments = {'debug', 'testflight', 'app_store'}; static final bool _supported = !kIsWeb && defaultTargetPlatform == TargetPlatform.iOS; static final Random _random = Random.secure(); late final Future _ready = _load(); // started by the first call final HttpClient _http = HttpClient()..connectionTimeout = const Duration(seconds: 30); SharedPreferencesWithCache? _prefs; File? _store; Map _context = const {}; String? _writeKey; String? _environment; String? _anonymousId; String? _userId; bool _enabled = true; List> _queue = []; bool _flushing = false; Timer? _timer; DateTime? _retryAt; int _backoff = 0; // seconds Future? _writing; bool _dirty = false; bool _warned = false; /// Call once at launch, after `WidgetsFlutterBinding.ensureInitialized()`. /// /// Debug and profile builds are marked `debug`. Release builds are marked with [environment] /// (`testflight` or `app_store`) when given, otherwise they carry no environment. void configure({required String writeKey, String? environment}) { if (!_isSupported()) return; _writeKey = writeKey; if (!kReleaseMode) { _environment = 'debug'; } else if (environment != null && _environments.contains(environment)) { _environment = environment; } _timer ??= Timer.periodic(const Duration(seconds: 30), (_) => flush()); unawaited(_ready); } /// The ID of this install, or null before the first tracked event and while tracking is off. /// Show it on a support screen so a user can ask for their data to be deleted. Future get currentAnonymousId async { if (!_isSupported()) return null; await _ready; return _anonymousId; } /// Turns tracking on or off, and remembers the choice across launches. Tracking is on by default. /// Turning it off deletes this install's IDs and every event not yet sent; `track` then does nothing. /// If your app needs the user's consent first, call `setEnabled(false)` at launch until they agree. Future setEnabled(bool enabled) async { if (!_isSupported()) return; await _ready; _enabled = enabled; unawaited(_prefs?.setBool(_disabledKey, !enabled)); if (enabled) return; _anonymousId = null; _userId = null; _queue = []; unawaited(_prefs?.remove(_anonymousIdKey)); unawaited(_prefs?.remove(_userIdKey)); _persist(); // an empty queue deletes the file } /// Records an event. Cheap; returns at once and never waits for the network. /// Does nothing while tracking is off. Property values: String, int, double, bool or null. void track(String name, [Map properties = const {}]) { if (!_isSupported()) return; final eventId = _uuid(); final occurredAt = _now(); final props = _flat(name, properties); unawaited(_ready.then((_) { if (!_enabled) return; _queue.add({ 'event_id': eventId, 'name': name, 'anonymous_id': _anonymousId ?? _newAnonymousId(), if (_userId != null) 'user_id': _userId, 'occurred_at': occurredAt, 'properties': props, 'context': _context, }); if (_queue.length > _maxQueue) _queue.removeRange(0, _queue.length - _maxQueue); _persist(); if (_queue.length >= _flushAt) unawaited(flush()); })); } /// Call after the user signs in to your app. Use your own stable user ID, never an email. Future identify(String userId) async { if (!_isSupported()) return; await _ready; if (!_enabled) return; _userId = userId; unawaited(_prefs?.setString(_userIdKey, userId)); } /// Call on sign-out: later events belong to a new anonymous person. Future reset() async { if (!_isSupported()) return; await _ready; _userId = null; _anonymousId = null; unawaited(_prefs?.remove(_userIdKey)); unawaited(_prefs?.remove(_anonymousIdKey)); } /// Sends queued events. Does nothing while waiting out a retry delay. Future flush() async { if (!_isSupported()) return; await _ready; final writeKey = _writeKey; if (!_enabled || _flushing || writeKey == null || _queue.isEmpty) return; final retryAt = _retryAt; if (retryAt != null && retryAt.isAfter(DateTime.now())) return; _flushing = true; try { while (_queue.isNotEmpty) { final batch = _queue.take(_maxBatch).toList(); final events = [ for (final event in batch) { ...event, 'context': { if (_environment != null) 'environment': _environment, ...(event['context'] as Map? ?? const {}), }, }, ]; final response = await _post(writeKey, jsonEncode({'events': events})); if (response == null) { _delayRetry(null); // offline: keep the queue return; } if (!_enabled) return; // turned off while sending: the queue is already gone final (status, retryAfter, body) = response; if (status == 429 || status >= 500) { _delayRetry(status == 429 ? double.tryParse(retryAfter ?? '') : null); // keep the queue return; } _retryAt = null; _backoff = 0; if (kDebugMode) _report(status, body); // 2xx: stored. Other 4xx: retrying the same batch cannot succeed. final sent = {for (final event in batch) event['event_id']}; _queue.removeWhere((event) => sent.contains(event['event_id'])); _persist(); } } finally { _flushing = false; } } Future _load() async { try { final prefs = await SharedPreferencesWithCache.create( cacheOptions: const SharedPreferencesWithCacheOptions( allowList: {_anonymousIdKey, _userIdKey, _disabledKey}, ), ); _prefs = prefs; _enabled = !(prefs.getBool(_disabledKey) ?? false); _anonymousId = prefs.getString(_anonymousIdKey); // created on the first tracked event _userId = prefs.getString(_userIdKey); } catch (error) { _debug('settings unavailable, keeping IDs in memory: $error'); } try { final dir = await getApplicationSupportDirectory(); await dir.create(recursive: true); final store = File('${dir.path}/aso-events-queue.json'); _store = store; if (await store.exists()) { final saved = jsonDecode(await store.readAsString()) as List; _queue = [for (final event in saved) Map.from(event as Map)]; } } catch (error) { _debug('queue file unavailable, keeping events in memory: $error'); } var appVersion = '', build = '', osVersion = '', deviceModel = ''; try { final package = await PackageInfo.fromPlatform(); appVersion = package.version; build = package.buildNumber; } catch (_) {} try { final ios = await DeviceInfoPlugin().iosInfo; osVersion = ios.systemVersion; deviceModel = ios.utsname.machine; } catch (_) {} _context = { 'app_version': appVersion, 'build': build, 'os_version': osVersion, 'device_model': deviceModel, 'locale': PlatformDispatcher.instance.locale.toString(), // en_US }; } Future<(int, String?, String)?> _post(String writeKey, String body) async { try { return await () async { final request = await _http.postUrl(_endpoint); request.headers.contentType = ContentType.json; request.headers.set('X-Write-Key', writeKey); request.add(utf8.encode(body)); final response = await request.close(); final text = await response.transform(utf8.decoder).join(); return (response.statusCode, response.headers.value('retry-after'), text); }().timeout(const Duration(seconds: 60)); } catch (_) { return null; } } /// Waits `seconds` when the server says so, otherwise 30 s, 60 s, 120 s… up to 10 minutes. void _delayRetry(double? seconds) { _backoff = min(max(_backoff * 2, 30), 600); final wait = Duration(milliseconds: ((seconds ?? _backoff) * 1000).round()); _retryAt = DateTime.now().add(wait); } /// Writes the queue to disk, one write at a time; the last write always has the latest queue. void _persist() { if (_store == null) return; _dirty = true; _writing ??= _write(); } Future _write() async { while (_dirty) { _dirty = false; final store = _store!; try { if (_queue.isEmpty) { if (await store.exists()) await store.delete(); } else { final temp = File('${store.path}.tmp'); await temp.writeAsString(jsonEncode(_queue), flush: true); await temp.rename(store.path); } } catch (_) {} } _writing = null; } String _newAnonymousId() { final id = _uuid(); _anonymousId = id; unawaited(_prefs?.setString(_anonymousIdKey, id)); return id; } /// Keeps String, int, finite double, bool and null values; drops anything else. Map _flat(String name, Map properties) { final result = {}; properties.forEach((key, value) { if (value == null || value is String || value is int || value is bool || (value is double && value.isFinite)) { result[key] = value; } else { _debug('$name: property "$key" dropped, ${value.runtimeType} is not a flat value'); } }); return result; } /// Debug builds only: prints dropped batches and rejected or clamped events to the Flutter console. void _report(int status, String body) { Object? json; try { json = jsonDecode(body); } catch (_) {} if (status < 200 || status >= 300) { _debug('HTTP $status, batch dropped: ${json ?? body}'); return; } if (json is! Map) return; for (final key in ['rejected', 'clamped']) { final items = json[key]; if (items is List && items.isNotEmpty) _debug('$key: $items'); } } bool _isSupported() { if (_supported) return true; if (!_warned) { _warned = true; _debug('iOS only: tracking is off on ${kIsWeb ? 'web' : defaultTargetPlatform.name}'); } return false; } static void _debug(String message) { if (kDebugMode) debugPrint('[EventTracker] $message'); } static String _now() { final now = DateTime.now().millisecondsSinceEpoch; return DateTime.fromMillisecondsSinceEpoch(now, isUtc: true).toIso8601String(); } /// A random (version 4) UUID. static String _uuid() { final bytes = List.generate(16, (_) => _random.nextInt(256)); bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80; final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(); return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-${hex.substring(12, 16)}-' '${hex.substring(16, 20)}-${hex.substring(20)}'; } } ``` ### 5.1 Wire it up ```dart import 'dart:async'; import 'package:flutter/widgets.dart'; import 'event_tracker.dart'; void main() { WidgetsFlutterBinding.ensureInitialized(); EventTracker.shared.configure( writeKey: 'YOUR_WRITE_KEY', environment: const String.fromEnvironment('ASO_ENV'), // see "Test builds" in §5 ); EventTracker.shared.track('app_opened', {'source': 'cold'}); var wasInBackground = false; // Stays registered for the app's lifetime; no need to keep a reference. AppLifecycleListener( onHide: () { // The app is moving to background: send what is queued. wasInBackground = true; unawaited(EventTracker.shared.flush()); }, onResume: () { if (!wasInBackground) return; // alerts, Control Center and Face ID only make it inactive wasInBackground = false; EventTracker.shared.track('app_opened', {'source': 'warm'}); }, ); runApp(const MyApp()); } ``` If `main()` already does other setup, keep it, and put these calls after `WidgetsFlutterBinding.ensureInitialized()` and before `runApp`: the tracker reads its stored IDs and device details through plugins, which need the binding. `AppLifecycleListener` needs Flutter 3.13 or later. If the app already has a `WidgetsBindingObserver`, you can use it instead: call `flush()` on `AppLifecycleState.hidden` and track the warm `app_opened` on the next `resumed`. `app_opened` is sent on returning from background only, not on every resume: system alerts, Control Center and Face ID also make the app inactive and active again, without hiding it. **Background time.** iOS gives an app a few seconds after it moves to background, which is usually enough for `flush()` to finish. A Flutter app cannot ask iOS for more time without native code, so if the app is suspended first, the events stay in the queue file and are sent at the next launch. ### 5.2 Track events ```dart EventTracker.shared.track('paywall_viewed', {'placement': 'onboarding'}); EventTracker.shared.track('onboarding_completed', {'duration_s': 42}); // Variables work the same way: String, int, double, bool or null values. EventTracker.shared.track('purchase_started', {'product_id': productId}); // After sign-in / sign-out in your app: await EventTracker.shared.identify(user.id); await EventTracker.shared.reset(); // Consent or an in-app "Share analytics" toggle: call it at launch, before configure and the first track, // with the user's current choice, and again whenever the choice changes. await EventTracker.shared.setEnabled(userAllowsAnalytics); // Support screen: show this so a user can ask for their data to be deleted (null if nothing was tracked yet). final installId = await EventTracker.shared.currentAnonymousId; ``` If tracking waits for consent, call `setEnabled` before the launch `app_opened` in [§5.1](#51-wire-it-up); while tracking is off, that call does nothing and no ID is created. Property values must be `String`, `int`, `double`, `bool` or `null`. The tracker drops any other value (a `DateTime`, an enum, a nested map or list, `double.nan`) and, in a debug build, prints `[EventTracker] … dropped`. Convert first: `date.toIso8601String()`, `plan.name`. **Purchases.** Track purchases in the purchase flow, where the user taps buy. Put this wrapper around your purchase call: ```dart /// How a purchase ended, as your purchase code reports it. enum PurchaseOutcome { success, cancelled, pending, failed } /// Wraps your purchase call. [purchase] runs it and says how it ended. Future buy({ required String productId, required double price, required String currency, required bool startsTrial, required Future Function() purchase, }) async { final base = {'product_id': productId}; EventTracker.shared.track('purchase_started', base); PurchaseOutcome outcome; try { outcome = await purchase(); } catch (_) { outcome = PurchaseOutcome.failed; } switch (outcome) { case PurchaseOutcome.success: EventTracker.shared.track('purchase_completed', { ...base, 'price': price, 'currency': currency, 'trial': startsTrial, }); if (startsTrial) EventTracker.shared.track('trial_started', base); case PurchaseOutcome.cancelled: EventTracker.shared.track('purchase_failed', {...base, 'reason': 'cancelled'}); case PurchaseOutcome.failed: EventTracker.shared.track('purchase_failed', {...base, 'reason': 'failed'}); case PurchaseOutcome.pending: break; // Ask to Buy or extra approval: not completed yet, track nothing } } ``` `purchase` is your own function around your store library's purchase method. It returns `success` when the purchase went through and was verified, `cancelled` when the user cancelled, `pending` for Ask to Buy or other approval, and `failed` otherwise (throwing counts as `failed`). `price` (a number, not a formatted string) and `currency` (an ISO 4217 code such as `"USD"`) come from your product details, and `startsTrial` is whatever your paywall already knows: true when this purchase starts a free trial. - **`in_app_purchase`:** `buyNonConsumable` and `buyConsumable` only start the purchase; the result arrives on `purchaseStream`. Make `purchase` start the purchase and wait for the first update for that product: `PurchaseStatus.purchased` is `success`, `canceled` is `cancelled`, `pending` is `pending`, and `error` is `failed`. Price and currency are `ProductDetails.rawPrice` and `currencyCode`. - **RevenueCat (`purchases_flutter`):** its purchase methods return when the purchase succeeds and throw a `PlatformException` when it does not. Map `PurchasesErrorCode.purchaseCancelledError` to `cancelled`, `paymentPendingError` to `pending`, and other errors to `failed`. - **Any other library:** put the same calls around its purchase method. Do not track purchases from a listener that receives every transaction, such as your `in_app_purchase` `purchaseStream` handler: it also delivers restored purchases (`PurchaseStatus.restored`), renewals and purchases that finish at a later launch, so they would be counted as new purchases. ## 6. What to track Funnels are only as good as the events behind them. Start with the steps below and add more as questions come up. **Naming rules** - `snake_case`, `object_action`, past tense: `paywall_viewed`, `purchase_completed`. - One name per action. Put variations in properties (`paywall_viewed` with `placement: "settings"`), not in the name (`settings_paywall_viewed`). - Never put IDs, dates or user data in the name. - Where you want to split a funnel by a property, give it a short list of fixed values (`plan: "yearly"`), not free text. The dashboard shows the top 10 values and groups the rest as "Other". - Names and property values are case-sensitive: `Paywall_Viewed` and `paywall_viewed` are two different events. **Recommended starter set** Track the events whose flow exists in your app; skip the rest. Properties marked *optional* can be left out. | Event | When | Properties | |---|---|---| | `app_opened` | App launch and every return from background (the [§5.1](#51-wire-it-up) wiring sends it) | `source` (`"cold"` launch, `"warm"` return) | | `onboarding_started` | First onboarding screen shown | | | `onboarding_completed` | Last onboarding step done | `duration_s` *optional* (number) | | `signup_completed` | Account created in your app | `method` (`"apple"`, `"google"`, `"email"`) | | `paywall_viewed` | Paywall shown | `placement` (where it was shown: `"onboarding"`, `"settings"`, `"feature_gate"`), `paywall_id` *optional* | | `purchase_started` | User taps buy | `product_id` | | `purchase_completed` | Purchase succeeded and verified, in the purchase flow ([§5.2](#52-track-events)). Includes purchases that start a free trial | `product_id`, `price` (number), `currency`, `trial` (boolean) | | `purchase_failed` | User cancelled, or the purchase failed. Ask to Buy (pending) is neither: track nothing | `product_id`, `reason` (`"cancelled"`, `"failed"`) | | `trial_started` | Sent **in addition to** `purchase_completed` when that purchase starts a free trial | `product_id` | | `purchase_restored` | Restore purchases found an active subscription | `product_id` *optional* | | Your core action | The one thing your app is for. Name it for that action: `scan_completed`, `workout_finished`, `photo_exported` | what describes it | **What events from the app cannot show.** Renewals, free trials that turn into paid subscriptions, cancellations and refunds happen at Apple, usually while your app is closed. The app never sees them, so they are not in these events, and funnels here end at the purchase or the trial start. **Example funnels these enable** | Funnel | Steps | Window | What it answers | |---|---|---|---| | First session | `onboarding_started → onboarding_completed → paywall_viewed (placement = onboarding) → purchase_completed` | 1 day | How many new users reach the paywall and buy | | Paywall conversion | `paywall_viewed → purchase_started → purchase_completed`, broken down by `placement` | 1 hour | Which paywall placement converts best, and whether people drop at the price or at Apple's sheet | | Activation | `onboarding_completed → scan_completed` (your core action) | 1 day | How many new users get to the point of the app | ## 7. Privacy This section is guidance, not legal advice. You know what your app sends and where your users are, so the final decisions are yours, ideally with your own counsel. Privacy contact for everything in this section: `privacy@app-store-operator.com`. ### 7.1 What App Store Operator receives - Event names and their properties. - `anonymous_id`: a random UUID the reference code creates with the first event tracked while tracking is on, and keeps for that install until tracking is turned off or `reset` is called. It is not the IDFA or any other identifier shared with other apps. - `user_id`, only if you call `identify`. - The device context in [§4.3](#43-event-object): app version, build, OS version, device model, locale and build environment. - The country, derived from the request's network location (see [§7.3](#73-ip-address-and-country)). The reference code sends events from the iOS build only; Android, web and desktop builds send nothing. **Never send** names, emails, phone numbers, precise location, the IDFA, or free text typed by the user, whether in event names, properties or `user_id`. `user_id` must be your app's own internal ID (for example a database key), not an email, a phone number, or an ID another company assigned. ### 7.2 Roles and service providers - **Roles.** For the events your app sends, you are the data controller (under KVKK, *veri sorumlusu*): you decide what is collected and why. Nefarius, which runs App Store Operator, processes the events on your behalf as your data processor (under KVKK, *veri işleyen*), to store them and show them to you in the dashboard. - **What we do not do.** We do not sell event data, use it for advertising, or share it with other customers. - **Service providers (subprocessors).** Like any hosted service, we rely on providers that handle event data only on our behalf: - **Cloudflare**: network delivery and security. Every request from your app passes through it. - **Our server hosting provider**: runs the servers and the database where events are stored. - **Locations.** Cloudflare operates worldwide, so a request may be handled outside your users' country. - **Data processing agreement (DPA).** If you need a DPA (for example under GDPR Article 28), the current list of service providers with their locations, or details of the safeguards for international transfers, write to the privacy contact above. ### 7.3 IP address and country Your app's requests reach us through Cloudflare, which needs the IP address to deliver them and looks up the country from it. App Store Operator keeps only the country (no city or region) and never stores or logs the IP address. ### 7.4 Retention and deletion requests - Events are kept for 13 months, then deleted automatically. - Deleting one person's events from the dashboard is not available yet. Until it is, when a user asks you to delete their data (for example under GDPR Article 17 or KVKK Article 11), email the privacy contact above from the address of a member of your App Store Operator workspace, with: - the app's name as shown in the dashboard; - the person's `user_id`, and/or their `anonymous_id`. A `user_id` also covers every `anonymous_id` linked to it. For users without an account, your app can show the `anonymous_id` from `await EventTracker.shared.currentAnonymousId`, for example on a support screen ([§5.2](#52-track-events)). Read it before calling `setEnabled(false)` or `reset()`: both delete it from the device, and without it we cannot find that install's events. - We delete every event with those IDs and confirm by email. Send requests promptly: you have your own deadline to answer the user (generally one month under GDPR, 30 days under KVKK). - Requests from anyone who is not a member of the workspace are not acted on; we refer the person to you. ### 7.5 Your privacy policy and consent - **Privacy policy.** Your app's privacy policy should say that you collect usage analytics, what data that includes (§7.1), that a service provider (App Store Operator, run by Nefarius) processes it for you, and that it is kept for 13 months. - **Legal basis and consent.** You choose the legal basis for analytics and whether you need your users' consent first. In the EU and UK, storing or reading an identifier on the device for analytics often requires consent; under KVKK you must at least inform users. If you need consent, call `EventTracker.shared.setEnabled(false)` at launch, before anything else, until the user agrees, then `setEnabled(true)` ([§5.2](#52-track-events)). While tracking is off, no ID or event is stored on the device (only the off setting itself) and nothing is sent. The tracker creates its `anonymous_id` only with the first event tracked while it is on. If the user later withdraws consent, `setEnabled(false)` stops tracking and deletes the IDs and unsent events on the device. It does not delete events already sent: if consent was your only legal basis, or the user asks for deletion, request it through [§7.4](#74-retention-and-deletion-requests), reading `currentAnonymousId` first. ### 7.6 App Tracking Transparency App Store Operator does not combine your events with data from other companies' apps, websites or offline sources for advertising or ad measurement, does not share them with data brokers, and does not use the device context to fingerprint devices. On its own, therefore, the integration is not tracking as Apple defines it and does not require the App Tracking Transparency (ATT) prompt. ATT is decided for your app as a whole, not per integration. If your app, or another SDK in it, links these events or your `user_id` with other companies' data for advertising or ad measurement, or shares them with a data broker, that is tracking: you need the user's ATT permission first, and your privacy label must say the data is used to track. See Apple's [User Privacy and Data Use](https://developer.apple.com/app-store/user-privacy-and-data-use/). ### 7.7 App Store privacy label and privacy manifest You answer Apple's privacy questions for the whole app, and Apple asks you to include data collected by third-party code you add, which includes this code. For the data App Store Operator receives, the typical answers are: | Apple data type | Declare when | Purpose | |---|---|---| | Usage Data → Product Interaction | Always | Analytics | | Identifiers → Device ID | Always: `anonymous_id` is a persistent per-install identifier | Analytics | | Location → Coarse Location | Always: the country is derived from the user's network location. It is coarser than Apple's examples, but declaring it is the safer answer | Analytics | | Purchases → Purchase History | If you track the purchase events in §6 | Analytics | | Identifiers → User ID | If you call `identify` or send `user_id` | Analytics | - **Linked to You.** If you send `user_id`, declare every row above as *Linked to You*: the events are joined to an account ID in your system. If you never send `user_id` and do not connect the events to an account or other identifying data anywhere else, the data is tied only to a random install ID and you may be able to answer *Not Linked to You*. When in doubt, answer *Linked to You*. - **Tracking.** *Not used to track you*, unless your app tracks as described in §7.6. - **Privacy manifest.** Apple requires a stated reason for some APIs, in your code and in every plugin. For this integration: - `shared_preferences` keeps the IDs and the on/off setting in `UserDefaults`. Its iOS plugin ships its own privacy manifest that declares `UserDefaults` (`NSPrivacyAccessedAPICategoryUserDefaults`), so you do not add an entry for the tracker's use. - The queue file is written with `dart:io`; Flutter's engine ships its own privacy manifest for the file APIs it uses. - `device_info_plus` (13.3.0) also reads the device's free disk space when the tracker asks for the OS version and model. The tracker does not use that value, and the plugin's manifest declares no reason for it. If App Store Connect reports a missing reason for `NSPrivacyAccessedAPICategoryDiskSpace` (ITMS-91053) after you upload, add that category to your app's `PrivacyInfo.xcprivacy` with the reason from Apple's list that matches your app's use, or ask the plugin's maintainers. - Still yours to check: your app's own `PrivacyInfo.xcprivacy` (Flutter does not create one; add it to the `Runner` target in Xcode) should list collected data types that match your label, and App Store Connect's email after each upload lists any missing reasons for the whole app, other plugins included. Apple's definitions: [App privacy details on the App Store](https://developer.apple.com/app-store/app-privacy-details/) and [Privacy manifest files](https://developer.apple.com/documentation/bundleresources/privacy-manifest-files). ### 7.8 Apps for children Apple's [App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) (1.3 and 5.1.4) do not allow third-party analytics in Kids Category apps, except in limited cases where the service collects no identifiable information about children, including device information. App Store Operator receives a persistent install ID, the device model and the country, so **do not add it to an app in the Kids Category**. For other apps aimed at children, check the rules that apply to you (for example COPPA in the US, or GDPR rules on children's consent) with your counsel before integrating. ## 8. Verify and troubleshoot 1. Run the app on an iOS simulator or device (`flutter run`), trigger a few events, then send it to background (that sends the queue). 2. Dashboard → your app → **Events → Live**: your events appear within seconds. 3. **Events → Catalog** lists each event name with its property keys. Check the names and keys are the ones you meant. Android, web and desktop builds send nothing. In a debug build the console shows `[EventTracker] iOS only: tracking is off on android` (or the platform's name) once. **Test builds.** Each app has one write key, used by test builds and App Store builds alike. The reference code marks events from debug and profile builds (`flutter run`) as `debug`, and release builds with the `environment` from `--dart-define=ASO_ENV=...` (`testflight` or `app_store`), or with none. By default the dashboard shows `app_store` events and events with no environment; to see your test runs, switch the environment filter to **All builds**. A release build without the define cannot tell TestFlight from the App Store, so its events, TestFlight testers' included, count as App Store events ([§5](#5-reference-implementation)). The curl test sends no environment, so it shows in the default view; find it by its `anonymous_id`, `curl-test`. | Symptom | Likely cause | |---|---| | Nothing in Live | Wrong key (`401`); `configure` never called; the app is running on Android or another platform that is not iOS; or fewer than 20 events queued and the app has not gone to background yet (wait 30 s) | | `401 invalid_write_key` | Key typo; the key was rotated more than 30 days ago; the old key was revoked ([§3.1](#31-rotating-the-key)); or the app or its App Store Connect connection was removed from App Store Operator | | Event missing, others present | Rejected. In a debug build the Flutter console shows `[EventTracker] rejected: …` with the code ([§4.5](#45-errors)) | | A property missing from an event | Its value was not a `String`, `int`, `double`, `bool` or `null`. In a debug build the console shows `[EventTracker] … dropped` | | `[EventTracker] settings unavailable` or `queue file unavailable` in the console | The tracker ran before `WidgetsFlutterBinding.ensureInitialized()`, or the app was not rebuilt after `flutter pub add` (stop it and run it again: a hot restart does not load new plugins). IDs and events are then kept in memory only | | Nothing in Live from a test build | The default view shows App Store events and events with no environment: switch the environment filter to **All builds** | | App Store users missing from the default view | The released build was made with `--dart-define=ASO_ENV=testflight`; build the next release without it | | Events arrive late in bursts | Over a rate limit (`429`), or the server or network was down, or the app was suspended before `flush()` finished; the reference code keeps them and sends them later | | Wrong times | Device clock far off: times more than 7 days in the past or 5 minutes in the future are replaced by the time we received the event | | Same person counted twice in a funnel | `reset()` called when it should not be, or `identify` called with different IDs for one user | | Funnel step is zero | Step's event name or property filter does not match exactly (names and values are case-sensitive) | ## 9. Done checklist The integration is done when every line is true. When you report, give the file and line for each code item; mark an item *not applicable* with the reason. The API is live, so nothing is left pending: run the end-to-end check too. - [ ] `path_provider`, `shared_preferences`, `package_info_plus` and `device_info_plus` are in `pubspec.yaml`, and no other dependency was added for tracking. - [ ] `lib/event_tracker.dart` is unchanged from §5 (iOS-only check included), `flutter analyze` reports no errors, and the app builds for iOS (`flutter build ios --no-codesign`). - [ ] `configure(writeKey: ...)` runs once in `main()`, after `WidgetsFlutterBinding.ensureInitialized()` and before `runApp`, with this app's real key; the text `YOUR_WRITE_KEY` appears nowhere in the project. - [ ] `EventTracker.shared.flush()` runs when the app moves to background. - [ ] `app_opened` is tracked at launch (`source: "cold"`) and on every return from background (`source: "warm"`). - [ ] Every §6 event whose flow exists in this app is tracked, with the listed properties. Report each one as `event → file:line`, and list the §6 events you skipped and why. - [ ] Purchase events are tracked in the purchase flow (§5.2), not in a listener such as `purchaseStream` that also delivers restores. - [ ] Every event name matches `^[A-Za-z0-9_.:-]{1,64}$` and follows the §6 naming rules, and every property value is a `String`, `int`, `double`, `bool` or `null`. - [ ] No `track` call sends a name, email, phone number, precise location, IDFA or text the user typed. - [ ] If the app has accounts: `identify` is called after sign-in with the app's own user ID, and `reset` after sign-out. Otherwise neither is called. - [ ] *End to end:* the §3 curl test with this app's key returns `accepted: 1`; a debug run of the app's iOS build shows no rejected events or dropped batches in the Flutter console; and its events appear in Dashboard → Events → Live (**All builds**). - [ ] *Developer:* the list of events and properties above was handed to the developer to check, against §7, the App Store privacy label, the app's `PrivacyInfo.xcprivacy`, the app's privacy policy and any consent requirement, and to decide whether any build uses `--dart-define=ASO_ENV` (§5). The app is not in the Kids Category. --- # App Store Operator Events: integration guide for React Native > **Who this is for:** React Native developers adding event tracking to the iOS build of a React Native app (bare React Native or Expo), and the AI coding agents they hand this document to. It is self-contained: an agent can complete the integration from this file alone. App Store Operator covers iOS apps for now: on Android the tracker in this guide does nothing (Android support is planned). --- ## For AI coding agents: read this first You are adding event tracking to the iOS build of a React Native app so its owner can build funnels in App Store Operator. The app will send events to `POST https://api.app-store-operator.com/v1/events` with the header `X-Write-Key`. **Steps, in order** 1. **Get the write key.** If this document still contains the text `YOUR_WRITE_KEY`, ask the developer for their key (Dashboard → their app → Events → Setup; it starts with `aso_wk_`). Never invent a key or leave the placeholder in code. 2. **Add the tracker.** Install the two packages listed in [§5](#5-reference-implementation), then copy the file in §5 into the app's source as `eventTracker.ts`, unchanged. 3. **Wire it up** as in [§5.1](#51-wire-it-up): `configure(...)` once at launch, `EventTracker.flush()` when the app moves to background, and `app_opened` at launch and on every return from background. 4. **Add `track(...)` calls** for each event in [§6](#6-what-to-track) whose flow exists in this app. Skip events whose flow does not exist. 5. **Add `identify` and `reset`** only if the app has its own sign-in ([§5.2](#52-track-events)). 6. **Finish** with [§9 Done checklist](#9-done-checklist): report every item as done or not applicable, with the file and line that shows it. **Rules** - Do not change the behavior of `eventTracker.ts` (batching, retries, endpoint, queue, the iOS-only check). If it does not fit the app, report why instead of rewriting it. - Do not add any other third-party dependency: only `@react-native-async-storage/async-storage` and `react-native-device-info`. If the app already has them, keep the versions it has. - The tracker does nothing on Android by design. Do not add Android-specific code for it or work around the check. - Do not send directly identifying data: names, emails, phone numbers, precise location, IDFA, or text the user typed ([§7](#7-privacy)). If the app is in the App Store Kids Category, stop and tell the developer: this tracker must not be added ([§7.8](#78-apps-for-children)). If the app asks users for consent to analytics, ask the developer whether tracking must wait for it ([§7.5](#75-your-privacy-policy-and-consent)). - Property values are flat: string, number, boolean or `null`. No nested objects or arrays ([§4.3](#43-event-object)). The tracker's types enforce this; do not cast around them. - Use the event names in §6 exactly as written. Ask the developer before naming an event for a flow §6 does not cover. - Call `identify` only with the app's own stable internal user ID, never an email, phone number or name. If you cannot tell which ID that is, ask. - **Check it end to end: the API is live.** Run the §3 curl test with this app's real key and confirm `accepted: 1`. Then run the iOS app in a debug build (a simulator is fine), trigger a few events and send it to background: the Metro / JS console must show no `[EventTracker]` line for a rejected event or a dropped batch. Ask the developer to confirm the events under Dashboard → Events → Live with the environment filter on **All builds** ([§8](#8-verify-and-troubleshoot)). A `401` means the key is wrong; fix every other failure or report it, do not leave it for later. The write key is public by design (it can only write events for one app), so it may live in source code or in the app's config. --- ## 1. Quick facts | | | |---|---| | Base URL | `https://api.app-store-operator.com/v1` | | Auth | Header `X-Write-Key: ` (Dashboard → your app → Events → Setup) | | Send events | `POST /v1/events` (batch of 1–100) | | Link a user | Automatic when an event carries both `anonymous_id` and `user_id`; or `POST /v1/identify` | | Content type | `application/json`, UTF-8 | | Rate limit | 10,000 events per minute per write key (all installs together; 500 on the Free plan) and 300 per minute per install (`anonymous_id`) | | Monthly events | Counted per account across all its apps, reset on the 1st (UTC). Free: 25,000 a month. Past 110% of your plan's limit, new events are refused (`403 quota_exceeded`) until the next month | | Event names | Up to 500 different names per app; an event with a new name past that is rejected (`too_many_event_names`). The catalog lists up to 200 property keys per event name | | Minimum for the reference code | React Native 0.76 or Expo SDK 52, iOS build only; TypeScript or JavaScript. Expo needs a development build, not Expo Go | | Data retention | 13 months | ## 2. How it works 1. Your app creates a random **anonymous ID** on first launch and keeps it. 2. Every action you care about becomes an **event**: a name, a time, optional properties and some device context. 3. Events are queued on the device and sent in **batches**. If the device is offline, they wait and are sent later. 4. When the user signs in to *your* app, you may set a **user ID**. From then on events carry both IDs, and App Store Operator treats the earlier anonymous events and the later signed-in events as one person. 5. In the dashboard you see events arrive live, and you build **funnels** from them: ordered steps such as `onboarding_started → paywall_viewed → purchase_completed`, counted as unique people. ## 3. Get your write key 1. Open the App Store Operator dashboard → **Apps** → your app → **Events** → **Setup**. 2. Copy the write key (it starts with `aso_wk_`). 3. Test it from a terminal (macOS or Linux). The command creates a new `event_id` and the current time on every run, so you can run it again: ```bash curl -sS https://api.app-store-operator.com/v1/events \ -H "Content-Type: application/json" \ -H "X-Write-Key: YOUR_WRITE_KEY" \ -d '{ "events": [{ "event_id": "'"$(uuidgen)"'", "name": "integration_test", "anonymous_id": "curl-test", "occurred_at": "'"$(date -u +%Y-%m-%dT%H:%M:%SZ)"'", "properties": { "source": "curl" } }] }' ``` Expected response: `accepted` is `1` and `rejected` is empty. The event appears under **Events → Live** within a few seconds. Why fresh values: a repeated `event_id` is stored only once, so a second run with the same ID shows nothing new in Live, and a time more than 7 days old is replaced by the time we received it. ### 3.1 Rotating the key Rotate the key only if it is being abused, for example if someone is sending fake events with it. The key is public, so being visible in your app is not a reason to rotate. 1. Setup → **Rotate key**. Any member of the workspace can do this, and it is recorded. 2. Put the new key in your app and ship an update. 3. The old key keeps working for **30 days**, so your users have time to update. After that, builds that still use the old key get `401` and the reference code drops their events. People on those builds are not counted until they update. 4. If the old key is still being abused, Setup → **Revoke old key now** ends its 30 days at once. From then on, builds that use the old key are not counted. Any member of the workspace can do this, and it is recorded. 5. While an old key is in its 30 days, **Rotate key** is disabled. To rotate again, revoke the old key first or wait until its 30 days end. ## 4. API reference ### 4.1 `POST /v1/events` Send 1 to 100 events. **Headers** | Header | Required | Value | |---|---|---| | `Content-Type` | yes | `application/json` | | `X-Write-Key` | yes | your app's write key | **Body** ```json { "events": [ , ... ] } ``` The whole body must be at most **1 MB**. Unknown fields, in the body or in an event, are ignored. ### 4.2 Response `200 OK` whenever the batch itself is valid, even if some events were rejected: ```json { "accepted": 2, "rejected": [ { "index": 2, "event_id": "…", "code": "invalid_name", "message": "Event name must match ^[A-Za-z0-9_.:-]{1,64}$" } ], "clamped": [ { "index": 0, "event_id": "…" } ] } ``` - `accepted`: events stored, including duplicates that were already stored (see `event_id`). - `rejected`: events that were not stored and must not be retried unchanged. - `clamped`: events whose `occurred_at` was out of range and was replaced by the server's receive time. They are stored and counted in `accepted`. All three fields are always present; `rejected` and `clamped` may be empty. ### 4.3 Event object | Field | Type | Required | Rules | |---|---|---|---| | `event_id` | string (UUID) | yes | Unique per event. Generate it when the event is created, not when it is sent, so a retried batch is not counted twice. | | `name` | string | yes | `^[A-Za-z0-9_.:-]{1,64}$`. A `$` followed by 1–63 of those characters (e.g. `$session_start`) is reserved for App Store Operator and rejected with `reserved_name`; any other invalid name is `invalid_name`. Use `snake_case` `object_action`, e.g. `paywall_viewed`. | | `anonymous_id` | string | yes | 1–128 chars. Stable per install. | | `user_id` | string or null | no | 1–128 chars. Your own stable user ID. Never an email or phone number. | | `occurred_at` | string | yes | ISO 8601 with timezone, e.g. `2026-10-23T12:00:00.123Z`. Accepted from 7 days in the past to 5 minutes in the future. | | `properties` | object | no | Flat object, at most 50 keys. Key: 1–64 chars. Value: string (≤ 1024 chars), number, boolean or `null`. **No nested objects or arrays.** | | `context` | object | no | See below. Recommended: the dashboard filters and breaks funnels down by these fields. | **`context`** | Field | Example | Notes | |---|---|---| | `app_version` | `"2.4.0"` | `CFBundleShortVersionString` | | `build` | `"412"` | `CFBundleVersion` | | `os_version` | `"18.1"` | | | `device_model` | `"iPhone16,2"` | Hardware identifier, not a marketing name | | `locale` | `"en_US"` | The device locale, `language_REGION` | | `environment` | `"app_store"` | `"debug"`, `"testflight"` or `"app_store"`. The dashboard shows only `app_store` events (and events without it) unless you choose otherwise | Every `context` value is a string of at most 64 characters. A value that breaks this, and any key not in this table, is dropped without rejecting the event. The server adds `country` from the request's network location. The IP address itself is never stored. A serialized event must be at most **8 KB**. **Full example** ```json { "event_id": "0b6f6a3e-3c3e-4d8a-8f6e-1f9b8a2c7d10", "name": "purchase_completed", "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723", "occurred_at": "2026-10-23T12:04:31.512Z", "properties": { "product_id": "pro_yearly", "price": 39.99, "currency": "USD", "trial": true }, "context": { "app_version": "2.4.0", "build": "412", "os_version": "18.1", "device_model": "iPhone16,2", "locale": "en_US", "environment": "app_store" } } ``` ### 4.4 `POST /v1/identify` (optional) Links an anonymous ID to a user ID without sending an event. You rarely need it: any event that carries both IDs does the same. Use it when the link is known on your server. ```json { "anonymous_id": "C5E1B0B2-4F7A-4E0F-9C1D-2A6B7E8F9012", "user_id": "u_81723" } ``` Response: `204 No Content`. The first link for an anonymous ID wins; later different user IDs for the same anonymous ID are ignored. Errors use the same body and codes as §4.5: `400 invalid_body` when the body is not JSON or either ID is missing or not a 1–128 char string, `401 invalid_write_key`, `413 payload_too_large`, and `429 rate_limited`, because each call counts as one event against the write key's rate limit. ### 4.5 Errors | Status | `code` | Meaning | Client action | |---|---|---|---| | 400 | `invalid_body` | Body is not valid JSON or not `{ "events": [...] }`, or 0 / more than 100 events | Fix the code; do not retry | | 401 | `invalid_write_key` | Missing, unknown or revoked key. `/v1/events` also answers it when the app was removed from App Store Operator, its App Store Connect connection was deleted, or the workspace's account was disabled | Do not retry; drop the batch and check the key | | 413 | `payload_too_large` | Body over 1 MB | Send smaller batches | | 403 | `quota_exceeded` | The account has used 110% of its monthly event limit. Nothing in the request was stored | Do not retry; drop the batch. Sending resumes on the 1st (UTC) or after an upgrade | | 429 | `rate_limited` | Over 10,000 events per minute for the key (500 on the Free plan), or 300 for one `anonymous_id`. The key's limit counts every event sent, rejected ones included, and each `/v1/identify` call as one; the `anonymous_id` limit counts accepted events. Nothing in the request was stored | Keep the batch; retry after `Retry-After` seconds | | 5xx | `server_error` | Our fault | Keep the batch; retry with backoff | Error body: `{ "code": "invalid_write_key", "message": "…" }`. **Per-event rejection codes** (inside a `200` response): | Code | When | |---|---| | `invalid_event` | The item in `events` is not a JSON object | | `invalid_name` | `name` missing, or not matching `^[A-Za-z0-9_.:-]{1,64}$` | | `reserved_name` | `name` is `$` followed by 1–63 characters from `[A-Za-z0-9_.:-]` | | `invalid_id` | `event_id` missing or not a UUID; `anonymous_id` missing or not a 1–128 char string; `user_id` present but not a 1–128 char string or `null` | | `invalid_timestamp` | `occurred_at` missing, unparseable, or without a timezone. (Out of range is not a rejection: see `clamped`) | | `invalid_properties` | `properties` not a flat object; a key outside 1–64 chars; a nested object or array; a string over 1,024 chars | | `too_many_properties` | More than 50 properties | | `event_too_large` | The serialized event is over 8 KB | | `too_many_event_names` | The app already has 500 different event names and this one is new. Reuse a name and put the detail in a property | **Retry rule in one line:** retry on network failure, `429` and `5xx`, keeping the same `event_id`s; drop on every other status. ## 5. Reference implementation One TypeScript file for the iOS build of a bare React Native or Expo app. Add it to the app's source as `eventTracker.ts` and use it unchanged. It needs two packages and nothing else. **Install the packages** Bare React Native: ```bash npm install @react-native-async-storage/async-storage react-native-device-info npx pod-install ``` Expo: ```bash npx expo install @react-native-async-storage/async-storage react-native-device-info npx expo prebuild ``` Both packages contain native code. In Expo they work in a development build or after `npx expo prebuild`, not in Expo Go, which does not include `react-native-device-info`. Rebuild the iOS app after installing them. If the app already uses either package, keep its version: the tracker uses only `getItem`, `setItem` and `removeItem` from `@react-native-async-storage/async-storage` (version 2 or 3) and `getVersion`, `getBuildNumber`, `getSystemVersion` and `getDeviceId` from `react-native-device-info`. What it does: - Runs on iOS only. On any other platform (`Platform.OS !== "ios"`) every method does nothing, so Android installs do not mix into App Store funnels. - Creates a random anonymous ID (UUID v4) with the first tracked event and keeps it (in AsyncStorage). `currentAnonymousId()` returns it. - Has an on/off switch, `setEnabled(...)`, remembered across launches and on by default. Turning it off deletes the IDs and every unsent event, and `track` does nothing until it is turned on again. - Saves every event to a queue in AsyncStorage, so events survive the app being closed. - Sends the queue in batches of up to 100: every 30 seconds, when 20 or more events are waiting, and when you call `flush()`. - Offline or `5xx`: keeps the queue and waits before trying again: 30 seconds, then 60, 120… up to 10 minutes. `429`: keeps the queue and waits as long as the server's `Retry-After` says. Any other response: removes the batch from the queue. - Keeps at most 1,000 events; past that, the oldest are dropped. - Development builds only (`__DEV__`): logs rejected and clamped events, and dropped batches, to the Metro / JS console as `[EventTracker] …`. Release builds log nothing. - Marks each event from a development build as `debug`, so test runs stay out of your funnels. A release build cannot tell TestFlight from the App Store without native code, so `configure` takes an optional `environment` (`"testflight"` or `"app_store"`) for apps whose build config already knows it ([§5.1](#51-wire-it-up)). Without it, release events carry no environment and the dashboard counts them as App Store events. - `flush()` sends the queue when the app moves to background. iOS gives the app a few seconds there; anything not sent by then stays in the queue and goes out on the next launch. `track` works before `configure` and before the stored state has loaded from AsyncStorage; events wait in memory, then in the queue, until a key is set. **One app, one key.** Each app in the dashboard has its own write key. Use each key only in that app's binary. **Not in app extensions.** Extensions (widgets, share, notification extensions) keep their own storage, so each would get its own anonymous ID and count as a separate person. Track from the main app's JavaScript only. ```typescript import AsyncStorage from "@react-native-async-storage/async-storage"; import { Platform } from "react-native"; import DeviceInfo from "react-native-device-info"; /** Sends events to App Store Operator. Docs: https://app-store-operator.com/docs/events/react-native */ /** A property value. Flat only: no objects or arrays. */ export type EventValue = string | number | boolean | null; export type EventProperties = Record; export type EventEnvironment = "testflight" | "app_store"; type Context = { app_version: string; build: string; os_version: string; device_model: string; locale: string; environment?: string; }; type Event = { event_id: string; name: string; anonymous_id: string; user_id: string | null; occurred_at: string; properties: EventProperties; context: Context; }; const ENDPOINT = "https://api.app-store-operator.com/v1/events"; const MAX_BATCH = 100; const MAX_QUEUE = 1_000; const FLUSH_AT = 20; const FLUSH_INTERVAL_MS = 30_000; const REQUEST_TIMEOUT_MS = 60_000; const ANONYMOUS_ID_KEY = "aso.events.anonymousId"; const USER_ID_KEY = "aso.events.userId"; const DISABLED_KEY = "aso.events.disabled"; const QUEUE_KEY = "aso.events.queue"; // App Store Operator covers iOS apps. On every other platform each method does nothing. const SUPPORTED = Platform.OS === "ios"; class Tracker { private writeKey: string | null = null; private environment: string | undefined = __DEV__ ? "debug" : undefined; private isEnabled = true; private anonymousId: string | null = null; private userId: string | null = null; private queue: Event[] = []; private isFlushing = false; private timer: ReturnType | null = null; private retryAt = 0; private backoffSeconds = 0; private cachedContext: Context | null = null; // Stored state is read once, asynchronously. Calls made before it is loaded wait here, in order. private loading: Promise | null = null; private isLoaded = false; private pending: Array<() => void> = []; private writes: Promise = Promise.resolve(); private queueWriteScheduled = false; /** * Call once at launch. `environment` is for release builds only: pass "testflight" or "app_store" * if your app already knows which one it is. Development builds (`__DEV__`) are always "debug". */ configure(writeKey: string, options: { environment?: EventEnvironment } = {}): void { if (!SUPPORTED) return; this.writeKey = writeKey; if (!__DEV__ && options.environment) this.environment = options.environment; void this.load(); if (this.timer !== null) return; this.timer = setInterval(() => void this.flush(), FLUSH_INTERVAL_MS); } /** * The ID of this install, or null before the first tracked event and while tracking is off. * Show it on a support screen so a user can ask for their data to be deleted. */ async currentAnonymousId(): Promise { if (!SUPPORTED) return null; await this.load(); return this.anonymousId; } /** * Turns tracking on or off, and remembers the choice across launches. Tracking is on by default. * Turning it off deletes this install's IDs and every event not yet sent; `track` then does nothing. * If your app needs the user's consent first, call `setEnabled(false)` at launch until they agree. */ setEnabled(enabled: boolean): void { this.whenLoaded(() => { this.isEnabled = enabled; this.write(() => (enabled ? AsyncStorage.removeItem(DISABLED_KEY) : AsyncStorage.setItem(DISABLED_KEY, "1"))); if (enabled) return; this.anonymousId = null; this.userId = null; this.queue = []; this.write(() => AsyncStorage.removeItem(ANONYMOUS_ID_KEY)); this.write(() => AsyncStorage.removeItem(USER_ID_KEY)); this.write(() => AsyncStorage.removeItem(QUEUE_KEY)); }); } /** Records an event. Cheap; never blocks on the network. Does nothing while tracking is off. */ track(name: string, properties: EventProperties = {}): void { if (!SUPPORTED) return; // The ID and time are fixed now, even if stored state is still loading. const eventId = uuidV4(); const occurredAt = new Date().toISOString(); const props = { ...properties }; this.whenLoaded(() => { if (!this.isEnabled) return; const anonymousId = this.anonymousId ?? this.newAnonymousId(); this.queue.push({ event_id: eventId, name, anonymous_id: anonymousId, user_id: this.userId, occurred_at: occurredAt, properties: props, context: this.context(), }); if (this.queue.length > MAX_QUEUE) this.queue.splice(0, this.queue.length - MAX_QUEUE); this.persistQueue(); if (this.queue.length >= FLUSH_AT) void this.flush(); }); } /** Call after the user signs in to your app. Use your own stable user ID, never an email. */ identify(userId: string): void { this.whenLoaded(() => { if (!this.isEnabled) return; this.userId = userId; this.write(() => AsyncStorage.setItem(USER_ID_KEY, userId)); }); } /** Call on sign-out: later events belong to a new anonymous person. */ reset(): void { this.whenLoaded(() => { this.userId = null; this.anonymousId = null; this.write(() => AsyncStorage.removeItem(USER_ID_KEY)); this.write(() => AsyncStorage.removeItem(ANONYMOUS_ID_KEY)); }); } /** Sends queued events. Does nothing while waiting out a retry delay. */ async flush(): Promise { if (!SUPPORTED) return; await this.load(); const writeKey = this.writeKey; if (!this.isEnabled || this.isFlushing || writeKey === null || this.queue.length === 0) return; if (this.retryAt > Date.now()) return; this.isFlushing = true; try { while (this.queue.length > 0) { const batch = this.queue.slice(0, MAX_BATCH); const environment = this.environment; const events = batch.map((event) => event.context.environment !== undefined || environment === undefined ? event : { ...event, context: { ...event.context, environment } }, ); let response: Response; const abort = new AbortController(); const timeout = setTimeout(() => abort.abort(), REQUEST_TIMEOUT_MS); try { response = await fetch(ENDPOINT, { method: "POST", headers: { "Content-Type": "application/json", "X-Write-Key": writeKey }, body: JSON.stringify({ events }), signal: abort.signal, }); } catch { this.delayRetry(null); // offline: keep the queue return; } finally { clearTimeout(timeout); } if (!this.isEnabled) return; // turned off while sending: the queue is already gone const status = response.status; if (status === 429 || status >= 500) { const header = response.headers.get("Retry-After"); const retryAfter = header === null ? Number.NaN : Number(header); this.delayRetry(status === 429 && retryAfter >= 0 ? retryAfter : null); // keep the queue return; } this.retryAt = 0; this.backoffSeconds = 0; if (__DEV__) await report(status, response); // 2xx: stored. Other 4xx: retrying the same batch cannot succeed. const sent = new Set(batch.map((event) => event.event_id)); this.queue = this.queue.filter((event) => !sent.has(event.event_id)); this.persistQueue(); } } finally { this.isFlushing = false; } } /** Waits `seconds` when the server says so, otherwise 30 s, 60 s, 120 s… up to 10 minutes. */ private delayRetry(seconds: number | null): void { this.backoffSeconds = Math.min(Math.max(this.backoffSeconds * 2, 30), 600); this.retryAt = Date.now() + (seconds ?? this.backoffSeconds) * 1000; } private newAnonymousId(): string { const id = uuidV4(); this.anonymousId = id; this.write(() => AsyncStorage.setItem(ANONYMOUS_ID_KEY, id)); return id; } private context(): Context { this.cachedContext ??= { app_version: DeviceInfo.getVersion(), build: DeviceInfo.getBuildNumber(), os_version: DeviceInfo.getSystemVersion(), device_model: DeviceInfo.getDeviceId(), // hardware identifier, e.g. "iPhone16,2" locale: deviceLocale(), }; return this.cachedContext; } private whenLoaded(operation: () => void): void { if (!SUPPORTED) return; if (this.isLoaded) { operation(); return; } this.pending.push(operation); void this.load(); } private load(): Promise { this.loading ??= this.readStoredState(); return this.loading; } private async readStoredState(): Promise { try { const [disabled, anonymousId, userId, queue] = await Promise.all([ AsyncStorage.getItem(DISABLED_KEY), AsyncStorage.getItem(ANONYMOUS_ID_KEY), AsyncStorage.getItem(USER_ID_KEY), AsyncStorage.getItem(QUEUE_KEY), ]); this.isEnabled = disabled === null; this.anonymousId = anonymousId; // created on the first tracked event this.userId = userId; const stored: unknown = queue === null ? [] : JSON.parse(queue); if (Array.isArray(stored)) this.queue = stored as Event[]; } catch { // Unreadable storage: start with an empty queue. } this.isLoaded = true; // Calls made while loading run now, in order; their events go after the stored ones. const pending = this.pending; this.pending = []; for (const operation of pending) operation(); } /** Saves the queue once per batch of changes, after the writes already waiting. */ private persistQueue(): void { if (this.queueWriteScheduled) return; this.queueWriteScheduled = true; this.write(() => { this.queueWriteScheduled = false; return AsyncStorage.setItem(QUEUE_KEY, JSON.stringify(this.queue)); }); } /** Storage writes run one after another, so they land in the order they were made. */ private write(operation: () => Promise): void { this.writes = this.writes.then(operation).catch(() => undefined); } } /** Development builds only: logs dropped batches and rejected or clamped events to the console. */ async function report(status: number, response: Response): Promise { let json: Record = {}; try { const parsed: unknown = await response.json(); if (parsed !== null && typeof parsed === "object") json = parsed as Record; } catch { // Not JSON: log the status alone. } if (status < 200 || status >= 300) { console.log(`[EventTracker] HTTP ${status}, batch dropped:`, json); return; } for (const key of ["rejected", "clamped"]) { const items = json[key]; if (Array.isArray(items) && items.length > 0) console.log(`[EventTracker] ${key}:`, items); } } /** A random UUID v4. Hermes has no crypto.randomUUID, so it is built from random bytes. */ function uuidV4(): string { const bytes = new Uint8Array(16); const crypto = (globalThis as { crypto?: { getRandomValues?: (array: Uint8Array) => Uint8Array } }).crypto; if (crypto?.getRandomValues) { crypto.getRandomValues(bytes); } else { for (let i = 0; i < bytes.length; i++) bytes[i] = Math.floor(Math.random() * 256); } let nibble = 0; return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (char) => { const byte = bytes[nibble >> 1] ?? 0; const value = nibble % 2 === 0 ? byte >> 4 : byte & 0x0f; nibble++; return (char === "x" ? value : (value & 0x3) | 0x8).toString(16); }); } /** The device locale as `language_REGION`, e.g. "en_US" (or just "en" when there is no region). */ function deviceLocale(): string { try { const tag = Intl.DateTimeFormat().resolvedOptions().locale; // e.g. "en-US", "zh-Hans-CN" const [language = "", ...subtags] = (tag.split("-u-")[0] ?? "").split("-"); const region = subtags.find((part) => /^([A-Z]{2}|\d{3})$/.test(part)); return region ? `${language}_${region}` : language; } catch { return ""; } } export const EventTracker = new Tracker(); ``` ### 5.1 Wire it up Configure the tracker and send the cold `app_opened` once per launch, at module scope of the app's root file, so neither runs again on a re-render or twice under `StrictMode`. Bare React Native: `App.tsx`. Expo Router: `app/_layout.tsx`. ```tsx import { useEffect } from "react"; import { AppState } from "react-native"; import { EventTracker } from "./eventTracker"; // Module scope: runs once per launch. EventTracker.configure("YOUR_WRITE_KEY"); EventTracker.track("app_opened", { source: "cold" }); export default function App() { useEffect(() => { let wasInBackground = false; const subscription = AppState.addEventListener("change", (state) => { if (state === "background") { wasInBackground = true; void EventTracker.flush(); } else if (state === "active" && wasInBackground) { wasInBackground = false; EventTracker.track("app_opened", { source: "warm" }); } }); return () => subscription.remove(); }, []); return ; } ``` `app_opened` is sent on returning from background only, not on every `active`: system alerts, Control Center and Face ID make the app `inactive` and then `active` again without it ever going to background. In development, Fast Refresh can run the module scope again after you edit that file, which sends an extra cold `app_opened`. Those events are marked `debug` and stay out of the default view. **Telling TestFlight from the App Store.** If the app's build config already knows which channel a release build is for (for example an environment variable set per EAS build profile or per Xcode scheme), pass it to `configure`. Development builds ignore it and stay `debug`. ```typescript EventTracker.configure("YOUR_WRITE_KEY", { environment: IS_TESTFLIGHT_BUILD ? "testflight" : "app_store", }); ``` `IS_TESTFLIGHT_BUILD` stands for whatever the app's config provides. Without such a value, leave `environment` out. ### 5.2 Track events ```typescript import { EventTracker } from "./eventTracker"; EventTracker.track("paywall_viewed", { placement: "onboarding" }); EventTracker.track("onboarding_completed", { duration_s: 42 }); // After sign-in / sign-out in your app: EventTracker.identify(user.id); EventTracker.reset(); // Consent or an in-app "Share analytics" toggle: call it at launch, before configure and the first track, // with the user's current choice, and again whenever the choice changes. EventTracker.setEnabled(userAllowsAnalytics); // Support screen: show this so a user can ask for their data to be deleted (null if nothing was tracked yet). const installId = await EventTracker.currentAnonymousId(); ``` `track`, `identify`, `reset` and `setEnabled` return at once and can be called from any code, including render handlers and button callbacks. `flush` and `currentAnonymousId` return promises. If tracking waits for consent, call `setEnabled` before the launch `app_opened` in [§5.1](#51-wire-it-up); while tracking is off, that call does nothing and no ID is created. If the choice is stored asynchronously, still call `setEnabled(false)` first at module scope and `setEnabled(true)` once the stored choice says yes: calls take effect in the order they are made. Property values are typed `EventValue`: `string | number | boolean | null`. TypeScript rejects objects and arrays. **Purchases.** Track purchases in the purchase flow, where the user taps buy, around the purchase call of whatever the app uses (react-native-iap, RevenueCat or another library). Do not track them in a listener or callback that also delivers restores, renewals or purchases from other devices. The wrapper below takes the app's purchase call as a function that reports one of four outcomes. ```typescript import { EventTracker } from "./eventTracker"; export type PurchaseOutcome = "success" | "cancelled" | "pending" | "error"; /** * `purchase` is the app's own purchase call, mapped to an outcome: * completed and verified → "success"; the user cancelled → "cancelled"; * Ask to Buy or other deferred approval → "pending"; anything else → "error" (or throw). */ export async function buy( product: { id: string; price: number; currency: string }, startsTrial: boolean, purchase: () => Promise, ): Promise { const base = { product_id: product.id }; EventTracker.track("purchase_started", base); let outcome: PurchaseOutcome; try { outcome = await purchase(); } catch { outcome = "error"; } switch (outcome) { case "success": EventTracker.track("purchase_completed", { ...base, price: product.price, currency: product.currency, trial: startsTrial, }); if (startsTrial) EventTracker.track("trial_started", base); break; case "cancelled": EventTracker.track("purchase_failed", { ...base, reason: "cancelled" }); break; case "error": EventTracker.track("purchase_failed", { ...base, reason: "failed" }); break; case "pending": break; // Ask to Buy or extra approval: not completed yet, track nothing } return outcome; } ``` Call it from the buy button with the product the paywall shows and a function that runs the library's purchase method and maps its result: ```typescript const outcome = await buy(product, startsTrial, async () => { const result = await yourPurchaseCall(product.id); // the library's purchase method return toPurchaseOutcome(result); // "success" | "cancelled" | "pending" | "error" }); ``` `product.price` is the price as a number and `product.currency` the ISO 4217 currency code (`"USD"`), both from the library's product object. `startsTrial` is whatever your paywall already knows: true when this purchase starts a free trial. Many libraries report a user cancel as a thrown error with a cancel flag or error code; map that to `"cancelled"`, not `"error"`. If the library reports the result only through a purchase listener, track `purchase_completed` only for the purchase the user just started in this flow. ## 6. What to track Funnels are only as good as the events behind them. Start with the steps below and add more as questions come up. **Naming rules** - `snake_case`, `object_action`, past tense: `paywall_viewed`, `purchase_completed`. - One name per action. Put variations in properties (`paywall_viewed` with `placement: "settings"`), not in the name (`settings_paywall_viewed`). - Never put IDs, dates or user data in the name. - Where you want to split a funnel by a property, give it a short list of fixed values (`plan: "yearly"`), not free text. The dashboard shows the top 10 values and groups the rest as "Other". - Names and property values are case-sensitive: `Paywall_Viewed` and `paywall_viewed` are two different events. **Recommended starter set** Track the events whose flow exists in your app; skip the rest. Properties marked *optional* can be left out. | Event | When | Properties | |---|---|---| | `app_opened` | App launch and every return from background (the [§5.1](#51-wire-it-up) wiring sends it) | `source` (`"cold"` launch, `"warm"` return) | | `onboarding_started` | First onboarding screen shown | | | `onboarding_completed` | Last onboarding step done | `duration_s` *optional* (number) | | `signup_completed` | Account created in your app | `method` (`"apple"`, `"google"`, `"email"`) | | `paywall_viewed` | Paywall shown | `placement` (where it was shown: `"onboarding"`, `"settings"`, `"feature_gate"`), `paywall_id` *optional* | | `purchase_started` | User taps buy | `product_id` | | `purchase_completed` | Purchase succeeded and verified, in the purchase flow ([§5.2](#52-track-events)). Includes purchases that start a free trial | `product_id`, `price` (number), `currency`, `trial` (boolean) | | `purchase_failed` | User cancelled, or the purchase failed. Ask to Buy (pending) is neither: track nothing | `product_id`, `reason` (`"cancelled"`, `"failed"`) | | `trial_started` | Sent **in addition to** `purchase_completed` when that purchase starts a free trial | `product_id` | | `purchase_restored` | Restore purchases found an active subscription | `product_id` *optional* | | Your core action | The one thing your app is for. Name it for that action: `scan_completed`, `workout_finished`, `photo_exported` | what describes it | **What events from the app cannot show.** Renewals, free trials that turn into paid subscriptions, cancellations and refunds happen at Apple, usually while your app is closed. The app never sees them, so they are not in these events, and funnels here end at the purchase or the trial start. **Example funnels these enable** | Funnel | Steps | Window | What it answers | |---|---|---|---| | First session | `onboarding_started → onboarding_completed → paywall_viewed (placement = onboarding) → purchase_completed` | 1 day | How many new users reach the paywall and buy | | Paywall conversion | `paywall_viewed → purchase_started → purchase_completed`, broken down by `placement` | 1 hour | Which paywall placement converts best, and whether people drop at the price or at Apple's sheet | | Activation | `onboarding_completed → scan_completed` (your core action) | 1 day | How many new users get to the point of the app | ## 7. Privacy This section is guidance, not legal advice. You know what your app sends and where your users are, so the final decisions are yours, ideally with your own counsel. Privacy contact for everything in this section: `privacy@app-store-operator.com`. ### 7.1 What App Store Operator receives - Event names and their properties. - `anonymous_id`: a random UUID the reference code creates with the first event tracked while tracking is on, and keeps in AsyncStorage for that install until tracking is turned off or `reset()` is called. It is not the IDFA or any other identifier shared with other apps. - `user_id`, only if you call `identify`. - The device context in [§4.3](#43-event-object): app version, build, OS version, device model, locale and, when known, build environment. - The country, derived from the request's network location (see [§7.3](#73-ip-address-and-country)). Only iOS installs send anything: on Android the reference code sends nothing. **Never send** names, emails, phone numbers, precise location, the IDFA, or free text typed by the user, whether in event names, properties or `user_id`. `user_id` must be your app's own internal ID (for example a database key), not an email, a phone number, or an ID another company assigned. ### 7.2 Roles and service providers - **Roles.** For the events your app sends, you are the data controller (under KVKK, *veri sorumlusu*): you decide what is collected and why. Nefarius, which runs App Store Operator, processes the events on your behalf as your data processor (under KVKK, *veri işleyen*), to store them and show them to you in the dashboard. - **What we do not do.** We do not sell event data, use it for advertising, or share it with other customers. - **Service providers (subprocessors).** Like any hosted service, we rely on providers that handle event data only on our behalf: - **Cloudflare**: network delivery and security. Every request from your app passes through it. - **Our server hosting provider**: runs the servers and the database where events are stored. - **Locations.** Cloudflare operates worldwide, so a request may be handled outside your users' country. - **Data processing agreement (DPA).** If you need a DPA (for example under GDPR Article 28), the current list of service providers with their locations, or details of the safeguards for international transfers, write to the privacy contact above. ### 7.3 IP address and country Your app's requests reach us through Cloudflare, which needs the IP address to deliver them and looks up the country from it. App Store Operator keeps only the country (no city or region) and never stores or logs the IP address. ### 7.4 Retention and deletion requests - Events are kept for 13 months, then deleted automatically. - Deleting one person's events from the dashboard is not available yet. Until it is, when a user asks you to delete their data (for example under GDPR Article 17 or KVKK Article 11), email the privacy contact above from the address of a member of your App Store Operator workspace, with: - the app's name as shown in the dashboard; - the person's `user_id`, and/or their `anonymous_id`. A `user_id` also covers every `anonymous_id` linked to it. For users without an account, your app can show the `anonymous_id` from `await EventTracker.currentAnonymousId()`, for example on a support screen ([§5.2](#52-track-events)). Read it before calling `setEnabled(false)` or `reset()`: both delete it from the device, and without it we cannot find that install's events. - We delete every event with those IDs and confirm by email. Send requests promptly: you have your own deadline to answer the user (generally one month under GDPR, 30 days under KVKK). - Requests from anyone who is not a member of the workspace are not acted on; we refer the person to you. ### 7.5 Your privacy policy and consent - **Privacy policy.** Your app's privacy policy should say that you collect usage analytics, what data that includes (§7.1), that a service provider (App Store Operator, run by Nefarius) processes it for you, and that it is kept for 13 months. - **Legal basis and consent.** You choose the legal basis for analytics and whether you need your users' consent first. In the EU and UK, storing or reading an identifier on the device for analytics often requires consent; under KVKK you must at least inform users. If you need consent, call `EventTracker.setEnabled(false)` at launch, before anything else, until the user agrees, then `EventTracker.setEnabled(true)` ([§5.2](#52-track-events)). While tracking is off, no ID or event is stored on the device (only the off setting itself) and nothing is sent. The tracker creates its `anonymous_id` only with the first event tracked while it is on. If the user later withdraws consent, `setEnabled(false)` stops tracking and deletes the IDs and unsent events on the device. It does not delete events already sent: if consent was your only legal basis, or the user asks for deletion, request it through [§7.4](#74-retention-and-deletion-requests), reading `currentAnonymousId()` first. ### 7.6 App Tracking Transparency App Store Operator does not combine your events with data from other companies' apps, websites or offline sources for advertising or ad measurement, does not share them with data brokers, and does not use the device context to fingerprint devices. On its own, therefore, the integration is not tracking as Apple defines it and does not require the App Tracking Transparency (ATT) prompt. ATT is decided for your app as a whole, not per integration. If your app, or another SDK in it, links these events or your `user_id` with other companies' data for advertising or ad measurement, or shares them with a data broker, that is tracking: you need the user's ATT permission first, and your privacy label must say the data is used to track. See Apple's [User Privacy and Data Use](https://developer.apple.com/app-store/user-privacy-and-data-use/). ### 7.7 App Store privacy label and privacy manifest You answer Apple's privacy questions for the whole app, and Apple asks you to include data collected by third-party code you add, which includes this code. For the data App Store Operator receives, the typical answers are: | Apple data type | Declare when | Purpose | |---|---|---| | Usage Data → Product Interaction | Always | Analytics | | Identifiers → Device ID | Always: `anonymous_id` is a persistent per-install identifier | Analytics | | Location → Coarse Location | Always: the country is derived from the user's network location. It is coarser than Apple's examples, but declaring it is the safer answer | Analytics | | Purchases → Purchase History | If you track the purchase events in §6 | Analytics | | Identifiers → User ID | If you call `identify` or send `user_id` | Analytics | - **Linked to You.** If you send `user_id`, declare every row above as *Linked to You*: the events are joined to an account ID in your system. If you never send `user_id` and do not connect the events to an account or other identifying data anywhere else, the data is tied only to a random install ID and you may be able to answer *Not Linked to You*. When in doubt, answer *Linked to You*. - **Tracking.** *Not used to track you*, unless your app tracks as described in §7.6. - **Privacy manifest.** The reference code is JavaScript and calls no API Apple requires a reason for itself, but the native code of the two packages does, and each package ships its own `PrivacyInfo.xcprivacy` declaring it. In the versions current when this guide was written, `@react-native-async-storage/async-storage` declares file timestamp (`NSPrivacyAccessedAPICategoryFileTimestamp`, `C617.1`), and `react-native-device-info` declares `UserDefaults` (`CA92.1`), file timestamp (`C617.1`), system boot time (`NSPrivacyAccessedAPICategorySystemBootTime`, `35F9.1`) and disk space (`NSPrivacyAccessedAPICategoryDiskSpace`, `85F4.1`). What you still have to check: - Archive the app in Xcode and generate its privacy report (Organizer → right-click the archive → **Generate Privacy Report**). It should list those reasons. If it does not, add them to the app's own manifest: in bare React Native, `ios//PrivacyInfo.xcprivacy` (the React Native template creates it); in Expo, `ios.privacyManifests` in the app config, then prebuild again. - The collected data types in the app's own manifest (`NSPrivacyCollectedDataTypes`) should match your label. The packages declare none, because collecting events is what your app does with them. - After upgrading either package, look at its `PrivacyInfo.xcprivacy` again: the declared reasons can change. Apple's definitions: [App privacy details on the App Store](https://developer.apple.com/app-store/app-privacy-details/) and [Privacy manifest files](https://developer.apple.com/documentation/bundleresources/privacy-manifest-files). ### 7.8 Apps for children Apple's [App Review Guidelines](https://developer.apple.com/app-store/review/guidelines/) (1.3 and 5.1.4) do not allow third-party analytics in Kids Category apps, except in limited cases where the service collects no identifiable information about children, including device information. App Store Operator receives a persistent install ID, the device model and the country, so **do not add it to an app in the Kids Category**. For other apps aimed at children, check the rules that apply to you (for example COPPA in the US, or GDPR rules on children's consent) with your counsel before integrating. ## 8. Verify and troubleshoot 1. Run the iOS app (simulator or device, a debug build), trigger a few events, then send it to background (that sends the queue). 2. Dashboard → your app → **Events → Live**: your events appear within seconds. 3. **Events → Catalog** lists each event name with its property keys. Check the names and keys are the ones you meant. **Test builds.** Each app has one write key, used by test builds and App Store builds alike. The reference code marks every event from a development build (`__DEV__`) as `debug`. Release builds, including TestFlight builds, carry the `environment` passed to `configure` ([§5.1](#51-wire-it-up)); without it they carry none and count as App Store events, so TestFlight runs then show in the default view. By default the dashboard shows `app_store` events and events with no environment; to see your development runs, switch the environment filter to **All builds**. The curl test sends no environment, so it shows in the default view; find it by its `anonymous_id`, `curl-test`. | Symptom | Likely cause | |---|---| | Nothing in Live | Wrong key (`401`); `configure` never called; the app ran on Android (the tracker does nothing there); or fewer than 20 events queued and the app has not gone to background yet (wait 30 s) | | `401 invalid_write_key` | Key typo; the key was rotated more than 30 days ago; the old key was revoked ([§3.1](#31-rotating-the-key)); or the app or its App Store Connect connection was removed from App Store Operator | | Event missing, others present | Rejected. In a development build the Metro / JS console shows `[EventTracker] rejected: …` with the code ([§4.5](#45-errors)) | | Nothing in Live from a test build | The default view shows App Store events and events with no environment: switch the environment filter to **All builds** | | App fails at launch with a native module error from AsyncStorage or DeviceInfo (module is `null` or not found) | The iOS app was not rebuilt after installing the packages: run `npx pod-install` and rebuild, or make a new Expo development build. Expo Go cannot run `react-native-device-info` | | Events arrive late in bursts | Over a rate limit (`429`), or the server or network was down; the reference code keeps them and sends them later | | Wrong times | Device clock far off: times more than 7 days in the past or 5 minutes in the future are replaced by the time we received the event | | Same person counted twice in a funnel | `reset()` called when it should not be, or `identify` called with different IDs for one user | | Funnel step is zero | Step's event name or property filter does not match exactly (names and values are case-sensitive) | | Extra cold `app_opened` in development | Fast Refresh ran the module scope again ([§5.1](#51-wire-it-up)); development events are marked `debug` | ## 9. Done checklist The integration is done when every line is true. When you report, give the file and line for each code item; mark an item *not applicable* with the reason. The API is live, so nothing is left pending: run the end-to-end check too. - [ ] `@react-native-async-storage/async-storage` and `react-native-device-info` are installed (pods installed, or a new Expo development build), and no other dependency was added. - [ ] `eventTracker.ts` is in the app's source, unchanged from §5, and the iOS app builds and launches. - [ ] `configure(...)` runs once at launch, at module scope, with this app's real key; the text `YOUR_WRITE_KEY` appears nowhere in the project. - [ ] `EventTracker.flush()` runs when `AppState` changes to `background`. - [ ] `app_opened` is tracked at launch (`source: "cold"`) and on every return from background (`source: "warm"`), not on every `active`. - [ ] Every §6 event whose flow exists in this app is tracked, with the listed properties. Report each one as `event → file:line`, and list the §6 events you skipped and why. - [ ] Purchase events are tracked in the purchase flow, around the purchase call, not in a listener that also delivers restores or renewals. - [ ] Every event name matches `^[A-Za-z0-9_.:-]{1,64}$` and follows the §6 naming rules. - [ ] No `track` call sends a name, email, phone number, precise location, IDFA or text the user typed. - [ ] If the app has accounts: `identify` is called after sign-in with the app's own user ID, and `reset` after sign-out. Otherwise neither is called. - [ ] *End to end:* the §3 curl test with this app's key returns `accepted: 1`; a debug run of the iOS app shows no rejected events or dropped batches in the Metro / JS console; and its events appear in Dashboard → Events → Live (**All builds**). - [ ] *Developer:* the list of events and properties above was handed to the developer to check, against §7, the App Store privacy label, the required-reason entries in the app's privacy report ([§7.7](#77-app-store-privacy-label-and-privacy-manifest)), the app's privacy policy and any consent requirement. The app is not in the Kids Category.