# Affiliate listings: search → listing → booking

Start with the [Affiliate Integration Guide](affiliate-integration-guide.md) for the complete partner workflow, cURL requests, populated examples, and photo rendering.

**Listing approval:** every property must have an approved request for the authenticated affiliate, including existing listings and the affiliate's own properties. Pending, denied and never-requested properties are excluded. Blacklist and active-inventory rules still apply. See [Listing partner requests](listing-partner-requests.md) for rollout status and onboarding.

Destination IDs are geographically qualified (for example `julian-ca`, `aurora-co`, `aurora-il`, `paris-tx`, `paris-fr`). See [destination IDs, compatibility, and supported areas](travel-destinations.md). This ID update is local and not deployed yet.

Use `https://api-preview.wikiup.app` for integration testing and `https://api.wikiup.app` after the production release is verified. `preview.wikiup.app` is not an API origin. Match the target deployment to the documented contract before enabling a consumer release. The machine-readable [JSON schemas](travel-listings.schema.json) describe successful affiliate responses, image metadata, and errors.

## Connect a listing partner

1. Sign in with the partner's verified email, create an Affiliate profile, and create an **Affiliate** API key. Keep the secret in the partner server's secret store. The key belongs to that email account, not to a property. Hosts can also be affiliates.
2. Set the server origin to `https://api-preview.wikiup.app` and send `Authorization: Bearer $WIKIUP_API_KEY`. Never expose the key to a browser, URL, analytics, or logs. No `x-property-id` header is needed.
3. Only inventory approved for the authenticated affiliate is included across owners, including the affiliate's own properties. Owners submit through Property → Listing Partners; affiliates approve through Affiliate Portal → Requests. Affiliates can blacklist properties in Console → Affiliate Portal → Listings. Each request checks eligibility, active affiliate status and the blacklist. These keys cannot read owner resources, guests, reservations, access codes, memberships, or internal notes.
4. A property needs an authoritative listing type (`hotel` or `vacation_rental`). Existing saved hotel/rental channel plans are supported. New property setup persists this choice. Geographic searches use its explicit destination assignment or an unambiguous city match. An unmapped property cannot appear in a regional search, but appears in the unfiltered approved catalog and can be fetched directly.
5. Search-only `travel_availability` keys and property-restricted keys retain their owner-publication and property-access requirements and the old nested response. They do not authorize the new direct affiliate listing routes.

## Portal preview access

