# Interads

Interads is the internal cross-promotion ad hub for Intercode's apps (2meet4free, Date.Mom, MetalDate, Booster+, Five Tibetan Rites, Luseed, Yourricane…). Each app can **show** ads for the other apps (it is a *host*) and can **be advertised** in them (it is an *advertiser*). The hub picks the ad, counts views and clicks, sends the click to the right store or website, and attributes installs and conversions back to the ad.

- Base URL: `https://interads.intercode.info`
- API: `https://interads.intercode.info/api/v1` (Bearer token)
- This guide as Markdown, for AI agents: `https://interads.intercode.info/docs.md`
- Version 0.1.0

> **If you are an AI agent working on one app's codebase:** read "Quick start for an app's AI" first, then the sections for the platforms you work on. Everything you need is in this file. You have a token scoped to your app; the rules matrix (which app may advertise where) is set by the admin, not by you.

## Quick start for an app's AI

You were given `INTERADS_URL` (= `https://interads.intercode.info`) and `INTERADS_TOKEN` (starts with `ia_`). Do this, in order:

1. `GET /api/v1/me` to see which app your token manages and what it can do.
2. **Destinations** (where clicks on *your* app's ads land): `PUT /api/v1/apps/{your-app}/destinations/{platform}` for every platform your app exists on: `android` (package name), `ios` (numeric App Store id), `macos`, `web` (marketing site), `webapp` (web version of the app), `windows`, `linux`.
3. **Install attribution in your app** (so the hub can credit installs to ads): Android install referrer, iOS first-open with `identifierForVendor`, web landing `hub_click` parameter. See "Measuring installs and conversions".
4. **Placements** (ad slots inside *your* app, where other apps' ads show): `POST /api/v1/apps/{your-app}/placements`, then embed the slot (iframe on web, WebView or JSON on native). See "Showing ads in your app".
5. **Campaign** for your app: `POST /api/v1/campaigns` with one creative per language. Upload images with `POST /api/v1/assets` if you have no public URL for them.
6. `GET /api/v1/campaigns/{id}/eligibility` tells you exactly where it can run and what is missing. Set `"status": "active"` when ready.
7. From your app's **backend**, report conversions (signup, purchase…) with `POST /api/v1/conversions` and the click id you stored.
8. Read results with `GET /api/v1/stats?role=advertiser` (your campaigns) or `role=host` (ads shown in your slots).

## Concepts

| Thing | What it is |
|---|---|
| App | One product (all its platforms). Has a `slug` like `booster-plus`, a `content_rating` (`everyone`, `teen`, `mature`). |
| Destination | Where a click on this app's ads lands, per viewer platform. Fallback order: the viewer's platform, then `webapp`, then `web`, then the app's `website_url`. |
| Placement | An ad slot inside a host app, e.g. `home-strip`, `session-end`. Has a `layout` (`auto`, `strip`, `card`, `panel`) and `max_ads` (1-6). |
| Campaign | Promotion of one app. Status `draft` → `active` ↔ `paused` → `archived`. Optional dates, `weight`, and targeting by viewer `platforms`, `countries`, `languages`. |
| Creative | The ad itself: headline, body, button text, icon, images, screenshots, accent color, one language (or none = any). |
| Rule | Whether advertiser X may show in host Y (optionally only in one placement). **Default is deny.** Only the admin or a global token can change rules. |
| Content rating | An advertiser rated above the host never shows there (a `mature` dating app never appears in an `everyone` wellness app), whatever the rules say. |
| Click id | 22-char random id minted on a click, passed to the destination as `hub_click` (web) or inside the Play `referrer`. Used to attribute conversions. |

**Targeting is contextual only**: the host app, the placement, the viewer's platform, language and country of the request. No user profile, no history, no advertising ID, no cookies. That is what lets the apps show and measure these ads without a consent prompt.

## Authentication and errors

Send `Authorization: Bearer ia_...` (or `X-Api-Key: ia_...`) on every `/api/v1` call. Bodies are JSON (`Content-Type: application/json`).

- An **app-scoped token** manages its own app: app details (not slug, rating or active), destinations, placements, campaigns, creatives, conversions, stats, uploads. It can read every app and the rules that involve its app.
- A **global token** can do everything, including creating apps, changing the rules matrix and creating tokens.

Errors are JSON with an HTTP status:

```json
{ "error": { "code": "validation_failed", "message": "Some fields are invalid.", "fields": { "headline": "Required." } } }
```

Codes: `unauthorized` (401), `forbidden` (403), `not_found` / `app_not_found` / `campaign_not_found` (404), `validation_failed` (422), `internal` (500). Fix the listed `fields` and retry.

## Showing ads in your app

### The slot URL

```
GET https://interads.intercode.info/serve?app={host-app}&placement={placement}&platform={platform}&lang={lang}
GET https://interads.intercode.info/serve.json?...same parameters...
```

| Parameter | Required | Meaning |
|---|---|---|
| `app` | yes | Slug of the app showing the ad (yours). |
| `placement` | yes | Placement slug. |
| `platform` | yes | Viewer platform: `android`, `ios`, `macos`, `windows`, `linux`, `web`, `webapp`. Decides which store the click goes to. |
| `lang` | recommended | UI language (ISO 639-1, `fr`, `en`). Defaults to `Accept-Language`. |
| `country` | optional | ISO alpha-2, if the app knows it. A `CF-IPCountry` header wins when present. |
| `layout` | optional | Force `strip`, `card` or `panel` instead of the placement's layout. |
| `n` | optional | How many ads (up to the placement's `max_ads`). |
| `exclude` | optional | Comma list of campaign ids not to show (e.g. the ones the app showed in the last minutes; keep that list in the app, not on the server). |
| `theme` | optional | `light` or `dark` (default follows the system). |
| `bg` | optional | Background: hex without `#` (e.g. `ffffff`) or `transparent`. |
| `target` | optional | Link target in HTML mode: `_top` (default), `_blank`, `_self`. |

The HTML is a complete, self-contained page meant for an iframe or a WebView. Layouts:

| Layout | Use it for | Looks like |
|---|---|---|
| `strip` | phone banners, 56-120 px tall | icon · headline · app name · button, one row |
| `card` | taller phone slots, 190 px+ | wide image on top, text, full-width button |
| `panel` | tablet and desktop, 560 px+ wide and 150 px+ tall | image left, text and screenshots right |
| `auto` (default) | anything | picks strip / card / panel from the slot's actual size and re-picks on resize or rotation |

Recommended slot sizes: phone strip 100% × 72-96 px; phone card 100% × 300-360 px; tablet/desktop panel 100% × 220-300 px. Use `auto` and give the slot a bigger height on large screens: the same placement then shows a strip on phones and a panel on tablets.

Every ad shows a disclosure label ("Ad · Intercode" / "Pub · Intercode") and a ⋯ link to report it (required by Apple for apps with ads).

An empty slot (no eligible ad) returns the page with no ad, header `X-Interads-Fill: 0`, and sends an `empty` message (below); collapse the slot when you get it.

### Web (iframe)

```html
<iframe id="ia-home" src="https://interads.intercode.info/serve?app=booster-plus&placement=home-strip&platform=web&lang=fr"
        title="Ad" loading="lazy" style="width:100%;height:88px;border:0;display:block"></iframe>
<script>
window.addEventListener('message', function (e) {
  if (e.origin !== 'https://interads.intercode.info'.replace(/^(https?:\/\/[^/]+).*/, '$1') || !e.data || !e.data.interads) return;
  if (e.data.type === 'empty') document.getElementById('ia-home').style.display = 'none';
});
</script>
```

Clicks navigate the top page through the hub (`target=_top`). For the **web version of an app** use `platform=webapp`; for a marketing website use `platform=web`. On iPhone/Android browsers you may pass `platform=ios`/`android` (detect from the user agent) so the click goes straight to the store.

Ad blockers: serve the iframe from your own domain if you can (a reverse proxy path such as `/p/` → `https://interads.intercode.info/`). The hub never uses the word "ad" in its paths.

### Android (WebView)

Load the slot in a `WebView` and hand clicks to the hub yourself, so store links open in the Play Store app and not inside the WebView. The page calls `InteradsBridge.postMessage(json)` with `{type: "click"|"report"|"filled"|"empty", url}` when the bridge exists.

```kotlin
// build.gradle: implementation("androidx.webkit:webkit:1.12.0") is not required; plain WebView works.
class InteradsSlot(private val webView: WebView, private val scope: CoroutineScope) {
    private val base = "https://interads.intercode.info"

    @SuppressLint("SetJavaScriptEnabled")
    fun load(app: String, placement: String, lang: String) {
        webView.settings.javaScriptEnabled = true
        webView.setBackgroundColor(Color.TRANSPARENT)
        webView.addJavascriptInterface(object {
            @JavascriptInterface
            fun postMessage(json: String) {
                val msg = JSONObject(json)
                when (msg.optString("type")) {
                    "click" -> scope.launch { openClick(msg.getString("url")) }
                    "report" -> openExternal(msg.getString("url"))
                    "empty" -> webView.post { webView.visibility = View.GONE }
                }
            }
        }, "InteradsBridge")
        webView.loadUrl("$base/serve?app=$app&placement=$placement&platform=android&lang=$lang&bg=transparent")
    }

    // POST to the click URL: the hub logs the click and answers {"url": "...", "click_id": "..."}.
    private suspend fun openClick(clickUrl: String) {
        val url = withContext(Dispatchers.IO) {
            val conn = URL(clickUrl).openConnection() as HttpURLConnection
            conn.requestMethod = "POST"
            conn.setRequestProperty("Content-Type", "application/json")
            conn.doOutput = true
            conn.outputStream.use { it.write("{}".toByteArray()) }
            JSONObject(conn.inputStream.bufferedReader().readText()).getString("url")
        }
        openExternal(url)
    }

    private fun openExternal(url: String) {
        val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        if (url.startsWith("https://play.google.com/")) intent.setPackage("com.android.vending")
        try { webView.context.startActivity(intent) } catch (e: ActivityNotFoundException) {
            webView.context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK))
        }
    }
}
```

### iOS / iPadOS / macOS (WKWebView)

Register a script message handler named `interads`; the page posts `{type, url}` to it. On a click, POST to the click URL **with `identifierForVendor`** so the advertised app can be credited at its first launch (no ATT prompt is needed: the vendor id is shared only between apps from the same App Store account, which Apple allows for analytics without tracking permission).

```swift
import UIKit
import WebKit

final class InteradsSlot: NSObject, WKScriptMessageHandler {
    let webView: WKWebView
    private let base = URL(string: "https://interads.intercode.info")!

    init(frame: CGRect) {
        let config = WKWebViewConfiguration()
        webView = WKWebView(frame: frame, configuration: config)
        super.init()
        config.userContentController.add(self, name: "interads")
        webView.isOpaque = false
        webView.backgroundColor = .clear
        webView.scrollView.isScrollEnabled = false
    }

    func load(app: String, placement: String, lang: String) {
        var c = URLComponents(url: base.appendingPathComponent("serve"), resolvingAgainstBaseURL: false)!
        c.queryItems = [.init(name: "app", value: app), .init(name: "placement", value: placement),
                        .init(name: "platform", value: "ios"), .init(name: "lang", value: lang),
                        .init(name: "bg", value: "transparent")]
        webView.load(URLRequest(url: c.url!))
    }

    func userContentController(_ uc: WKUserContentController, didReceive message: WKScriptMessage) {
        guard let body = message.body as? [String: Any], let type = body["type"] as? String else { return }
        switch type {
        case "click":
            guard let s = body["url"] as? String, let url = URL(string: s) else { return }
            Task { await openClick(url) }
        case "report":
            if let s = body["url"] as? String, let url = URL(string: s) { UIApplication.shared.open(url) }
        case "empty":
            webView.isHidden = true
        default: break
        }
    }

    private func openClick(_ clickURL: URL) async {
        var req = URLRequest(url: clickURL)
        req.httpMethod = "POST"
        req.setValue("application/json", forHTTPHeaderField: "Content-Type")
        let vendor = await UIDevice.current.identifierForVendor?.uuidString ?? ""
        req.httpBody = try? JSONSerialization.data(withJSONObject: ["vendor_id": vendor])
        guard let (data, _) = try? await URLSession.shared.data(for: req),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
              let s = json["url"] as? String, let dest = URL(string: s) else { return }
        await UIApplication.shared.open(dest)
    }
}
```

On macOS use `NSWorkspace.shared.open` and `platform=macos`. A SwiftUI app wraps `InteradsSlot.webView` in a `UIViewRepresentable`.

### Native rendering (JSON)

If a WebView is not wanted, call `/serve.json` and draw the ad yourself:

```json
{
  "ads": [{
    "campaign_id": 12, "creative_id": 31,
    "advertiser": { "slug": "luseed", "name": "Luseed", "icon_url": "https://…" },
    "headline": "Lucid dreams, one night at a time", "body": "…", "cta": "Try it",
    "icon_url": "https://…", "image_square_url": "https://…", "image_wide_url": "https://…",
    "screenshots": ["https://…"], "accent_color": "#6A3DE8",
    "label": "Ad · Intercode", "report_label": "Report", "destination_platform": "ios",
    "click_url": "https://interads.intercode.info/c/eyJ…", "view_url": "https://interads.intercode.info/v/eyJ…", "report_url": "https://interads.intercode.info/report/eyJ…"
  }],
  "layout": "auto", "placement": { "host": "booster-plus", "slug": "session-end", "layout": "auto", "max_ads": 1 }, "fill": true
}
```

Rules when rendering natively: show `label` and a way to open `report_url`; call `view_url` (POST, empty body) once when at least half the ad has been on screen for one second; on tap, POST to `click_url` (iOS: with `{"vendor_id": identifierForVendor}`) and open the returned `url`. Ad links stay valid for 24 hours.

### Clicks

`GET /c/{token}` answers `302` to the destination (web). `POST /c/{token}` answers `{"url": "...", "click_id": "..."}` (apps). A double tap within 10 seconds reuses the same click. Bots and link previewers are redirected without being counted.

## Measuring installs and conversions

The hub adds a click id to the destination, the advertised app reads it, and the app's backend reports conversions with it. Nothing else identifies the person.

| Click lands on | How the click id arrives | What the advertised app does |
|---|---|---|
| Google Play | inside the Play `referrer` (`…&hub_click=ID`) | read the Install Referrer once at first launch, POST it to `/open` |
| App Store / Mac App Store | cannot pass through the store | at first launch POST `identifierForVendor` to `/open` |
| Website or web app | `?utm_…&hub_click=ID` on the landing URL | store `hub_click` server-side (session or signup record) |

Attribution window: **7 days** from the click. Click rows are deleted after 30 days.

In **aggregate-only countries** (EU/EEA, UK, Switzerland by default) the hub mints no click id: views, clicks and installs are counted per campaign but cannot be tied to a conversion. `hub_click` is then absent; handle that.

### First open: `POST /open` (no token)

Called by the advertised app itself, once, on first launch.

```json
POST https://interads.intercode.info/open
{ "app": "luseed", "platform": "android", "referrer": "utm_source=interads&utm_medium=house&…&hub_click=6sK2…" }
```

or on iOS:

```json
{ "app": "luseed", "platform": "ios", "vendor_id": "E621E1F8-C36C-495A-93FC-0C247A3E6E5F" }
```

or with an id you already have: `{ "app": "luseed", "click_id": "6sK2…" }`.

Response: `{"matched": true, "click_id": "6sK2…", "matched_by": "click_id", "campaign_id": 12, "from_app": "booster-plus"}` or `{"matched": false, "click_id": null}`. It records an `install` conversion. **Save the returned `click_id`** and send it to your backend with the signup, so later conversions can be attributed.

Android (Play Install Referrer library `com.android.installreferrer:installreferrer:2.2`):

```kotlin
fun reportFirstOpen(context: Context, app: String) {
    val prefs = context.getSharedPreferences("interads", Context.MODE_PRIVATE)
    if (prefs.getBoolean("first_open_sent", false)) return
    val client = InstallReferrerClient.newBuilder(context).build()
    client.startConnection(object : InstallReferrerStateListener {
        override fun onInstallReferrerSetupFinished(code: Int) {
            if (code != InstallReferrerClient.InstallReferrerResponse.OK) { client.endConnection(); return }
            val referrer = client.installReferrer.installReferrer ?: ""
            client.endConnection()
            if (!referrer.contains("hub_click")) { prefs.edit().putBoolean("first_open_sent", true).apply(); return }
            thread {
                val conn = URL("https://interads.intercode.info/open").openConnection() as HttpURLConnection
                conn.requestMethod = "POST"; conn.doOutput = true
                conn.setRequestProperty("Content-Type", "application/json")
                conn.outputStream.use { it.write(JSONObject(mapOf("app" to app, "platform" to "android", "referrer" to referrer)).toString().toByteArray()) }
                val clickId = JSONObject(conn.inputStream.bufferedReader().readText()).optString("click_id", "")
                prefs.edit().putBoolean("first_open_sent", true).putString("click_id", clickId).apply()
            }
        }
        override fun onInstallReferrerServiceDisconnected() {}
    })
}
```

If the app already reads the install referrer for Google Ads (`gclid`), use the same read: a referrer contains either `gclid` or `hub_click`.

iOS:

```swift
func reportFirstOpen(app: String) async {
    let d = UserDefaults.standard
    guard !d.bool(forKey: "interads.firstOpenSent"), let vendor = UIDevice.current.identifierForVendor?.uuidString else { return }
    var req = URLRequest(url: URL(string: "https://interads.intercode.info/open")!)
    req.httpMethod = "POST"
    req.setValue("application/json", forHTTPHeaderField: "Content-Type")
    req.httpBody = try? JSONSerialization.data(withJSONObject: ["app": app, "platform": "ios", "vendor_id": vendor])
    if let (data, _) = try? await URLSession.shared.data(for: req),
       let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
        d.set(json["click_id"] as? String, forKey: "interads.clickId")
        d.set(true, forKey: "interads.firstOpenSent")
    }
}
```

The vendor id matches only if the click happened in another app from the same Apple developer account (Intercode inc.) on the same device. Development builds installed from Xcode may report a different vendor id; test with TestFlight builds.

Web landing (PHP):

```php
// On any landing page: keep the hub click id for the visit (server-side, no cookie needed if you have a session).
if (isset($_GET['hub_click']) && preg_match('/^[A-Za-z0-9]{10,32}$/', $_GET['hub_click'])) {
    $_SESSION['hub_click'] = $_GET['hub_click'];
}
// At signup: save it with the new account ($user->hub_click), then report the conversion from the backend.
```

### Conversions: `POST /api/v1/conversions` (token, from your backend)

```json
POST https://interads.intercode.info/api/v1/conversions
Authorization: Bearer ia_...
{ "event": "signup", "click_id": "6sK2…", "external_id": "user-81723" }
```

| Field | Meaning |
|---|---|
| `event` | Lowercase name: `signup`, `purchase`, `subscribe`, `qualified`, `trial_start`… (letters, digits, `_`, max 32). `install` is recorded by `/open`. |
| `click_id` | From `hub_click`, the Play referrer or `/open`. Or send `referrer` (raw Play referrer) or `vendor_id` (iOS) instead. |
| `external_id` | Your own id for this conversion (order id, transaction id, user id). With it, every distinct id counts once; without it, one conversion per click per event. |
| `value`, `currency` | Optional revenue, e.g. `9.99`, `CAD`. |
| `occurred_at` | Optional ISO 8601 time, default now. |
| `app` | Only needed with a global token. |

Answers `201 {"attributed": true, "duplicate": false, "campaign_id": 12, …}`, `200 {"attributed": true, "duplicate": true}` for a repeat, or `200 {"attributed": false, "reason": "…"}` when no click matches (older than the window, other app, or aggregate-only country). Unattributed conversions are not stored.

### Existing click systems (e.g. 2meet4free)

If an app already tracks its own campaigns from URL parameters, give it a destination `url_template` with macros instead of the defaults:

```json
PUT /api/v1/apps/2meet4free/destinations/web
{ "url_template": "https://www.2meet4free.com/?src=interads&camp={campaign_id}&from={src_app}&slot={placement}&hub_click={click_id}" }
```

Macros (values are URL-encoded; `{utm}`, `{referrer}` and `{apple_query}` are inserted as-is):

| Macro | Value |
|---|---|
| `{click_id}` | Hub click id (empty in aggregate-only countries) |
| `{src_app}` | Slug of the app that showed the ad |
| `{placement}` | Placement slug |
| `{campaign}` / `{campaign_id}` | Campaign name slugified / numeric id |
| `{creative_id}` | Creative id |
| `{platform}` / `{country}` / `{lang}` | Viewer platform, country (ZZ if unknown), language |
| `{store_id}` | The destination's store id |
| `{utm}` | `utm_source=interads&utm_medium=house&utm_campaign=…&utm_content=…` |
| `{referrer}` | Play referrer value (utm + hub_click), already encoded |
| `{apple_query}` | `pt=…&ct=…&mt=8` for App Store links |

Default templates when `url_template` is empty: Android `https://play.google.com/store/apps/details?id={store_id}&referrer={referrer}`; iOS `https://apps.apple.com/app/id{store_id}?{apple_query}`; web and others: the app's website + `?{utm}&hub_click={click_id}`.

## Creating a campaign

```json
POST https://interads.intercode.info/api/v1/campaigns
Authorization: Bearer ia_...
{
  "name": "Luseed launch, winter 2026",
  "status": "draft",
  "languages": ["fr", "en"],
  "creatives": [
    { "language": "fr", "headline": "Rêvez lucide, une nuit à la fois", "body": "Journal de rêves, rappels et techniques guidées.", "cta": "Essayer",
      "icon_url": "https://…/icon-512.png", "image_wide_url": "https://…/wide-1200x675.jpg", "accent_color": "#6A3DE8",
      "screenshots": ["https://…/s1.png", "https://…/s2.png"] },
    { "language": "en", "headline": "Lucid dreams, one night at a time", "body": "Dream journal, reminders and guided techniques.", "cta": "Try it",
      "icon_url": "https://…/icon-512.png", "image_wide_url": "https://…/wide-1200x675.jpg", "accent_color": "#6A3DE8" }
  ]
}
```

The response contains the campaign and its `eligibility`. Then:

```json
PATCH https://interads.intercode.info/api/v1/campaigns/12
{ "status": "active" }
```

Campaign fields: `name` (required), `status`, `weight` (0-10000, default 100: relative share against other eligible campaigns), `starts_at`, `ends_at` (ISO 8601; UTC if no offset), `platforms` (viewer platforms; empty = all), `countries` (ISO alpha-2; empty = all), `languages` (empty = all), `notes`. With a global token add `"app": "luseed"`.

Creative fields and guidance:

| Field | Limit | Guidance |
|---|---|---|
| `headline` | 90, required | About 30 characters fit a phone strip. Say what the app does for the person. |
| `body` | 240 | Shown in cards and panels, hidden in strips. |
| `cta` | 30 | Button: "Install", "Try it", "Essayer". |
| `language` | ISO 639-1 or empty | One per creative. Selection: exact language, then empty, then `en` (if the campaign has no language targeting). |
| `icon_url` | URL | 1:1, 512 px+. Empty = the app's icon. |
| `image_wide_url` | URL | 16:9, 1200×675+. Used by cards and panels. |
| `image_square_url` | URL | 1:1, 1080 px. Fallback image. |
| `screenshots` | up to 8 URLs | Portrait screenshots, shown in large panels. |
| `accent_color` | `#RRGGBB` | Button and image backdrop color. |
| `weight` | 0-10000 | Rotation between creatives of the same language. |
| `active` | bool | `DELETE /api/v1/creatives/{id}` deactivates. |

Ads must be appropriate for the hosts' ratings and honest: no fake system alerts, no claims the app cannot back up. People can report ads; the admin reviews reports.

### Uploading images

```
POST https://interads.intercode.info/api/v1/assets            (multipart field "file")
POST https://interads.intercode.info/api/v1/assets            {"data_base64": "iVBORw0…"}
→ 201 {"url": "https://interads.intercode.info/uploads/2026/11/x.png", "width": 1200, "height": 675, "hint": "Wide 16:9: use as image_wide_url."}
```

PNG, JPEG, WebP or GIF, 2 MB max. SVG is refused.

## API reference

All paths are under `https://interads.intercode.info`. "Scoped" = allowed for an app-scoped token on its own app.

| Method & path | Who | Does |
|---|---|---|
| `GET /api/v1/me` | any | Token, scope and app |
| `GET /api/v1/macros` | any | Macros, platforms, layouts, ratings, statuses, stats dimensions |
| `GET /api/v1/apps` | any | List apps |
| `POST /api/v1/apps` | global | Create: `slug`, `name`, `website_url`, `icon_url`, `content_rating`, `description` |
| `GET /api/v1/apps/{app}` | any | App with destinations and placements |
| `PATCH /api/v1/apps/{app}` | scoped | Update name, description, website_url, icon_url (slug, content_rating, active: global) |
| `DELETE /api/v1/apps/{app}` | global | Delete app and its campaigns |
| `GET /api/v1/apps/{app}/destinations` | any | List |
| `PUT /api/v1/apps/{app}/destinations/{platform}` | scoped | Upsert `store_id`, `url_template`, `active`; answers with an `example_click_url` |
| `DELETE /api/v1/apps/{app}/destinations/{platform}` | scoped | Remove |
| `GET /api/v1/apps/{app}/placements` | any | List |
| `POST /api/v1/apps/{app}/placements` | scoped | Create `slug`, `name`, `layout`, `max_ads`; answers with an embed `snippet` |
| `PATCH /api/v1/apps/{app}/placements/{placement}` | scoped | Update name, layout, max_ads, active |
| `DELETE /api/v1/apps/{app}/placements/{placement}` | scoped | Delete |
| `GET /api/v1/apps/{app}/placements/{placement}/snippet` | any | Embed URLs and iframe |
| `GET /api/v1/campaigns?app=&status=&with=creatives` | scoped | List (scoped tokens see their app's only) |
| `POST /api/v1/campaigns` | scoped | Create (optionally with `creatives`) |
| `GET /api/v1/campaigns/{id}` | scoped | Campaign with creatives |
| `PATCH /api/v1/campaigns/{id}` | scoped | Update any campaign field |
| `DELETE /api/v1/campaigns/{id}` | scoped | Archive |
| `GET /api/v1/campaigns/{id}/eligibility` | scoped | Where it can run, what blocks it |
| `GET /api/v1/campaigns/{id}/creatives` | scoped | List |
| `POST /api/v1/campaigns/{id}/creatives` | scoped | Add |
| `GET/PATCH/DELETE /api/v1/creatives/{id}` | scoped | Read, update, deactivate |
| `GET /api/v1/rules?app=` | any | Rules involving the app, plus `can_advertise_in` / `can_show_ads_from` |
| `PUT /api/v1/rules` | global | `{host, advertiser, placement?, allowed}`; `allowed: null` removes the rule |
| `POST /api/v1/conversions` | scoped | Report a conversion |
| `GET /api/v1/stats` | scoped | See below |
| `POST /api/v1/assets` | scoped | Upload an image |
| `GET/POST /api/v1/tokens`, `DELETE /api/v1/tokens/{id}` | global | Manage tokens (`{name, app?}`) |
| `GET /serve`, `GET /serve.json` | public | The slot |
| `GET/POST /c/{token}` | public | Click |
| `POST /v/{token}` | public | View beacon |
| `POST /open` | public | First-open attribution |
| `GET /health` | public | Health check |

### Stats

```
GET https://interads.intercode.info/api/v1/stats?role=advertiser&from=2026-11-01&to=2026-11-30&group_by=day,campaign
```

- `role`: `advertiser` (your campaigns, wherever they ran), `host` (ads shown in your placements), default both.
- `group_by`: any of `day`, `advertiser_app`, `host_app`, `placement`, `campaign`, `creative`, `platform`, `country`.
- `campaign`: one campaign id. `app`: with a global token.
- Default period: the last 30 days (UTC).

```json
{ "from": "2026-11-01", "to": "2026-11-30", "group_by": ["campaign"],
  "totals": { "served": 1840, "views": 1502, "clicks": 41, "ctr": 0.0273, "conversions": { "install": 9, "signup": 4 }, "value": { "CAD": 1998 } },
  "rows": [ { "campaign": { "id": 12, "name": "Luseed launch" }, "served": 1840, "views": 1502, "clicks": 41, "ctr": 0.0273,
              "conversions": { "install": 9, "signup": 4 }, "value": { "CAD": 1998 } } ] }
```

`served` = ads returned by `/serve`; `views` = ads at least half visible for one second; `ctr` = clicks / views (or / served when no views were reported); `value` is in cents.

## Privacy model

What the hub stores:

- **Aggregated counters** per day, host app, placement, campaign, creative, viewer platform and country.
- **Click rows** for 30 days: random click id, where the click came from, the destination platform, country, and for iOS clicks a keyed hash of `identifierForVendor` (never the raw value).
- **Conversions** that matched a click: event name, your `external_id`, optional value, and the ad dimensions.

What the hub's database never stores or uses: IP addresses, user agents, cookies, advertising IDs (IDFA, GAID), app set ID, user profiles, or anything from inside the host app. Targeting uses only the request context. (The web server's access log still records requests like for any site; its retention is a server setting.)

What to keep doing in each app: mention in its privacy policy that it shows house ads for other Intercode apps and measures their clicks and installs; declare the matching items in the App Store privacy label and the Play data-safety form (usage data, "analytics", not linked to identity, not used for tracking). This is the developer's legal call; this design avoids identifiers that require consent prompts on iOS and Android, but Quebec Law 25 and EU rules should be checked by whoever is responsible for each app.

## Admin

The admin (`https://interads.intercode.info/admin`) is for a person: apps, destinations and placements, campaigns and creatives, the rules matrix, previews of every slot at phone, tablet and desktop sizes, stats, ad reports, tokens and an audit log of every change made by people and tokens.
