# Agency guide

As an agency you receive **offers**: creators Creator Guard matched to your search profile. This guide takes one offer from the moment it arrives to the signed creator, with runnable samples in curl, JavaScript and Python. Every status, field and rule is on [Agencies: offers & reservations](https://docs.creator-guard.com/agencies/). Matching stays with Creator Guard: you see your offers, never the marketplace. Offers with a creator's profile reach your account only after your agency passed our vetting; GET /v1/agency-profile shows the state.

Build it with a `cg_test_` key first: [test helpers](https://docs.creator-guard.com/agencies/#testing-with-a-test-key) create offers for you and play our payment and warranty steps.

## 1. Key and terms

Use an **agency key**; a referral partner's key gets [`403 wrong_account_type`](https://docs.creator-guard.com/errors/#wrong_account_type) on every agency endpoint. Writes need the current `agency_terms`, and accepting an offer also the current `warranty_terms` — without them [`403 terms_not_accepted`](https://docs.creator-guard.com/errors/#terms_not_accepted) names the missing `agreement_type`. Read the versions with `GET /v1/agreements` and accept with `POST /v1/agreements/{type}/accept`.

## 2. Keep your search profile current

`GET /v1/search-profile` returns what we match creators against; `PUT /v1/search-profile` replaces it as a whole, so read it, change what you need and send the whole object back. `flex` says per criterion how far a creator may deviate: [Search profile](https://docs.creator-guard.com/agencies/#search-profile-and-agency-profile).

## 3. Read your offers

React to `offer.created` with a [webhook](https://docs.creator-guard.com/webhooks/), or list your open offers:

curl:

```bash
BASE="${CG_API_BASE:-https://api.creator-guard.com}"
auth() { printf 'Authorization: Bearer %s\n' "$CG_API_KEY"; }   # read through a file descriptor: the key never shows in `ps`
api() {  # api METHOD PATH [JSON] [HEADER] → body on stdout; HTTP >= 400 → status + body on stderr, return 1
  local out
  out="$(curl -sS -X "$1" -H @<(auth) -H "Content-Type: application/json" ${4:+-H "$4"} ${3:+--data "$3"} \
    -w "\n%{http_code}" "$BASE$2")"
  [[ "${out##*$'\n'}" -lt 400 ]] || { echo "${out##*$'\n'} ${out%$'\n'*}" >&2; return 1; }
  printf "%s\n" "${out%$'\n'*}"
}
page="$(api GET "/v1/offers?status=offered&limit=100")"
jq -r '.data[] | "\(.id) \(.creator_ref) answer by \(.expires_at)"' <<<"$page"
```

JavaScript:

```js
const BASE = process.env.CG_API_BASE ?? 'https://api.creator-guard.com';
const res = await fetch(`${BASE}/v1/offers?status=offered&limit=100`, {
  headers: { Authorization: `Bearer ${process.env.CG_API_KEY}` },
});
const page = await res.json();
if (!res.ok) throw new Error(`${res.status} ${page.error.code}: ${page.error.message}`);
for (const offer of page.data) console.log(offer.id, offer.creator_ref, 'answer by', offer.expires_at);
if (page.has_more) console.log('more: pass next_cursor as starting_after');
```

Python:

```python
import json
import os
import urllib.error
import urllib.request

BASE = os.environ.get("CG_API_BASE", "https://api.creator-guard.com")

def call(method, path, body=None, headers=None):
    """(status, headers, JSON body); 4xx/5xx are returned, not raised: they carry error.code."""
    req = urllib.request.Request(BASE + path, method=method, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Authorization": "Bearer " + os.environ["CG_API_KEY"],
                                          "Content-Type": "application/json", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=30) as res:
            return res.status, res.headers, json.load(res)
    except urllib.error.HTTPError as err:
        return err.code, err.headers, json.load(err)

def fail(status, data):
    raise SystemExit(f"{status} {data['error']['code']}: {data['error']['message']}")

status, _, page = call("GET", "/v1/offers?status=offered&limit=100")
if status != 200:
    fail(status, page)
for offer in page["data"]:
    print(offer["id"], offer["creator_ref"], "answer by", offer["expires_at"])
if page["has_more"]:
    print("more: pass next_cursor as starting_after")
```

An open offer shows her name and creator number (`CR-…`), the listing with the deal and the fee, and `expires_at`. Her contact data follows only after payment. `GET /v1/offers/{id}/photos` returns the photos she agreed to share, as links valid for 1 hour.

curl:

```bash
BASE="${CG_API_BASE:-https://api.creator-guard.com}"
auth() { printf 'Authorization: Bearer %s\n' "$CG_API_KEY"; }   # read through a file descriptor: the key never shows in `ps`
api() {  # api METHOD PATH [JSON] [HEADER] → body on stdout; HTTP >= 400 → status + body on stderr, return 1
  local out
  out="$(curl -sS -X "$1" -H @<(auth) -H "Content-Type: application/json" ${4:+-H "$4"} ${3:+--data "$3"} \
    -w "\n%{http_code}" "$BASE$2")"
  [[ "${out##*$'\n'}" -lt 400 ]] || { echo "${out##*$'\n'} ${out%$'\n'*}" >&2; return 1; }
  printf "%s\n" "${out%$'\n'*}"
}
id="$(api GET "/v1/offers?limit=1" | jq -r '.data[0].id // empty')"
[[ -n "$id" ]] || { echo "no offers yet" >&2; exit 1; }
offer="$(api GET "/v1/offers/$id")"
jq -r '"\(.id) \(.creator_ref) \(.status) expires \(.expires_at)"' <<<"$offer"
```

JavaScript:

```js
const BASE = process.env.CG_API_BASE ?? 'https://api.creator-guard.com';
const headers = { Authorization: `Bearer ${process.env.CG_API_KEY}` };
async function get(path) {
  const res = await fetch(`${BASE}${path}`, { headers });
  const data = await res.json();
  if (!res.ok) throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
  return data;
}
const [first] = (await get('/v1/offers?limit=1')).data;
if (!first) throw new Error('no offers yet');
const offer = await get(`/v1/offers/${first.id}`);
console.log(offer.id, offer.creator_ref, offer.status, 'expires', offer.expires_at);
```

Python:

```python
import json
import os
import urllib.error
import urllib.request

BASE = os.environ.get("CG_API_BASE", "https://api.creator-guard.com")

def call(method, path, body=None, headers=None):
    """(status, headers, JSON body); 4xx/5xx are returned, not raised: they carry error.code."""
    req = urllib.request.Request(BASE + path, method=method, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Authorization": "Bearer " + os.environ["CG_API_KEY"],
                                          "Content-Type": "application/json", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=30) as res:
            return res.status, res.headers, json.load(res)
    except urllib.error.HTTPError as err:
        return err.code, err.headers, json.load(err)

def fail(status, data):
    raise SystemExit(f"{status} {data['error']['code']}: {data['error']['message']}")

status, _, page = call("GET", "/v1/offers?limit=1")
if status != 200:
    fail(status, page)
if not page["data"]:
    raise SystemExit("no offers yet")
status, _, offer = call("GET", f"/v1/offers/{page['data'][0]['id']}")
if status != 200:
    fail(status, offer)
print(offer["id"], offer["creator_ref"], offer["status"], "expires", offer["expires_at"])
```

Every offer carries `next_actions`, so you never have to re-implement which step is allowed when.

Every offer also carries `match`: how well she fits your [search profile](#2-keep-your-search-profile-current), as `score` of `total` criteria (a close match counts ½; sort by `score` / `total`) and `knocked_out` when a must-match criterion is missed. It names criteria (`languages`, `niche`, …) and results only, never her values, and is `null` while you have no search profile.

## 4. Accept or decline

`POST /v1/offers/{id}/accept` reserves her for you and creates a reservation awaiting payment. Only one agency can win her: [`409 offer_taken`](https://docs.creator-guard.com/errors/#offer_taken) means another agency was first, [`409 offer_expired`](https://docs.creator-guard.com/errors/#offer_expired) that the deadline passed, [`409 listing_unavailable`](https://docs.creator-guard.com/errors/#listing_unavailable) that her listing was taken off the market.

curl:

```bash
BASE="${CG_API_BASE:-https://api.creator-guard.com}"
auth() { printf 'Authorization: Bearer %s\n' "$CG_API_KEY"; }   # read through a file descriptor: the key never shows in `ps`
api() {  # api METHOD PATH [JSON] [HEADER] → body on stdout; HTTP >= 400 → status + body on stderr, return 1
  local out
  out="$(curl -sS -X "$1" -H @<(auth) -H "Content-Type: application/json" ${4:+-H "$4"} ${3:+--data "$3"} \
    -w "\n%{http_code}" "$BASE$2")"
  [[ "${out##*$'\n'}" -lt 400 ]] || { echo "${out##*$'\n'} ${out%$'\n'*}" >&2; return 1; }
  printf "%s\n" "${out%$'\n'*}"
}
id="$(api GET "/v1/offers?status=offered&limit=1" | jq -r '.data[0].id // empty')"
[[ -n "$id" ]] || { echo "no open offer" >&2; exit 1; }
# 409 offer_taken / offer_expired / listing_unavailable: someone else was faster or the deadline passed.
offer="$(api POST "/v1/offers/$id/accept" "" "Idempotency-Key: $(uuidgen)")"
echo "$id → $(jq -r .status <<<"$offer") — pay the reservation before its due date"
```

JavaScript:

```js
const BASE = process.env.CG_API_BASE ?? 'https://api.creator-guard.com';
const headers = { Authorization: `Bearer ${process.env.CG_API_KEY}` };
const list = await fetch(`${BASE}/v1/offers?status=offered&limit=1`, { headers });
const [offer] = (await list.json()).data ?? [];
if (!offer) throw new Error('no open offer');
const res = await fetch(`${BASE}/v1/offers/${offer.id}/accept`, {
  method: 'POST', headers: { ...headers, 'Idempotency-Key': crypto.randomUUID() },
});
const data = await res.json();
let outcome;
if (res.ok) outcome = data.status; // reserved: pay the reservation before the due date
else if (['offer_taken', 'offer_expired', 'listing_unavailable'].includes(data.error.code)) outcome = data.error.code;
else if (data.error.code === 'terms_not_accepted') outcome = `accept ${data.error.agreement_type} first`;
else throw new Error(`${res.status} ${data.error.code}: ${data.error.message}`);
console.log(offer.id, '→', outcome);
```

Python:

```python
import json
import os
import urllib.error
import urllib.request
import uuid

BASE = os.environ.get("CG_API_BASE", "https://api.creator-guard.com")

def call(method, path, body=None, headers=None):
    """(status, headers, JSON body); 4xx/5xx are returned, not raised: they carry error.code."""
    req = urllib.request.Request(BASE + path, method=method, data=None if body is None else json.dumps(body).encode(),
                                 headers={"Authorization": "Bearer " + os.environ["CG_API_KEY"],
                                          "Content-Type": "application/json", **(headers or {})})
    try:
        with urllib.request.urlopen(req, timeout=30) as res:
            return res.status, res.headers, json.load(res)
    except urllib.error.HTTPError as err:
        return err.code, err.headers, json.load(err)

def fail(status, data):
    raise SystemExit(f"{status} {data['error']['code']}: {data['error']['message']}")

status, _, page = call("GET", "/v1/offers?status=offered&limit=1")
if status != 200:
    fail(status, page)
if not page["data"]:
    raise SystemExit("no open offer")
offer = page["data"][0]
status, _, data = call("POST", f"/v1/offers/{offer['id']}/accept", None, {"Idempotency-Key": str(uuid.uuid4())})
if status == 200:
    outcome = data["status"]  # reserved: pay the reservation before the due date
elif data["error"]["code"] in ("offer_taken", "offer_expired", "listing_unavailable"):
    outcome = data["error"]["code"]
elif data["error"]["code"] == "terms_not_accepted":
    outcome = f"accept {data['error']['agreement_type']} first"
else:
    fail(status, data)
print(offer["id"], "->", outcome)
```

Changed your mind? `POST /v1/offers/{id}/undo-accept` works for a few minutes after accepting (`undo_until`) and only before payment. Not a fit? `POST /v1/offers/{id}/decline` with a `note` of 50–500 characters.

## 5. Pay the reservation

Payment happens outside the API: transfer the `amount` with the `payment_reference` before `payment_due_at`. When we have it, the reservation becomes `paid` and you receive `reservation.paid`.

## 6. Reach her and report progress

Once the reservation is paid, `GET /v1/reservations/{id}/creator` returns her name, Instagram, other contact, platforms, followers, niche and creator number; before payment it answers [`409 payment_pending`](https://docs.creator-guard.com/errors/#payment_pending). You never learn who referred her.

Report what happens with `POST /v1/offers/{id}/mark-contacted`, `POST /v1/offers/{id}/mark-in-talks`, `POST /v1/offers/{id}/mark-signed` or `POST /v1/offers/{id}/mark-lost` (with an `outcome_reason`; only before you paid — after payment it answers `409 deal_paid`, and a warranty claim is the way out).

## 7. Warranty claim

While the warranty runs (`warranty_until` on the reservation) you can file **one** claim with `POST /v1/reservations/{id}/warranty-claim`, giving a `reason`. A second claim answers [`409 claim_exists`](https://docs.creator-guard.com/errors/#claim_exists), one after the warranty [`409 warranty_expired`](https://docs.creator-guard.com/errors/#warranty_expired). Reasons and outcomes: [Reservations](https://docs.creator-guard.com/agencies/#reservations).

## Keep in step

Subscribe to the `offer.*`, `reservation.*` and `warranty_claim.created` events ([Webhooks](https://docs.creator-guard.com/webhooks/)); they fire the same way whether you act in the portal or through the API. Agencies refer creators too: [Referral partner guide](https://docs.creator-guard.com/guides/referral-partners/). The [SDKs](https://docs.creator-guard.com/sdks/) handle retries, idempotency keys and pagination for you.