The catalog, listing detail, room detail and direct availability GET routes also accept verified active affiliate sessions with the same approval/suspension restrictions. Omit catalog `destination` to browse all approved properties; response `query.destination` is then omitted. Session availability returns ordinary checkout links without commission attribution. Partner API-key links remain attributed. Batch POST and regional availability remain key-only. See [portal preview contract](affiliate-integration-guide.md#signed-in-affiliate-portal-previews).

## Fast catalog and lazy availability

Catalog cards and listing content include `mapLocation` and `timeZone`. Use only owner-approved coordinates, never destination centers. `mapLocation` is an exact `{latitude, longitude}` pair or `null`, without status/precision fields. Null locations remain unmapped; approximate positions are not supported. See [public map locations and owner setup](listing-locations.md) for the full contract and deployment requirements.

For browse-first pages, use `GET /api/travel/listings?destination=julian-ca` without dates, then `POST /api/travel/listings/availability` with up to 12 listing IDs or property IDs and dates/party. Catalog cards are explicitly unchecked and contain no prices. Batch availability checks each property once and omits images. See the [complete lazy-loading integration handoff](affiliate-lazy-loading.md) for request/response contracts, limits, pagination, stale-response handling and rollout requirements. Verify the target deployment supports these endpoints before enabling lazy loading; existing endpoints below remain compatible.

## Regional availability

```sh
curl --fail-with-body --get 'https://api-preview.wikiup.app/api/travel/availability' \
  -H "Authorization: Bearer $WIKIUP_API_KEY" \
  --data-urlencode destination=julian-ca \
  --data-urlencode checkIn=2027-02-09 --data-urlencode checkOut=2027-02-12 \
  --data-urlencode adults=2 --data-urlencode children=0 --data-urlencode pets=0 \
  --data-urlencode page=1 --data-urlencode pageSize=12
```

Dates are real `YYYY-MM-DD` dates: today or later, check-in within two years, 1–28 nights. Adults default to 2 (1–20), children to 0 (0–19), pets to 0 (0–10), humans at most 20. Page defaults to 1 (1–1000), pageSize to 12 (1–12). Unknown, repeated or invalid parameters fail with 422. Destination IDs come from WikiupTravel's catalog: `julian-ca`, its parent `east-county-san-diego-ca`, or `san-diego-county-ca`, for example.

Affiliate responses have `contractVersion: 2`, `listings`, legacy `results`, `query`, `failures`, and `meta`. Render `listings` directly. Do not group rooms yourself or infer type from room counts or names. One hotel card represents its property. Each independently bookable rental is a separate card. IDs are stable; preserve them unchanged for direct routes. Pagination is by property, so a page can contain more cards than pageSize. Order is stable by property ID, with rental inventory sorted by stable option ID. Never truncate rental cards to pageSize.

Every card includes ID/type/property ID, public name/property name/location, nullable cover URL, real responsive image sizes, currency, nightlyRate, staySubtotal, priceLabel and bookingUrl. Rentals include maxGuests; hotels include availableRoomCount. Hotel “From” nightly and stay prices come from the same lowest-subtotal qualifying option, in one currency. Different currencies are never compared. The average nightly rate and accommodation subtotal exclude taxes and fees. `taxes`, `fees`, and `finalTotal` are null until checkout; null does not mean zero.

`meta.nextPage` identifies another property page. `pageComplete` covers the current page; `complete` is true only for an entire one-page search with no failures. Retain failures across accumulated pages. `soldOutProperties` means checked properties with no qualifying availability; `withdrawnProperties` means eligibility changed during the search. `failures` contains propertyId, retryable=true and `timeout` or `provider_unavailable`. A 200 response may be partial. No cards with failures is not “sold out.” Searches launch at most three property checks concurrently, with a 10-second provider-search budget.

## Listing content

**Pending local update, not deployed:** detail GET now includes `address` and `contact`; the lightweight catalog is unchanged. See [full contract and sample JSON](./hidden-san-diego-integration.md#property-address-and-contact).

```sh
curl --fail-with-body \
  "https://api-preview.wikiup.app/api/travel/listings/$LISTING_ID" \
  -H "Authorization: Bearer $WIKIUP_API_KEY"
```

Response: `{ "listing": { ... } }`. Content includes public identity, type, property identity/name, location, nullable destination ID, nullable published description, amenities, coverImage and ordered gallery. Rental maxGuests can be null when unpublished/unconfigured. It contains **no prices, live counts or signed booking links**. An absent eligible photo is null/empty; a broken existing photo produces a provider error, not an invented replacement.

Each PublicImage contains id, URL, alt, width, height, variants and a nullable group descriptor. Listing content includes galleryGroups for the group menu. Widths/heights are actual pixel dimensions. Use `variants` for HTML `srcset` and an appropriate `sizes` attribute. Use the returned HTTPS URLs unchanged. They need no cookies or key and are independent of affiliate, search dates and party. Only explicit public cover/gallery references are exposed; check-in instruction images are excluded.

## Direct listing availability

```sh
curl --fail-with-body --get \
  "https://api-preview.wikiup.app/api/travel/listings/$LISTING_ID/availability" \
  -H "Authorization: Bearer $WIKIUP_API_KEY" \
  --data-urlencode checkIn=2027-02-09 --data-urlencode checkOut=2027-02-12 \
  --data-urlencode adults=2 --data-urlencode children=0 --data-urlencode pets=0
```

Use dates/party only, with the same bounds/defaults. No destination/page/pageSize. Lookup resolves the ID directly without scanning regional result pages. Response includes listingId, `status: available | sold_out`, options, complete=true and generatedAt. Each option contains stable id, nullable physical roomId/roomTypeId, name, capacity/maxGuests, availableCount, image/imageVariants, currency, average nightlyRate, staySubtotal, explicit null taxes/fees/finalTotal and exact bookingUrl. Pooled options count only qualifying physical rooms free throughout the stay, without also returning those rooms as separate options.

Sold out is 200 with empty options. Provider failures are 503 with complete=false. Withdrawn, blacklisted or wrong-type IDs return 404. A hotel search card's bookingUrl opens property-level selection; individual room/rental URLs target the exact physical room or pool. The property-level link has its own signed target; never strip a room ID from a signed link. Preserve the whole returned URL, including dates, adults, children, pets, total humans and affiliateReferral. Opening it does not create a reservation or charge. Hosted checkout rechecks availability and final totals. Guests do not need staff sign-in.

## Send the guest to Wikiup checkout

1. Set `LISTING_ID` to the selected catalog ID, URL-encoded as one path segment, and make the direct availability request above with the guest's current dates and party.
2. Read `options`. For a hotel, let the guest choose a room or room type; for a rental, use its matching option. `status: sold_out` means there is no option to reserve. A request failure is not sold out.
3. Set the Reserve button's destination to the selected option's **entire returned `bookingUrl`**, unchanged. Navigate the guest's browser there. Never rebuild the query string, replace its room ID, use `contact.websiteUrl` instead, or attach your API key.
4. Wikiup collects guest details and payment, rechecks inventory, calculates final taxes/fees, and handles reservation confirmation and the guest portal. The signed `affiliateReferral` in the URL preserves attribution. The partner does not call the owner reservation endpoints; affiliate keys cannot use them.

The [Listing partners section](./#listing-partners) includes a populated options response with all fields. Its IDs and referral token are examples, not a usable checkout link. Use an actual API response for testing.

To check that an actual returned checkout URL loads, set `BOOKING_URL` to that selected option's exact value, then run:

```sh
curl --silent --show-error --fail-with-body --max-time 25 \
  "$BOOKING_URL" \
  -H 'Accept: text/html' \
  --output wikiup-checkout.html
```

This GET returns HTML, not booking JSON, and does not reserve inventory or charge a card. Do not send an Authorization header. The guest should navigate to the URL; do not serve the downloaded HTML from the partner site. Keep signed URLs out of logs and caches.

Refresh availability whenever dates or party counts change. A Reserve click is not booking success, and an option can become unavailable before checkout. Do not simulate confirmation. There is currently no partner booking-completion webhook; Wikiup's confirmation flow tells the guest the actual outcome.

## Freshness, errors and rate limits

All affiliate JSON, availability and checkout responses are no-store. Every availability response, including 401/403/404/405/422/429/503, uses:

```http
Cache-Control: private, no-store, max-age=0
CDN-Cache-Control: no-store
Cloudflare-CDN-Cache-Control: no-store
```

Never save completed availability, prices, counts or booking URLs in framework caches, a CDN, service worker, browser storage or a completed-request map. Do not use ETag/304 revalidation or stale fallbacks. Every new request checks the provider. Identical simultaneous requests may share an in-flight promise only when scoped to the same affiliate and exact criteria; remove it immediately on settlement. The Worker removes conditional validators on these routes.

The account shares one admitted request per second across its keys and all travel resources. Fetch content then availability sequentially and honor HTTP 429 `Retry-After: 1`; use bounded retries. Errors use `error`, optional complete=false, and validation details `{field,message}` for 422. 401 means missing/invalid credentials; 403 means disallowed key/access; 404 hides inaccessible listings/photos; 405 rejects methods; 422 is invalid input; 429 is rate limiting; 503 is provider/configuration failure. Never turn 503 into sold out or fake a booking success.

## Existing gallery conversion and photo changes

The preview-only background processor reads current public gallery references, preserving original bytes. It creates WebP thumbnails at 320/640/960/1440/1920 pixels where source size permits, corrects orientation, preserves proportions and never enlarges or crops. Smaller originals get their own width. Each output is decoded and read back before its storage manifest is published. A failed/partial run retries safely without advertising incomplete thumbnails.

Property listing photos are a dedicated owner-managed collection of up to 10 images; the first is the cover. Website slideshow/general-gallery images are no longer listing sources. Existing covers remain until edited. Room/unit photo sources stay separate. Thumbnails and their technical manifest use the existing storage bucket. See [listing photo management](/property-listing-photos.md).

Saving a new/replacement gallery photo makes it eligible for the next background scan; uploads and saves never generate thumbnails. Until ready, the public API returns the original image with real dimensions. A storage-generation hash versions each URL. Replacements produce new URLs on the next request; no availability response cache is involved. The scheduled workflow is preview-only and runs every five minutes once registered on the repository default branch. GitHub may delay scheduled starts. The initial scan and retries use the same resumable command:

```sh
node scripts/run-listing-thumbnails.mjs --inspect
node scripts/run-listing-thumbnails.mjs --apply
```

Both commands require the guarded preview configuration. They never load production configuration. Withdrawn references stop being served at the origin. CDN retirement requires the explicit purge configuration below; failed purges retain their manifest for retry instead of silently dropping cleanup work.

## Optional future Wikiup CDN configuration — inactive

CDN caching is currently intended for the separately managed consumer. Wikiup sends `Cloudflare-CDN-Cache-Control: no-store` on image responses to bypass its own edge, while keeping ordinary immutable image headers for browsers and the consumer. Cloudflare consumes its vendor-specific header before forwarding the response. Consumers must purge their own cached copies when photos are withdrawn. Wikiup performs current public-reference checks at the origin.

If Wikiup-side caching is authorized later, its explicit image-header bypass must also be changed. See `plan/travel-listings-preview/cache-rules.json` in the repository for exact preview-only rules. Merge these into the existing zone cache ruleset; never replace unrelated rules. Eligible immutable image responses are cacheable; errors are no-store. The final bypass rule for affiliate JSON and checkout must run after any cache-everything rule. Never cache Authorization-bearing JSON.

Configure `CLOUDFLARE_WIKIUP_ZONE_ID` and a zone-scoped `CLOUDFLARE_CACHE_PURGE_TOKEN` (Cache Purge permission) in the preview API environment secret. The same secret file supplies the scheduled job. It purges each photo’s versioned URL prefix, including original fallback URLs, before deleting retired thumbnail files. A small storage marker keeps failed retirement attempts available for the next background run. Rule editing separately needs Zone Cache Rules Edit. Do not claim CDN hits or purge activation without live evidence; see the verification record.

## Hidden San Diego migration

The separately managed Hidden San Diego repository must make these changes before using this contract:

- Remove its **20-second completed-response cache in `lib/availability-client.ts`**. Delete completed entries on settlement, not after a TTL. Fetch with `cache: 'no-store'` on the server and browser proxy; return the three no-store headers above. Remove service-worker/offline and framework cache paths for availability.
- Read `listings` directly, preserve stable IDs, and stop inferring hotels or grouping rooms.
- On navigation, fetch `/api/travel/listings/{id}` and fresh `/availability` for the current party. Do not reuse completed search options. Keep the existing affiliate secret server-side; do not ask guests to sign in.
- Use imageVariants/coverImage.variants in srcset; follow failures, pagination and Retry-After. Preserve returned bookingUrl unchanged.
- Deploy the consumer only after preview returns contractVersion 2. Legacy nested `results` remains available during migration; search-only keys remain unchanged. Production migration needs a separate release.

WikiupTravel is updated in this repository. Editing it does not update Hidden San Diego. Verification must name which consumer and environment were actually exercised.

## Optional photo groups

Owners may assign one arbitrary group to each public gallery photo in the console. `PublicImage.group` is `{ id, title }` or null; listing content also supplies `galleryGroups: [{ id, title, imageIds }]`, ordered by first gallery appearance, with Title Case titles. Existing gallery order, photos and thumbnail URLs are unchanged. Missing fields during rollout mean ungrouped photos. See [the grouped gallery API contract and Hidden San Diego implementation handoff](/listing-gallery-groups.md) for menu/thumbnail behavior, owner configuration, examples and acceptance checks. This does not implement the partner's listing page.

## 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.

## Hotel room pages before checkout

Use `GET /api/travel/listings/{listingId}/rooms/{roomId}` with an affiliate key
for date-free public content belonging to an exact hotel room or pooled room type.
Encode each ID once per path segment. It has no price or booking URL and remains
readable when sold out. Refresh parent availability, match the exact option ID,
and use that option’s returned bookingUrl unchanged. See the complete
[room-detail contract, cURL examples and integration steps](hotel-room-details.md)
and [RoomContentResponse schema](travel-listings.schema.json#/$defs/RoomContentResponse).

## 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.

## Date-free hotel room galleries

Use `GET /api/travel/listings/{listingId}/rooms?page=1` to render all active hotel
rooms or pooled room types below the property description without an availability
search. Follow `meta.nextPage` until null; twelve rooms per page. Each `rooms[]`
entry is the existing individual room-detail object, including its own gallery.
See [room collection and detail contract](hotel-room-details.md#browse-every-room-without-dates)
for cURL, populated JSON, field definitions, authorization and retry behavior.
This addition is local until deployment is verified.
