# Affiliate partners

Start with the [Listing partners documentation section](/#listing-partners). Use the [main affiliate API guide](travel-listings.md) for listing/search/booking contracts, the [lazy-loading guide](affiliate-lazy-loading.md) for browse-first pages and batch date checks, the [gallery grouping guide](listing-gallery-groups.md) for grouped photos, and the [public map locations guide](listing-locations.md) for approved property pins. [Travel response schemas](travel-listings.schema.json) define public listing/search responses. [Affiliate management schemas](affiliate-management.schema.json) define account, blacklist, ratings and income responses. The [endpoint reference](/#affiliates) includes populated examples, nested field descriptions, null/optional semantics and error responses. Verify the target deployment supports the requested endpoints before enabling them.

Influencers and listing sites use the same Wikiup Console login as hosts. Open
`https://console.wikiup.app/affiliate-portal`, sign in (or create and verify an account),
and create an affiliate profile with a name and HTTPS website/social-profile URL.
Hosting and affiliate participation are independent: hosts keep their property
workflows; affiliate-only accounts open the affiliate portal and can later choose
**Start hosting**. Account/profile editing and sign-in settings remain available.

## Listing visibility

Every property requires approval by the affiliate before it appears on that
partner's site, including existing listings and properties the affiliate owns.
Owners visit **Property → Listing Partners**, open the partner's website and
submit a request. Affiliates review in **Affiliate Portal → Requests**, approve or deny
with a reason. See [the request workflow and REST contract](listing-partner-requests.md).

**Affiliate Portal → Listings** contains approved and suspended properties. Suspend and Resume control your side of the listing; Remove listing requires a fresh owner request and approval before it can return.
Approval for one affiliate never grants another affiliate access.

Inactive rooms, empty properties, paused room types and protected review fixtures
are excluded. Sold-out properties remain in the portal catalog; the availability
API returns only inventory bookable for the requested dates and party size.

Regional search uses the property's saved destination when present, regardless
of its WikiupTravel publication toggle. Otherwise it matches the property's
California city exactly to the destination catalog. An ambiguous or unknown city
is not guessed. A city of San Diego matches county-wide searches only, unless a
more precise destination is saved. Properties without mapped geography still
appear in the portal but cannot match a regional search until their address or
destination is corrected. No publication records are created automatically.

The former **Publish on WikiupTravel** UI is replaced by Listing Partners. Existing
persisted publication settings continue to control the legacy
`travel_availability` and property-restricted key catalogs. It does not control
affiliate participation.

## API keys and integration

**Environment and permissions are separate.** A preview affiliate key is an
Affiliate key created in the preview console, for `https://api-preview.wikiup.app`.
A production affiliate key is created in the production console, for
`https://api.wikiup.app`. Use the matching environment's key and API origin.

The same verified email may own properties and operate an affiliate site.
Permissions belong to each key: a hosting **Read and write** key does not become
an **Affiliate** key just because its account also participates as an affiliate.
Create the site's key from **Affiliate Portal → Affiliate API keys**
(`/api-keys?access=affiliate`), where creation is restricted to Affiliate access.
**All API keys** opens the separate view for managing hosting and other keys.
Affiliate keys cannot manage properties, guests, reservations or other keys.

1. Open **Affiliate API keys**, create a key with **Affiliate** access, and complete
   recent sign-in verification if requested. The key is associated with the
   signed-in account and its verified email; there is no arbitrary email field.
2. Copy the key once into your server's secret manager. Listing keys, metadata,
   prefix, expiry and revocation are retrievable later; the raw secret is not.
3. For browse-first pages, call `GET /api/travel/listings?destination=julian-ca` without dates, then `POST /api/travel/listings/availability` with visible listing IDs or property IDs and dates/party. Catalog cards are explicitly unchecked and have no prices or booking links. See the [lazy-loading contract](affiliate-lazy-loading.md) for request bodies, limits and response states. For a combined regional search with dates, call:

```sh
curl 'https://api.wikiup.app/api/travel/availability?destination=julian-ca&checkIn=2027-01-10&checkOut=2027-01-12&adults=2&children=0&pets=0' \
  -H 'Authorization: Bearer <affiliate-api-key>'
```

4. Render the v2 `listings` directly: one hotel card per property and one rental card per bookable item. Do not regroup the legacy `results` array. Merge batch pricing into catalog cards by stable listing ID. Preserve the returned
   `bookingUrl` **unchanged**. It contains the selected room, dates and party size,
   plus a signed `affiliateReferral` capability tied to the API key's affiliate,
   property and room/room-type target. Never substitute a client-supplied affiliate
   ID or put your API key in a URL, browser bundle, mobile app or iframe.
5. Follow `meta.nextPage`, display partial failures and retry failed searches.
   Availability is not a hold; accommodation subtotals exclude taxes and fees.
   The full affiliate response and paging contract is in [Affiliate listing API](travel-listings.md). The older [Travel availability](travel-availability.md) guide is for search-only and property-restricted keys.
6. The guest completes Wikiup's hosted booking/payment flow. Standalone booking
   links continue to the existing payment screen without an embedding host. The
   browser sends the referral capability, never the partner key. No booking or
   commission is recorded just because a search or link was issued.

Affiliate keys authorize these public travel operations:

| Endpoint | Purpose |
| --- | --- |
| GET /api/travel/listings?destination=... | Browse area listings without dates or availability calculations |
| POST /api/travel/listings/availability | Read-only date/party checks for 1–12 listing IDs or property IDs |
| GET /api/travel/availability | Combined regional availability and priced listings |
| GET /api/travel/listings/{listingId} | Public listing details and gallery |
| GET /api/travel/listings/{listingId}/availability | Fresh availability and booking links for one listing |

All require the active affiliate's server-side key; per-affiliate approval and suspension status apply. They cannot read
reservations, guests, financial records, profile settings, or manage keys. Guest
checkout remains the existing public booking contract. Affiliates do not gain
staff reservation-write access to other hosts' properties.

To rotate, choose **Rotate** on the existing key, copy/install the replacement,
then **Revoke previous key**. Rotation deliberately keeps the old key working
until the partner confirms the replacement is installed. Lost secrets cannot be
recovered: create a replacement and revoke the lost key. Existing signed booking
links survive key rotation for their original seven-day lifetime. Account
suspension, removal of active property inventory, or listing suspension/removal prevents a
new attributed checkout; already accepted payments retain their server snapshot
for confirmation retries and webhook recovery.

Hidden San Diego uses this same account, affiliate key, listing status, search and
booking-link flow. Set its server-side `WIKIUP_TRAVEL_API_KEY` to an **affiliate**
key and `WIKIUP_TRAVEL_API_URL` to the intended API origin. A legacy
`travel_availability` key still searches published inventory but does not promise
affiliate attribution. This implementation does not backfill historical referrals
or claim that earlier Hidden San Diego bookings were attributed.

## Bookings and income

**Affiliate Portal → Bookings & income** shows only the signed-in affiliate's attributed
bookings: property, stay dates, reservation status, accommodation subtotal,
refunds, rate, pending commission, earned commission. It never returns guest
names, email, phone, confirmation/access codes, notes or full reservation records.
Pagination uses `meta.nextCursor`; displayed rows are not a complete report until
all pages have been loaded. Currencies are kept separate.

Wikiup uses a fixed **0.75% commission** (75 basis points), defined in code.
Affiliates and platform users cannot configure the percentage. New attribution
records capture 75 basis points. Reports also use this policy for existing
attributed bookings, including legacy missing or different rates, without
rewriting reservations or payments. No per-affiliate terms setup is required.

Commission applies to the original accommodation subtotal after discounts,
excluding taxes, cleaning charges, pet fees and add-ons. It is pending until the
reservation is checked out, then earned only up to successfully collected funds.
Successful refunds conservatively reduce the accommodation commission base
dollar-for-dollar, capped at zero. Canceled bookings earn zero. Pending/failed
payments and refunds do not count. Extra revenue on later stay changes does not
automatically increase the original commission base. These reports calculate
pending/earned income; **payouts are not executed or tracked as paid**.

Attribution is server-owned and immutable through ordinary reservation edits.
It is stored with the reservation, survives Stripe webhook recovery, and does not
change booking ownership/channel provider. A partner cannot claim another
property or target by editing a URL or confirmation payload.

## Management endpoints

All endpoints below require a verified-email interactive Firebase session.
API keys cannot access them. Responses use `Cache-Control: private, no-store`.

| Endpoint | Purpose |
| --- | --- |
| GET /api/affiliates/account | Own profile, configured terms, current email and administrator capability |
| PUT /api/affiliates/account | Enroll/update `{ "name": "Partner", "website": "https://example.com" }`; cannot change rates or reactivate a suspension |
| GET /api/affiliates/listings?page=1&status=all | Own listing requests across owners, including inactive inventory for management; optional search by name/town and status, applied before pagination; pending requests first with stable property-ID ordering within each group; 12/page, requestId, status, derived visible, nullable listingId/coverImage/tagLine and explicit nextPage |
| PUT /api/affiliates/listings | Legacy compatibility: false suspends for the affiliate; true clears only its suspension. Prefer status PATCH |
| GET /api/affiliates/reports?cursor=... | Own booking/income rows, 25/page, opaque nextCursor |
| GET /api/affiliates/admin?cursor=... | Platform-only affiliate/terms list, 25/page |
| PUT /api/affiliates/admin | Platform-only account activity `{ "uid": "...", "active": true }`; optional legacy `commissionBps` accepts only 75 and cannot override the rate |

Platform management additionally requires the verified Firebase custom claim
`wikiupPlatformAdmin: true`. Assign this claim only to explicitly authorized
platform operators using Firebase administration, retaining other custom claims.
Refresh their sign-in token afterward. Affiliate enrollment cannot grant it.
The **Platform management** tab uses these same protected routes. No operator
has been granted this capability automatically.

## Environment setup and rollout

- Apply the reviewed full Onyx schema additions: AffiliateAccount,
  AffiliateTerms, AffiliateListingSelection, nullable Reservation.affiliateUid,
  nullable Reservation.affiliateAttributionJson, and affiliateUid index.
  The migration descriptor is additive documentation, not a standalone schema
  publish file. Never replace the database with a fragment.
- Configure a distinct server-only `AFFILIATE_REFERRAL_SECRET` (at least 32 random
  characters) per environment. All API instances serving search/checkout in that
  environment need the same value. Changing it invalidates outstanding links;
  existing accepted payment metadata remains recoverable.
  GitHub Actions reads the dedicated `AFFILIATE_REFERRAL_SECRET` secret from the
  `preview` or `production` GitHub environment and synchronizes only that Pages
  runtime binding before deploying. Keep the corresponding ignored local API
  environment value consistent for operator builds. Do not bulk-replace other
  runtime settings to add this secret.
- Preserve travel API origin/booking-origin setup from the travel guide. Never
  mix preview keys, links or databases with production. Ordinary hosts do not
  receive administrator claims or affiliate terms automatically.
- Schema and required API configuration must precede deploying the console that
  reads affiliate account capabilities. No domains need changing.
- Before launch verify approved cross-owner inclusion and unapproved exclusion, inactive inventory exclusion, suspension/resume,
  revoked/expired keys, signed-link validation, room and pooled checkout,
  attribution through webhook recovery, refunds, and account isolation.
- The additive schema is applied to both preview and production following owner
  approval, and distinct referral signing secrets are configured in their GitHub
  deployment environments. Administrator assignment, property geography and
  partner runtime configuration remain explicit onboarding steps.

## Request tracing

Server logs emit JSON events with `event: "api_key_request"` when an API key is
processed. Match `keyPrefix` to the prefix shown in Console → API keys; the value
uses the first eight characters of the public key ID, never the secret after
the dot. `access: "affiliate"` identifies a verified affiliate key, regardless
of whether the same account also hosts properties.

```json
{"event":"api_key_request","requestId":"example-request-id","keyPrefix":"wk_12345678","keyVerified":true,"access":"affiliate","method":"GET","route":"/api/travel/availability","outcome":"authenticated"}
```

Filter Cloudflare API runtime logs by `api_key_request`, `access: affiliate`, or
the key's displayed prefix. `requestId` correlates trace events within a request;
`cfRay` is included when a valid Cloudflare Ray ID is present. For local development,
these events appear in the API server's terminal/log output.

Outcomes are `authenticated`, `scope_denied`, and `authentication_failed`.
`authenticated` describes credential authentication only; it does not assert
successful property authorization, search, booking or a final HTTP response.
An authentication failure may include a syntactically valid presented prefix,
but it has `keyVerified: false` and `access: null`; do not treat that as proof
that the caller owns the key. Denials/failures include `authStatus` when known.

The trace excludes raw credentials, key hashes, account emails, request bodies,
query parameters and dynamic path segments. Routes outside the known resource
families are labeled `[other]`. Logging failure does not change authorization.

## Affiliate ratings

See [affiliate-listing-ratings.md](./affiliate-listing-ratings.md) for create/read/update/delete and `fetch=ratings`. Ratings belong to each affiliate, are omitted from listing responses by default, and never fall back to owner values. Check the linked rollout status before adopting.

## Listing lifecycle

See [suspension and removal](./listing-partner-lifecycle.md) for the single-status owner and affiliate transitions, PATCH requests and response examples. Only `approved` is publicly eligible. Suspended listings remain manageable. Neither side can clear the other’s suspension; removed/withdrawn listings require a new request and approval. Existing reservations are unaffected.

### Filter booking and income reports

`GET /api/affiliates/reports` accepts optional `search` (case-insensitive property
name or listing title, up to 120 characters), `from` and `to` (inclusive check-in
calendar dates in `YYYY-MM-DD` format). Omit dates for all time. Invalid dates or
`from` after `to` return 422. Filters apply before the 25-row page is selected;
reports remain restricted to the authenticated affiliate. Keep filters unchanged
when following `meta.nextCursor`; omit the cursor whenever filters change.
The response fields and page-scoped totals are unchanged.

```sh
curl --fail-with-body --get 'https://api.wikiup.app/api/affiliates/reports' \
  -H "Authorization: Bearer $WIKIUP_SESSION_TOKEN" \
  --data-urlencode 'search=Example Hotel' \
  --data-urlencode 'from=2027-02-01' \
  --data-urlencode 'to=2027-02-28'
```

## Portal listing search and cards

```sh
curl --fail-with-body --get 'https://api-preview.wikiup.app/api/affiliates/listings' \
  -H 'Authorization: Bearer <session-token>' \
  --data-urlencode 'status=all' --data-urlencode 'search=Julian' --data-urlencode 'page=1'
```

This private management endpoint requires a verified affiliate session, not an API key.
`search` is a case-insensitive substring of property name, listing title, or town
(maximum 200 characters). `status` accepts `all`, `pending`, `approved`, `denied`,
`owner_suspended`, `affiliate_suspended`, `both_suspended`, `withdrawn`, or `removed`.
Omitting status preserves approved/suspended results. The newest request per property
wins, including withdrawal/removal; an older approval cannot make it visible again.
Both filters apply before the fixed 12-property page, ordered by property ID.

Populated example (synthetic data):

```json
{
  "listings": [{
    "propertyId": "property_example",
    "requestId": "request_example",
    "name": "Example Mountain Inn",
    "destination": "Julian",
    "status": "approved",
    "visible": true,
    "listingId": "hotel:property_example",
    "tagLine": "A peaceful mountain stay",
    "coverImage": {
      "id": "photo_example", "url": "https://example.com/listing-cover.jpg",
      "alt": "Hotel entrance", "width": 1600, "height": 900,
      "variants": [], "group": null
    }
  }],
  "meta": { "page": 1, "nextPage": null }
}
```

Use `requestId` with `GET /api/affiliates/listing-requests/{requestId}` to review and
manage any returned state. For approved eligible inventory, `listingId` opens the
existing `GET /api/travel/listings/{listingId}` detail and availability flow.
`listingId` is null for other states, unavailable inventory, or properties with
multiple rental targets; private management remains available. `coverImage` is the
first saved listing photo (null when missing); `tagLine` is owner-supplied (null when
unset). Neither is fabricated. The complete image and field definitions are in
[the management schema](./affiliate-management.schema.json#/$defs/Listing).

For infinite scrolling, append each `meta.nextPage` with unchanged filters, deduplicate
by `requestId`, and stop at null. Reset to page 1 when filters change. Show skeleton
cards during loading; retain loaded cards and offer retry on errors. Provider errors
return 503 instead of an incomplete successful page. Public approval, suspension and
API-key access rules remain unchanged. Responses are private and no-store.

### Affiliate card image

`PUT /api/affiliates/account` accepts an optional `imageUrl` alongside `name` and `website`:

```json
{
  "name": "Example Travel Guide",
  "website": "https://example.com/",
  "imageUrl": "/api/web-assets/affilate-profile-pics/affiliate_example/card.jpg"
}
```

Upload through the console's existing image uploader using the `affilate-profile-pics` namespace. Images use an immutable owner folder and affiliate-card metadata; they are separate from the user's profile photo. Arbitrary external image URLs and another account's folder are rejected. Omission preserves the current image; explicit `null` removes it without deleting the stored asset. `GET` and `PUT /api/affiliates/account` return `account.imageUrl` as a path or `null`; `GET /api/listing-partners` includes the same field on each partner. Other response fields and pagination are unchanged.

The nullable `AffiliateAccount.imageUrl` schema field and affiliate image storage rules must be published before deployment. These changes are local until separately published.

The affiliate portal manages listing requests in Listings. Pending requests appear first and are labeled **Pending approval**. Open a property listing to approve or deny it; denial requires a reason. Existing notification links containing `?request=<requestId>` open that listing detail directly.

### Affiliate card copy

`PUT /api/affiliates/account` also accepts optional `description` (plain text, at most 500 characters) and `region` (plain text, at most 120 characters). Values are trimmed; `null` or blank clears a field, while omission preserves the saved value. Account GET/PUT and the owner directory `GET /api/listing-partners` return these fields as strings or null for older profiles.

```json
{
  "name": "Example Travel Guide",
  "website": "https://example.com/",
  "imageUrl": "/api/web-assets/affilate-profile-pics/affiliate_example/card.jpg",
  "description": "Independent guides to remarkable stays.",
  "region": "San Diego County"
}
```

The profile editor previews the same image/name/description/region card rendered in the property's Listing Partners tab. That tab combines discovery and request management on the cards, supports name/region search and lifecycle status filters, and puts pending requests first. It reads every page of the existing owner directory and property-request history before applying filters; failed loads do not present partial results as complete. Inactive partners with request history remain manageable using the request's affiliate snapshot. No additional management endpoints or lifecycle status values were added. Schema and storage-rule publication remain separate deployment prerequisites.
