# offerswap.com API: full reference OfferSwap was called BuyGoLinks until 2026-11-20. Every `buygolinks.com` short link, campaign link, `/click` button, `t.js` tag and postback URL, and every call to `https://app.buygolinks.com/api/*`, keeps working unchanged. New links show on `offerswap.com`. Branded short links, campaign tracking and click and page view analytics. All endpoints listed below in a single document, optimized for LLM ingestion. The canonical machine-readable spec is `https://docs.offerswap.com/openapi.yaml`, and the page at `https://docs.offerswap.com/` is generated from it. Every endpoint here is also an MCP tool in `@offerswap/mcp`. ## Base URLs - API: `https://app.offerswap.com` - Short-link resolver (public, no auth): `https://offerswap.com/{code}` - Collection rotator (public, no auth): `https://offerswap.com/c/{alias}` ## Authentication All `/api/*` endpoints require a Bearer token. Two token shapes are accepted: 1. **Personal access token**: `bgl_<24-base62>`. Recommended for programmatic use. Create with `POST /api/api-keys`. The raw token is returned exactly once; we store only SHA-256(token). 2. **Supabase JWT**: issued to the SPA after login. Short-lived; not intended for backend integrations. Send as: ``` Authorization: Bearer ``` ## Error shape All errors are JSON: `{ "error": "" }`. Common HTTP statuses: - `400 bad_json | invalid_url | invalid_url_scheme | url_required | invalid_platform | invalid_pixel_id | invalid_alias | invalid_collection | no_changes | name_required` - `401 unauthorized` - `403 forbidden`: resource exists but isn't yours - `404 not_found` - `409 alias_taken`: rotator alias collision - `500 code_collision`: exhausted short-code attempts (extremely rare) --- ## Links ### `GET /api/links` List the caller's links with per-link click counts and current usage. Query params: `include_archived=1` to include archived links (default: only active). Response: ```json { "links": [ { "id": 42, "code": "aB3xY7zQ", "destination_url": "https://www.amazon.com/dp/B08N5WRWNW", "asin": "B08N5WRWNW", "title": "Echo Dot (4th Gen)", "source_label": "ig-bio", "product_image_url": "https://ckpegrzcpdknthpwlsqf.supabase.co/storage/v1/object/public/products/B08N5WRWNW-aB3xY7zQ.jpg", "collection_id": 3, "domain_id": 7, "short_domain": "go.acme.com", "created_at": "2026-05-27T18:00:00Z", "archived_at": null, "clicks": 128 } ], "short_domain": "go.acme.com", "usage": { "plan": "free", "links": { "used": 1, "limit": null }, "clicks_30d": { "used": 128, "limit": null } } } ``` Each link's `short_domain` is the hostname it resolves at: either one of the user's active custom domains (when `domain_id` is set) or `offerswap.com` otherwise. The top-level `short_domain` is the account default (the user's first active custom domain, falling back to `offerswap.com`); new links default to it. ### `POST /api/links` Create a short link. Body: ```json { "destination_url": "https://www.amazon.com/dp/B08N5WRWNW", "title": "Echo Dot", // optional, max 200 "source_label": "ig-bio", // optional, max 60, sanitized to [a-z0-9_-] "domain_id": 7 // optional; id of one of the user's active custom domains } ``` If `domain_id` is omitted the link is created under the user's first active custom domain, or `offerswap.com` if they have none. If `destination_url` is an Amazon `/dp/{ASIN}` URL, the server: - extracts the ASIN, - best-effort scrapes the product image + title (capped at ~6s), - rehosts the image to our Supabase Storage bucket. Response: ```json { "link": { /* Link object */, "clicks": 0, "short_domain": "go.acme.com" }, "short_url": "https://go.acme.com/aB3xY7zQ", "short_domain": "go.acme.com" } ``` ### `PATCH /api/links/{id}` Edit a link. Body (any subset): ```json { "destination_url": "https://new-target.com", "title": "...", "source_label": "...", "archived": true, "password": "secret", "domain_id": 7, "alias": "summer-sale", "phone_open": "browser" } ``` `phone_open`: On a phone, what a tap does: `browser` leaves Facebook's, Instagram's or TikTok's own in-app browser for Safari or Chrome first, `stay` loads it where they tapped and never opens an app, `app` or null is the default (an app destination such as Amazon opens its app, by way of Safari or Chrome when the tap was in an in-app browser). Also accepted on `POST /api/links`. `destination_url` repoints the link at a new http(s) target. The short code, alias, and click history are preserved, and the ASIN is re-extracted for Amazon `/dp/` URLs (cleared for non-Amazon URLs). Errors: `url_required`, `invalid_url`, `invalid_url_scheme`. `archived: true` sets `archived_at` to now; `archived: false` clears it. `password: ""` removes password protection. `domain_id: null` moves the link back to `offerswap.com`; any non-null value must reference one of the caller's active custom domains. The response includes `short_domain` so clients can re-render the short URL immediately. `alias` is an optional custom path segment that lives on the link's custom domain (e.g. `alias: "summer-sale"` → `https://click.example.com/summer-sale`). 1–32 chars; letters, numbers, hyphens, underscores; must start with a letter or number. Aliases are case-insensitive and unique within a (custom domain, alias) scope. Setting `alias` REPLACES any previous alias on this link. The old alias stops resolving immediately and is freed for any other link to claim. The link's original random `code` keeps working forever regardless. Pass `alias: ""` or `alias: null` to remove the alias. Changing `domain_id` automatically clears the alias (aliases are scoped per-domain). Errors: `invalid_alias`, `alias_in_use`, `alias_reserved`, `alias_requires_custom_domain`. ### `DELETE /api/links/{id}` Hard delete. Cascades to `link_clicks` via FK. Returns `{ "ok": true }`. ### `POST /api/links/{id}/refresh-image` Get or refresh a link's thumbnail. Amazon `/dp/` links get the Amazon product photo. Any other URL gets a screenshot of the page (1280x800, the first screen, taken in a headless browser with ad pixels and analytics blocked so it never counts as a visit), with the page's `og:image` or first image as the fallback. The image is stored on OfferSwap storage. Takes about 5 to 10 seconds. Useful when a link was created without an image (thumbnail shows a placeholder) or to refresh a stale one. On success returns `{ "found": true, "link": { ... } }` with the updated `product_image_url`. If no image could be fetched this attempt, returns `{ "found": false, "product_image_url": }` and the stored image is left untouched. No request body. ### `GET /api/links/{id}/pixels` / `PUT /api/links/{id}/pixels` Which tracking pixels fire when this link is clicked. `GET` returns `{ "pixel_ids": [12], "events": { "12": "ViewContent" }, "overridden": true }`. A link fires only the pixels picked for it, and none when none are picked (since 2026-11-13; an active pixel on the account no longer fires on every link). `overridden` is kept for older clients and no longer changes what fires. `events` maps a pixel id to the event this link fires it as, when that differs from the pixel's `default_event`. `PUT` replaces the selection: ```json { "pixel_ids": [12, 15], "overridden": true, "events": { "12": "ViewContent" } } ``` The link fires exactly these pixels, and `{ "pixel_ids": [] }` fires none. Every pixel must be yours (403 otherwise), and each event must be valid for its pixel's platform. ### `POST /api/links/{id}/collection` Assign a link to a collection, or detach it. Body: ```json { "collection_id": 3 } // or { "collection_id": null } to detach ``` --- ## Statistics Time windows are clamped to 1–90 days; default 14. ### `GET /api/stats/overview?days=14` Account-wide click stats in one round trip. Covers branded short-link **clicks only**. It does **not** include Tracker page views, site-property traffic, or campaign visits/conversions. For **page views** use `GET /api/tracker/overview` (or the per-property `GET /api/properties/{id}/stats`). To report **clicks AND page views together**, read both this endpoint and `GET /api/tracker/overview` and combine them, because they read from separate event streams (`link_clicks` vs `property_events`/`tracker_events`). Returns: - `totals`: links / clicks / unique_clicks / unique_referrers / countries / top_referrer / top_country - `comparison`: clicks vs the previous window of equal length (`trend_pct`) - `link_performance`: `health` (0–100), counts of active/growing/declining links, and top growing links with delta_pct - `by_day`: `[{ day: "YYYY-MM-DD", count }]` - `links_created_by_day` - `by_country`, `by_device`, `by_browser`, `by_referrer`: top buckets - `by_hour`: 24 buckets `{ hour, count }` (UTC) - `by_weekday`: 7 buckets `{ name, count }` (Sun…Sat, UTC) - `peak_hour`, `peak_weekday` - `top_links`: top 5 by clicks - `recent_clicks`: last 25 - `window_days` ### `GET /api/stats/link/{id}?days=14` Same shape minus account-wide rollups, plus `by_language` and per-click `ip`. `link.campaign` names the campaign a link was turned into (null otherwise). ### `GET /api/stats/links?from=&to=` (or `?days=30`) Every live short link with its clicks in the window, plus archived links that had clicks in it, sorted by clicks. Each row: `id`, `code`, `title`, `destination_url`, `short_url`, `clicks`, `unique_clicks` (by IP), `top_country`, `top_device`, `last_click_at`, `archived`, and `campaign` (`{id, name}` when the link was turned into a campaign). `totals` has `links`, `clicks` and `unique_clicks` (one person on two links counts once). Short links are counted apart from the tracker, so `GET /api/tracker/overview` does not include them. ### Turn a link into a campaign: `GET` / `POST /api/links/{id}/campaign` For a plain link that now needs campaign tracking without a new URL. `POST` makes a campaign on the link's SHORT CODE and domain, so the URL already posted keeps working and runs through the tracker. Its flow sends traffic to an offer for the link's destination (a live offer on the same URL is reused, and an Amazon URL with no `tag` gets the account's Associates tag), and the link's `phone_open` moves to the offer step. The link is archived and keeps its click history (`campaign_id` points at the campaign). It cannot be undone. `GET` reports what would happen and changes nothing: `can_convert`, `blocked` (`link_has_alias`, `link_has_password`, `already_moved`, or null), `campaign_name`, `short_url`, `offer` (when one is reused), and `dropped` (`pixels`: how many click pixels stop firing, `collection`: whether it leaves a rotator). `POST` answers 409 with the same `blocked` code, or `{ campaign: {id, name, code, short_url}, offer: {id, reused}, link_id }`. --- ## Collections Group links into folders. If `rotator_enabled` is true, the public URL `https://offerswap.com/c/{rotator_alias}` picks a random member on each visit. ### `GET /api/collections` List collections with link + click counts. ### `POST /api/collections` Body: ```json { "name": "Top picks", "description": "...", // optional, max 280 "color": "#3b82f6", // hex from a fixed palette; invalid → #ef4444 "starred": false, "rotator_enabled": false, "rotator_alias": "topPicks2026" // 8–24 chars [A-Za-z0-9_-]; auto-generated if omitted } ``` ### `GET /api/collections/{id}?days=14` Collection detail: meta + member links + aggregated stats over the window. ### `PATCH /api/collections/{id}` / `DELETE /api/collections/{id}` Update or delete. Deleting a collection detaches its links (sets `links.collection_id = NULL`); it does not delete the links themselves. --- ## Tracking pixels Meta / TikTok / Google pixels. A pixel never goes on a page and never fires on its own: a short link fires one on its deep-link interstitial only when it was picked for that link, and a campaign sends, server-side, only the events it picked in `pixel_events`. Each pixel fires a **default event** chosen from its platform's catalog (Facebook `PageView`/`ViewContent`/`Lead`/`Purchase`/…, TikTok `ViewContent`/`CompletePayment`/…, GA4 `page_view`/`purchase`/…). The event can be overridden per-link (see the per-link pixel selection on the Edit Link page) and per-campaign (a campaign's `conversion_event`). Facebook and TikTok pixels can additionally store a **server-side Conversions API token** (`capi_token`), which lets a campaign's events fire server-to-server, and a Meta **`test_event_code`**: while it is set, every server event the pixel sends lands in Events Manager's Test events and none of them count. ### `GET /api/tracking-pixels` Returns `pixels` + the platform catalog. Each pixel row includes `default_event`, `has_capi_token` and `capi_token_tail` (the token's last four characters; the raw token is never returned), `test_event_code`, and the last server send: `last_sent_at` + `last_sent_event` (accepted by the platform) and `last_error` + `last_error_at` (the last refusal, kept with its time). Each platform in `platforms` includes `{ label, placeholder, help, events, defaultEvent, capi }` (`events` is the list of valid event names, `capi` is whether server-side conversions are supported). ### `POST /api/tracking-pixels` Body: ```json { "platform": "facebook", "pixel_id": "1234567890", "label": "Main pixel", "default_event": "Purchase", "capi_token": "EAAB...", "active": true } ``` `platform` must be a key from the catalog. `pixel_id` is sanitized per platform. `default_event` must be a valid event for the platform (defaults to the platform default). `capi_token` is optional (Facebook/TikTok only); whitespace inside it, such as a line break from pasting, is removed, and anything else that is not a token returns `400 invalid_capi_token`. The response is `{ pixel, meta_check }`. For a Facebook pixel saved with a token, `meta_check` is `{ ok, name, error }`. It comes from an empty event batch sent with that token: Meta refuses it as empty only when the token can send to that dataset, so nothing is recorded, and a wrong number (such as the Owner id Events Manager shows beside the Dataset ID) or a bad token comes back `ok: false` with Meta's message. `name` is the dataset's name when the token can read it; a Conversions API token usually cannot, so it is often null. Null when there is nothing to check. ### `PATCH /api/tracking-pixels/{id}` / `DELETE /api/tracking-pixels/{id}` PATCH accepts `pixel_id`, `label`, `default_event`, `active`, `capi_token` (empty string / null clears the token) and `test_event_code` (empty / null clears it and the pixel goes live). It returns `{ pixel, meta_check }`, with `meta_check` set when `pixel_id` or a new `capi_token` was saved on a Facebook pixel. ### `POST /api/tracking-pixels/{id}/test` Sends one test event (a $1 `Purchase` unless the body names another `event`) with the pixel's own token, to prove the pixel id and token work. It refuses with `400 no_test_event_code` unless the pixel has a test event code, so a test can never count as a real sale, and `400 no_capi_token` without a token. Returns `{ ok, event, error, test_event_code }` and records the result on the pixel's `last_sent_*` / `last_error*`. --- ## API keys Personal access tokens for programmatic API access. ### `GET /api/api-keys` List your keys. The token hash is never returned; you see `id`, `label`, `prefix` (first 8 chars of the random portion, for UI identification), `last_used_at`, `created_at`, `revoked_at`. ### `POST /api/api-keys` Create a new token. Body: ```json { "label": "production server" } // optional, max 80 ``` Response: ```json { "key": { "id": 12, "label": "production server", "prefix": "aB3xY7zQ", ... }, "token": "bgl_aB3xY7zQmN9pK2rT5sW8vCdE" } ``` The `token` field is returned **exactly once**. Save it now. We store only SHA-256(token) and cannot recover it. ### `DELETE /api/api-keys/{id}` Revoke a token. Existing usages will start failing with `401 unauthorized` on the next request. --- ## Custom domains Branded short-link hostnames (e.g. `go.acme.com`) served via Cloudflare for SaaS. Once DNS resolves, Cloudflare auto-issues SSL. Free plan does not include custom domains; paid plans allow 1 (Small), 5 (Medium), or 10 (Large) domains. ### `GET /api/domains` List your custom domains. Each row is force-refreshed against Cloudflare on each call (except recently-active rows, which are cached for 5 minutes). ```json { "domains": [ { "id": 7, "hostname": "go.acme.com", "cf_hostname_id": "0d89c7…", "status": "active", // pending | active | failed | blocked "ssl_status": "active", "verification_errors": null, "cf_last_synced_at": "2026-05-29T…", "created_at": "2026-05-29T…" } ], "plan": "small", "domain_limit": 1, "cname_target": "offerswap.com" } ``` ### `POST /api/domains` Register a new branded hostname. Returns instructions for the CNAME the user must add. Body: ```json { "hostname": "go.acme.com" } ``` Errors: - `402 upgrade_required`: free plan, custom domains not allowed. - `402 plan_limit_reached`: already at plan domain cap. - `400 invalid_hostname`: malformed. - `400 reserved_hostname`: tried to claim offerswap.com or a subdomain of it. - `409 hostname_taken`: already registered by another account. - `502 cloudflare_error`: CF API rejected the create (e.g. zone misconfigured). Response: ```json { "domain": { "id": 7, "hostname": "go.acme.com", "status": "pending", ... }, "cname_target": "offerswap.com", "instructions": "Add a CNAME record at your DNS provider: go.acme.com CNAME offerswap.com" } ``` ### `POST /api/domains/{id}/verify` Force a fresh sync against Cloudflare's Custom Hostnames API. Use after the user adds the CNAME record to advance `status` from `pending` to `active`. Returns the refreshed domain row. ### `DELETE /api/domains/{id}` Removes both the Cloudflare hostname binding and the local record. Short links served via this hostname stop resolving immediately. --- ### `GET /api/domains/{id}/dns` Detects where the domain's DNS is hosted from its public nameservers and reports the easiest way to connect it. `one_click.method` is `domain_connect` (send the user to `one_click.url` to approve at their provider), `cloudflare_oauth` (the user clicks Connect Cloudflare on the domain in Properties, which needs a browser), or `null` (add the CNAME by hand, at `dns_url` when known). On Cloudflare, `one_click.token_url` is also set, for connect-cloudflare below. ### `POST /api/domains/{id}/connect-cloudflare` ```json { "api_token": "..." } ``` For callers with no browser. Adds the CNAME to the user's own Cloudflare zone, using a token with Zone Read and DNS Edit. The token is used for this request only and is never stored. Returns `action` (`created` or `already_set`), `zone`, and the refreshed `domain`. An existing different record is never overwritten. Errors: `invalid_token`, `token_missing_dns`, `zone_not_found`, `record_exists`. ## Tracker (affiliate campaigns) The Tracker is a Voluum-lite affiliate-marketing layer on top of short links. **Model:** one **campaign** = one short link + N **offers** (weighted) + N optional **landers** (weighted) + one **pixel**. Optional **affiliate networks** group offers and set the click id param name. Sales come back on the account's ONE **postback URL**, shared by every campaign and network. A campaign mints a `click_id` (uuid) on the visit event. The id propagates through landers (URL token / cookie / pixel), outbound clicks, and conversions. Conversions arrive on the account's **postback URL** (`/postback/u/{token}`, from `GET /api/me` → `postback_url`): one URL that credits whichever campaign the click belongs to, across all campaigns and networks. It is the only postback URL the API hands out. ### `GET /api/affiliate-networks` List networks. Each row carries `conversion_param` (the name the network reads the click id from, appended to its offer URLs) and `amazon_tag` (Amazon Associates tag, or null). Networks have no postback URL: their sales come back on the account's one postback URL. ### `POST /api/affiliate-networks` Body: `{ name, conversion_param?, amazon_tag? }`. Set `amazon_tag` (e.g. `yourtagid-20`) on an Amazon network and any Amazon destination link the user adds is auto-converted to an affiliate link: the resolver appends `?tag={amazon_tag}` on each click (a `tag` already on the URL always wins). ### `PATCH /api/affiliate-networks/{id}` / `DELETE /api/affiliate-networks/{id}` Update / soft-archive / delete. --- ## Traffic sources User-managed list of the platforms you buy traffic from (Facebook, TikTok, Google, …). A campaign references one via `traffic_source_id`. Each source carries `token_params`: how the source's click macros map onto the Google UTM params the resolver captures from inbound short-link URLs (`utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`), so a campaign's short URL can be pre-filled (e.g. `?utm_campaign={{campaign.id}}&utm_content={{ad.id}}`) and reports can label the UTM columns. ### `GET /api/traffic-sources` Returns `sources` (your saved rows) plus a `presets` catalog (`facebook`, `tiktok`, `google`, `microsoft`, …) with each platform's standard macros, ready to copy into `create_traffic_source`. ### `POST /api/traffic-sources` Body: `{ name, platform?, token_params? }`. `platform` is an optional pixel-platform key (drives the icon + conversion-pixel suggestion). `token_params` is an array of `{ slot, label, token }` where `slot` is one of `utm_source`, `utm_medium`, `utm_campaign`, `utm_term`, `utm_content`. ### `PATCH /api/traffic-sources/{id}` / `DELETE /api/traffic-sources/{id}` PATCH accepts `name`, `platform`, `token_params` (replaces the whole set), and `archived`. DELETE unlinks the source from any campaigns (their `traffic_source_id` is set null) and removes it. --- ### `GET /api/offers` List offers (destination URLs). `?include_archived=1` adds archived ones (`archived_at` set). Each row may carry `affiliate_network_id`, `payout`, `payout_currency`, `country`, `asin` (auto-extracted from Amazon URLs), and `campaigns`: the live campaigns the offer is in, oldest first, each `{ id, name, short_url }`. Those are the links that reach the offer. ### `POST /api/offers/{id}/campaign` (the offer's "Create campaign" button) An offer has no link of its own, so this makes the simplest campaign for it: named after the offer, on the account's default domain, its link sending every click to the offer (flow Source to the offer, 100%). Returns `{ campaign: { id, name, code, short_url } }`. Each call makes a new campaign, so call it once unless a separate link per placement is wanted. Add a landing page or a split test later on the campaign itself. ### `POST /api/offers` Body: `{ name, url, affiliate_network_id?, payout?, payout_currency?, country? }`. An offer gets no short link of its own: the link that goes in an ad comes from a campaign, which also picks the domain. `domain_id` is accepted and ignored, for older callers. The app's Duplicate offer action is this call with the edited URL. ### `PATCH /api/offers/{id}` / `DELETE /api/offers/{id}` An offer made before offers stopped getting short links can still have one on its URL. Renaming the offer (`name`) renames that link, and renaming the link (`PATCH /api/links/{id}` with `title`) renames the offer, so the pair keeps one name. Offers are never deleted. `DELETE` archives the offer (sets `archived_at`) and returns `{ ok: true, archived: true }`: campaigns stop sending clicks to it, its sales history stays, and `PATCH` with `archived: false` restores it. ### `GET /api/landers` List landers (the user's own intermediate landing pages). ### `POST /api/landers` Body: `{ name, url, country? }`. The lander URL may contain `{clickid}` tokens which the resolver expands at click time. ### `PATCH /api/landers/{id}` / `DELETE /api/landers/{id}` ### `GET /api/campaigns` List campaigns with quick-look stats (`visits`, `lander_views`, `offer_clicks`, `conversions`, `revenue`). Each row also returns `short_url`, `click_url`, `pixel_snippet`, plus `traffic_source`, `conversion_pixel_id`, `conversion_event`, `report_value_mode` (+ `report_value_fixed`/`report_value_adjust_pct`/`report_value_adjust_flat`), `pixel_events`, `direct_slugs` (`[{ slug, label }]`), the legacy `direct_slug` (mirrors the OLDEST slug), and `fallback_url`. The response also includes a `traffic_sources` catalog (`{ key: { label, pixel_platform } }`). ### `POST /api/campaigns` Body: `{ name, traffic_source_id?, traffic_source?, traffic_source_label?, country?, cost_model?, cost_value?, transition_mode?, domain_id?, conversion_pixel_id?, conversion_event?, pixel_events?, report_value_mode?, report_value_fixed?, report_value_adjust_pct?, report_value_adjust_flat?, direct_slugs?, direct_slug?, fallback_url?, open_in_browser?, offer_ids?, offer_weights?, lander_ids?, lander_weights? }`. - `traffic_source_id`: id of one of the caller's saved traffic sources (from `GET /api/traffic-sources`). One per campaign; mirrors the source's name into the display label. The legacy free-text `traffic_source` key + `traffic_source_label` are still accepted for back-compat. - `conversion_pixel_id`: optional id of one of the caller's tracking pixels (from `GET /api/tracking-pixels`) to fire when this campaign converts. The campaign conversion fires **server-side via the pixel's CAPI token** (Facebook/TikTok), because the buyer converts on the advertiser's own site where a browser pixel can't run, so a pixel WITHOUT a CAPI token does nothing here. `conversion_event` overrides which event a sale fires (defaults to the pixel's `default_event`). - `pixel_events`: which of the campaign's events reach that pixel, and as what. Which events reach the pixel is the campaign's `pixel_events`: keyed by `conversion` (a sale), a traffic event (`lander_view`: the campaign's landing page shown, or a view of a direct lander from the property tag; `visit`: the ad click reaching the campaign link; `offer_click`: the tap that leaves for the offer) or a custom event slug, each `{ event, first_only? }`, for example `{"conversion":{"event":"Purchase","first_only":true},"upsell":{"event":"Purchase"},"initiate_checkout":{"event":"InitiateCheckout"}}`. A missing key is not sent, `first_only` sends only the click's first event of that kind, refunds and re-fired orders are never sent, and every event gets its own `event_id`, so a sale and an upsell on one click both count. Null keeps the old rule: sales only, as `conversion_event`. Add `&email=` with the buyer's email to the postback URL so the platform can match the sale: it is hashed before it is sent and never stored. Visits keep Meta's `fbc` (the `_fbc` cookie, or built from the ad's `fbclid`) and `fbp` (`_fbp`) for the same reason. Bot traffic is never sent. A key that is not `conversion`, `lander_view`, `visit`, `offer_click` or one of the caller's custom events returns `400 invalid_pixel_event_key`, and an event name the pixel's platform does not take returns `400 invalid_pixel_event`. Setting `pixel_events` also sets `conversion_event` to the sale's event; sending only `conversion_event` moves the sale's rule with it. - `report_value_mode` (+ `report_value_fixed`, `report_value_adjust_pct`, `report_value_adjust_flat`): what revenue VALUE to report back to the ad platform on that CAPI conversion. `payout` (default) reports the real conversion payout; `fixed` always reports `report_value_fixed` (e.g. `1`); `adjusted` reports the real payout minus `report_value_adjust_pct`% then minus `report_value_adjust_flat` (floored at 0), so the operator can bake their margin/cost into what the platform optimizes against rather than handing over the true payout. - `direct_slugs`: direct-link tags for this campaign. A campaign can claim **MULTIPLE** `utm_campaign` values, each routing through the campaign's flow. An array where each item is either a string (used as both slug and label) or an object `{ slug, label }`: `slug` is the sanitized lowercased-alnum+dashes value matched against incoming `utm_campaign` (e.g. `abo-testing-campaign`), `label` is the friendly display value (e.g. `ABO Testing Campaign`). For running traffic STRAIGHT to a lander with no tracker hop: put `?utm_campaign={slug}` on the ad URL and the property tag (`/t.js`) stitches the page view to this campaign. Multiple tags let you migrate an older campaign onto a new BGL campaign, or turn a lander already receiving direct traffic into a campaign without renaming its ad URLs. Each slug is **unique per owner**. A collision returns `409 { error: "direct_slug_taken" }`. Pass `[]` to clear all tags. - `direct_slug`: **deprecated** but still accepted: the legacy single direct-link tag. When passed it's added to the campaign's tag set; in responses `direct_slug` mirrors the OLDEST slug for back-compat. Prefer `direct_slugs`. Pass `null` to clear the legacy single field. - `fallback_url`: optional URL the click falls back to when the flow yields no live offer: the never-dead-end guarantee. If unset, falls back to the platform default. Pass `null` to clear. - `open_in_browser`: an older all-offers default, kept for compatibility. Set `phone_open` on each flow node instead (`PUT /api/campaigns/{id}/flow`), which wins over this. When true, a phone tap to an offer with no `phone_open` of its own leaves Facebook's, Instagram's or TikTok's own in-app browser for Safari or Chrome before the offer loads. Default `false`. The visitor leaves the browser that holds Meta's cookies, so a Meta pixel on the offer page may match fewer sales (the `fbclid` still rides on the URL). An offer that belongs to an app (Amazon, and every app short links open) always opens that app on a phone, whatever this says. - `cost_model`: `not_tracked` | `cpc` | `cpm`. Visits log `cost = cost_value` when `cpc`. - `transition_mode`: `302` (default), an instant redirect, or `meta_refresh`, a short Redirecting page that forwards at once, so the next page sees the campaign link, not the landing page, as the referrer. Neither fires a pixel; ad platform events are set with `pixel_events`. - `domain_id`: optional id of one of the caller's active custom domains (from `GET /api/domains`). The campaign's short link resolves at that hostname. If omitted, defaults to the caller's first active custom domain, or `offerswap.com` if they have none. Pass `null` to force the platform default. - Optional inline `offer_ids` / `lander_ids` arrays for one-call setup. Server mints the campaign's short `code` (8-char base62, same namespace as link codes; a DB trigger blocks collisions). Response includes `short_url`, `click_url`, `short_domain`, and `pixel_snippet`, all reflecting the picked domain. ### `GET /api/campaigns/{id}` Returns the campaign with `offers[]` and `landers[]` fully expanded (each item has `offer`/`lander` object, `weight`, `position`). `direct_lander` is true on a direct link campaign: its ads link straight to a lander, so `short_url` goes on that page's button and not in the ads. Includes `domain_id`, `short_domain`, `click_url`, `traffic_source`, `conversion_pixel_id`, `conversion_event`, `report_value_mode`, `report_value_fixed`, `report_value_adjust_pct`, `report_value_adjust_flat`, `direct_slugs` (`[{ slug, label }]`), the legacy `direct_slug` (mirrors the OLDEST slug), `fallback_url`, and the `traffic_sources` catalog. ### `PATCH /api/campaigns/{id}` / `DELETE /api/campaigns/{id}` PATCH accepts any subset of: `name`, `traffic_source_id`, `traffic_source`, `traffic_source_label`, `country`, `cost_model`, `cost_value`, `transition_mode`, `domain_id`, `conversion_pixel_id`, `conversion_event`, `pixel_events`, `report_value_mode`, `report_value_fixed`, `report_value_adjust_pct`, `report_value_adjust_flat`, `direct_slugs`, `direct_slug` (legacy), `fallback_url`, `open_in_browser`, `dim_labels`, `archived`. Pass `direct_slugs` (array of strings or `{ slug, label }`) to replace the campaign's full set of direct-link tags. `[]` clears them; the legacy single `direct_slug` is still accepted and merged in. Pass `domain_id` to move the campaign's short link to a different custom domain; `null` sends it back to `offerswap.com`. Pass `conversion_pixel_id: null` to clear the conversion pixel. Setting any slug already used by another of the caller's campaigns returns `409 { error: "direct_slug_taken" }`. Campaigns are never deleted. `DELETE` archives the campaign (sets `archived_at`) and returns `{ ok: true, archived: true }`: its flow, reports and history stay, its short link stops routing (it shows the not found page), and `GET /api/campaigns` leaves it out unless `?include_archived=1`. `PATCH` with `archived: false` restores it. ### `POST /api/campaigns/{id}/duplicate` Deep-copies the campaign's settings, full routing flow graph (nodes + edges with split weights), and derived offer/lander pools into a brand-new campaign with a fresh short code. The copy is named `COPY - {original}` (or `COPY (1) - {original}`, `COPY (2) - …` when duplicating a copy, with the existing copy prefix stripped first so prefixes don't stack). Stats are NOT copied and the unique direct-link tags (`direct_slugs` / legacy `direct_slug`) are left blank. Returns `{ campaign }` (including `short_url`/`click_url`). Useful for spinning up a geo/angle variant of a working campaign without rebuilding the flow. ### `GET /click` (public: the defined lander click URL) The single, **campaign-agnostic** URL the operator pastes into their lander's CTA button (the campaign response surfaces it as `click_url`, now a plain `https://{host}/click` with no campaign id baked in, so one lander can be reused across many campaigns). It ALWAYS resolves to an **offer** chosen by the campaign's flow graph + split weights, never a lander, never a dead page. The campaign is resolved at click time. Two shapes: - **Tracker-driven** (visitor first hit `{host}/{code}` and was served a lander): the existing `bgl_clk_{code}` cookie (same host) supplies the `click_id` + campaign and the `bgl_lnd_{code}` cookie supplies the remembered lander branch, so the bare `/click` **reuses the same `click_id`** (one click, not two) and picks among THAT lander's downstream offers. Nothing campaign-specific is on the CTA. (`?cid={click_id}` is also accepted.) - **Direct-link** (ad points straight at the lander, no tracker hop): the ad URL carries `?utm_campaign={slug}` and the lander forwards that onto the CTA, so `/click?utm_campaign={slug}` matches the campaign by any of its `direct_slugs`, mints a fresh `click_id`, logs the `visit` retroactively, then picks an offer. (A legacy `/click?cmp={code}` is still accepted as a fallback.) If no live offer exists, redirects to the campaign's `fallback_url`, then the platform default, never a 503. For direct-link campaigns you can also set one or more `direct_slugs` (matched from the ad's `utm_campaign`), or simply put `?cmp={campaign_code}` on the ad URL. The property tag attributes the lander's page view to the campaign either way before the CTA is clicked. The universal tag (`/t.js`) also records the paid-click identifier (`fbclid` for Facebook/Instagram, `gclid` for Google, `ttclid` for TikTok) off the landing URL onto the page view (`click_ref` / `click_ref_kind`); an `fbclid` present proves the visit came from paid Meta traffic even with no `utm_source`. ### `PUT /api/campaigns/{id}/offers` Body: `{ items: [{ offer_id, weight }, …] }`. Replaces the offer split. ### `PUT /api/campaigns/{id}/landers` Body: `{ items: [{ lander_id, weight }, …] }`. Replaces the lander split. Empty items removes all landers (clicks then go direct to offer). ### `GET /api/campaigns/{id}/flow` Returns the campaign's **routing flow graph** (n8n-style): `{ flow: { nodes, edges }, offers, landers }`. Nodes are `{ id, kind: "source"|"lander"|"offer"|"rule", ref_id, pos_x, pos_y, direct, phone_open, offer?, lander? }`, and a `rule` node also has `name`, `conditions` and `priority` (see Rule paths below). `phone_open` (landers and offers) is what a tap TO that step does on a phone: `browser` leaves Facebook's, Instagram's or TikTok's own browser for Safari or Chrome first (on a lander that is the ad tap, and a direct lander does it through the property tag on the page; on an offer it is the button tap), `stay` loads it where they tapped, `app` (offers) opens the offer's app, null is the default (an app offer such as Amazon opens its app, anything else stays). Each offer in `offers` carries `opens_app`, the app it opens ("Amazon") or null, with exactly one `source` node (the traffic entry, `ref_id` null). Edges are `{ id, from_node_id, to_node_id, weight }` and only go source→lander, source→offer (direct), or lander→offer; `weight` is the split-test weight, relative and not a percent: an edge's share is its weight over the sum of the weights leaving the same node, so two edges at 100 split 50/50. The resolver walks this graph per click, so a specific lander can route to its own specific offers (true per-path split testing). ### `PUT /api/campaigns/{id}/flow` Body: `{ nodes: [{ tmp_id, kind, ref_id, pos_x, pos_y, direct?, phone_open?, name?, conditions?, priority? }, …], edges: [{ from, to, weight }, …] }`. Replaces the whole graph. `tmp_id` is any client-stable string key; edges reference nodes by `tmp_id`. Provide exactly one `source` node; `lander`/`offer` nodes set `ref_id` to a lander/offer you own (unowned refs are dropped). Edges must respect source→lander, source→offer, lander→offer. Saving re-derives the flat offer/lander pools so legacy reports stay consistent. A campaign with an unwired graph (source with no outbound edges) falls back to flat-pool routing. **Rule paths:** a node with `kind: "rule"` sends some visitors their own way, like Voluum's rule-based paths. It takes `{ name, conditions, priority }` and no `ref_id`. It hangs off the `source` (not on a direct link campaign, whose ad goes straight to its page) or off a `lander`, with exactly one edge into it, and its own edges are its branches: landers or offers after the source, offers after a lander. When a visitor reaches that step, the step's rules are checked in `priority` order (lowest first). The first rule whose conditions all match and that has a branch sends them down its branches, weighted as usual. Everyone else takes the step's plain edges, and a step with rules and no plain edge sends them to the campaign's `fallback_url`. A rule after a lander is checked at the page's button (`/click` or `/c/{click_id}/out`), so it works on direct link campaigns too, and a rule on the ad's URL params or referrer reads them from the visit (or, on a direct lander's first tap, from that visitor's page view). A condition is `{ type, op: "is" | "is_not", values }`. Values in one condition are ORed, conditions in one rule are ANDed. Types: - `country`: ISO2 codes (`US`, `CA`). - `region`, `city`: names as Cloudflare gives them (`Texas`, `Austin`), case-insensitive. - `device`: `mobile` (iOS, Android) or `desktop` (Mac, Windows, Linux). iPads report themselves as Macs. - `os`: `ios`, `android`, `mac`, `windows`, `linux`, `other`. - `browser`: `chrome`, `safari`, `firefox`, `edge`, `opera`, `other`. - `inapp`: `facebook`, `instagram`, `messenger`, `tiktok`, `twitter`, `linkedin`, `pinterest`, `snapchat`, or `none` for a real browser. - `language`: the browser's first language as a 2 letter code (`en`, `es`). - `ip`: addresses or CIDR ranges (`203.0.113.0/24`, IPv6 too). - `isp`: matches when the network's name contains the text (`Verizon`). - `referrer`: domains; `facebook.com` also matches `m.facebook.com`. - `param`: `{ name, values }`, a parameter on the ad's URL; empty `values` matches any value. - `time`: `{ from: "HH:MM", to: "HH:MM", tz }`; `to` is exclusive and `to` before `from` runs overnight. - `weekday`: `{ values: ["sat", "sun"], tz }`. Mobile carrier and phone brand are not available. A bad condition or a misplaced rule is a `400` with a `message`: `invalid_rule`, `rule_on_direct_source`, `rule_bad_parent`, `rule_bad_branch` or `rule_has_many_parents`. Rules are copied by `duplicate`, and they never enter the flat offer/lander pools. **Direct landers:** set `direct: true` on a lander node when the ad links straight to that page and the campaign's short link or `/click` sits on its button. The link then goes on to that lander's offers instead of sending the visitor to the page, so no ad URL has to change, and direct landers win over every other edge on the source. With the property tag on the page, its page views join the campaign by URL and appear in the stats below as `lander_views`, with `direct_lander: true` and a per-row `lander_ctr` (visits per lander view). A campaign with direct-link tags claims tagged traffic only. Page views have no offer, so `lander_views` is 0 on the `offer` dimension and under an `offer` filter. ### `GET /api/campaigns/{id}/stats?days=14` (or `?from=…&to=…`) Returns full report: `totals` (visits / unique_visits / lander_views / unique_lander_views / lander_outbound / offer_clicks / unique_offer_clicks / conversions / revenue / cost / profit / CTR / CR / EPC / AOV / ROI; `aov` is net revenue per sale, after refunds and chargebacks, and `gross_aov` gross revenue per sale, before them; `epc` is gross revenue per offer click, before refunds and chargebacks, here and on every row), `by_day`, `by_country`, `by_device`, `by_browser`, `by_referrer`, `by_hour`, `by_offer`, `by_lander`, `recent_events[]`, and `breakdowns`: Voluum-style grouped report rows for 10 dimensions (`utm_campaign` / `utm_medium` / `utm_source` / `utm_content` / `utm_term` / `lander` / `offer` / `country` / `device` / `day`), each row `{ key, visits, unique_visits, clicks, unique_clicks, lander_views, unique_lander_views, conversions, revenue, gross_revenue, reversed_revenue, cost, ctr, cr, epc }`. `cost` (here and in `totals`) is the ad cost the campaign's cost model put on its visits (CPC), 0 without one. It never includes refunds or chargebacks, which are `reversed_revenue` (the app's Reversed column). Uniques count people, not rows: `unique_visits` and `unique_clicks` (`unique_offer_clicks` in totals) go by the IP and user agent of the visit that minted the click, and `unique_lander_views` by the property tag's visitor cookie, then IP and device. `totals.unique_events` counts the people behind each sale and custom event, keyed `conversion` or the event slug (refunds and chargebacks are left out). Offer clicks and conversions are attributed to the utm values of the **visit that minted their click_id** (utm params only exist on the visit event; postback conversions that land after the visit are matched back to it), so ad-level utm_campaign values roll up correctly. The `offer` dimension goes the other way: each visit is attributed to the offer its click routed to (rows keyed by offer name), so split-test offer rows read correctly. The `lander` dimension is the page the click came FROM: the visit's referrer normalized to host+path (pages running the property tag pass their full path via `bgl_page`, which the tag adds only to links on the account's own tracker domains, never to another site's link; clicks straight from an ad show the ad platform's host, e.g. `m.facebook.com`). Traffic with no value for a dimension groups under `(none)`. **Drill-down filters:** pass any breakdown dimension as a query param (`?utm_campaign=Summer%20Sale`, `?lander=promo.example.com%2Flander-a`, `?offer=My%20Offer`, `?country=US`, `?day=2026-07-09`, `(none)` matches missing values) and the WHOLE report (totals, by_day, breakdowns) narrows to that traffic slice; filters combine (e.g. `?utm_campaign=X` then read `breakdowns.offer` to see which split-test offer converts for that ad). Applied filters echo back in `filters`. `?breakdowns=0` skips the ten fixed breakdowns (they come back as empty arrays) and keeps everything else; on a long window for a busy campaign it is several times faster, and `group` covers any dimension you need. Window: rolling `days` (1–90, default 14) or an explicit closed range via `from`/`to` ISO dates (from/to override days). Also returns `window_from` / `window_to`. **Stacked report:** `?group=utm_campaign,utm_medium,offer` (up to 3 dimensions) returns `report.rows` as a tree, each row carrying its slice's metrics and `children` for the next level. Any breakdown dimension works, plus `region`, `city`, `browser`, `language`, `weekday` and `hour` and custom tokens written `param:`. `day`, `weekday`, `hour`, `by_day` and `by_hour` count in the account's time zone (`timezone` on `GET /api/me`, set with `PATCH /api/me`), or in the zone given as `?tz=America/New_York`; the response echoes it as `timezone`. With neither, they count in UTC. Every extra param on the inbound link (`adset_name=...`, `sub3=...`, `utm_id=...`) is kept on the visit, except click ids and personal fields. With no `group` the report groups by `offer`. `passed_dims` lists what the URLs really carried in the window: the `utm_*` tokens that had a value, then the `param:` ones. On a direct lander the ad's URL counts even if the page's button drops it: the visit fills in from that visitor's page view, and `lander_views` split by token too. Custom tokens filter as `?param:adset_name=Broad`. `dim_labels` holds the names the user gave this campaign's tokens, for example `utm_medium: "Ad Name"`. Set them by patching the campaign with the whole map. Only `utm_*` and `param:` keys are kept, and a blank name removes that one. Nothing is assumed about a slot: with no name, a token reads as its URL name. ### `GET /api/properties` List the user's properties (GTM/GA-style site containers) with a quick rollup (`page_views` / `unique_visitors` / `conversions` / `revenue`). Each carries an install `snippet`. ### `POST /api/properties` Create a property. Body: `{ name, site_url?, domain_id? }`. Server mints a 16-char base62 `property_key`. **Requires an active custom domain**: the tag is served first-party from the user's own domain so it tracks on iOS/Safari (a cross-site tag on offerswap.com gets its visitor cookie partitioned/blocked). Defaults to the user's first active custom domain; pass `domain_id` to pin one. With no active custom domain, returns `400 { error: "domain_required" }`. Response includes `tracking_domain` and the install `snippet`: a single GA/Facebook-style inline `