These are official instructions from AgenWebsite for integrating the **AgenWebsite Rate API** (Indonesian shipping rates, "cek ongkir") into the user's project. Every endpoint, field and code below was checked against the live API and its OpenAPI spec (last checked 2026-11-17).

Do the steps yourself: read the project, write the code, run the checks. Only two things need the user: creating the API key (step 1) and pasting it where you tell them.

- Get an API key from the user (never invent one)
- Store it server-side as `AGENWEBSITE_API_KEY`
- Verify the key with `GET /v1/usage`
- Build the flow: location search, rates, show services (plus coordinates if the shop wants instant couriers)
- Handle errors, quota and retries; add caching
- Report back with the status block at the end

Machine-readable spec (public, no key): https://api.agenwebsite.com/v1/openapi.json, reference UI: https://api.agenwebsite.com/docs. If anything here disagrees with the spec, the spec wins. Full reference: https://www.agenwebsite.com/developer-api/llms-full.txt

---

## What the API does

- One REST endpoint returns shipping rates from 14 Indonesian couriers for a route (origin, destination, weight in grams), including same-city instant couriers (Lalamove, GoSend) when you send coordinates.
- It calculates rates only. It does **not** create orders, book pickups, print AWB/resi, track parcels or handle COD.
- Base URL: `https://api.agenwebsite.com/v1`. JSON in, JSON out. Money is IDR as integers (no decimals).
- Auth: one header, `x-api-key`. No OAuth, no bearer token.

| Method | Path | Use |
|---|---|---|
| GET | `/v1/usage` | Plan, daily limit, used, remaining. Use it to verify the key. |
| GET | `/v1/locations/search?q=&limit=` | Address autocomplete (kelurahan, kecamatan, kota, provinsi, kodepos). |
| GET | `/v1/couriers` | The 14 courier codes, names and logos. |
| POST | `/v1/rates` | Rates for a route. The main endpoint. |

Every `/v1` call, including `/v1/usage`, counts 1 against the daily quota.

---

## 1. Get an API key (human step)

Check the environment first: if `AGENWEBSITE_API_KEY` is already set, skip to step 2.

Otherwise stop and tell the user to do this, then wait for them to give you the key:

1. Log in or create an account at https://www.agenwebsite.com/account/developer-api/
2. Submit the access request there (a short description of the use case). The AgenWebsite team approves it.
3. After approval, click **Generate** to create a key. The secret is shown **once**; copy it.

A key looks like `awk_live_` followed by 32 lowercase hex characters (`awk_live_0123456789abcdef0123456789abcdef`). Reject anything else before calling the API.

Never make up a key, never use a placeholder key in committed code, and never print the full key back in chat or logs (show the last 4 characters at most).

## 2. Store the key server-side

- Put it in the server environment as `AGENWEBSITE_API_KEY` (`.env`, `.env.local`, hosting dashboard, or secret manager). Add the file to `.gitignore` if it is not there already.
- Add `AGENWEBSITE_API_KEY=` (empty) to `.env.example` if the project has one.
- **Server-side only.** Never ship the key in browser JavaScript, a `NEXT_PUBLIC_`/`VITE_`/`EXPO_PUBLIC_` variable, a mobile app bundle, or HTML. The API sends no CORS headers, so browser calls fail anyway. The browser calls *your* backend; your backend calls AgenWebsite.
- Quota is per account and shared by all its keys. Extra keys do not add quota; use them to separate staging and production.

## 3. Verify the key

```bash
curl -s https://api.agenwebsite.com/v1/usage -H "x-api-key: $AGENWEBSITE_API_KEY"
```

Expected (`200`):

```json
{ "success": true, "data": { "plan": "free", "limit": 150, "used": 1, "remaining": 149, "reset_at": "2026-11-18T00:00:00+07:00" } }
```

`401 unauthorized` means the key is missing, mistyped, revoked, or the access request is not approved yet. Ask the user to check the key in https://www.agenwebsite.com/account/developer-api/. Do not keep retrying.

## 4. Build the integration flow

### 4a. Location search (address autocomplete)

```bash
curl -s -G https://api.agenwebsite.com/v1/locations/search \
  -H "x-api-key: $AGENWEBSITE_API_KEY" \
  --data-urlencode "q=coblong" --data-urlencode "limit=5"
```

```json
{
  "success": true,
  "data": [
    {
      "subdistrict_id": null,
      "postal_code": "40132",
      "subdistrict": "Lebak Siliwangi",
      "district": "Coblong",
      "city": "Bandung",
      "province": "Jawa Barat",
      "label": "Lebak Siliwangi, Coblong, Bandung, Jawa Barat, 40132"
    }
  ],
  "meta": { "count": 1, "query": "coblong" }
}
```

- `q`: 2 to 100 characters. Matches kelurahan, kecamatan, kota or provinsi names; a number also matches the start of a kodepos. `limit`: 1 to 50, default 10.
- Indonesian address levels: `subdistrict` = kelurahan/desa, `district` = kecamatan, `city` = kota/kabupaten, `province` = provinsi, `postal_code` = kodepos (5 digits).
- `data` is a flat array. Show `label` in the dropdown. `subdistrict_id` can be `null`; do not depend on it (`/v1/rates` does not accept it).
- Debounce input (300 ms) and only search from 3 characters in your UI. Every search costs 1 quota.

### 4b. Rates

```bash
curl -s -X POST https://api.agenwebsite.com/v1/rates \
  -H "x-api-key: $AGENWEBSITE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "shipper":     { "province": "Jawa Barat", "city": "Bandung", "district": "Coblong", "subdistrict": "Lebak Siliwangi" },
    "destination": { "zipcode": "10110" },
    "weight": 1200,
    "couriers": ["jne", "jnt", "sicepat"],
    "sort": "cheapest"
  }'
```

Request body:

| Field | Type | Required | Notes |
|---|---|---|---|
| `shipper`, `destination` | object | yes | Each is **either** `{ "zipcode": "40132" }` **or** `{ "province", "city", "district" }` plus optional `"subdistrict"`. |
| `weight` | integer | yes | Grams, greater than 0. `1200` = 1.2 kg. The server converts to each courier's unit. |
| `dimensions` | object | no | `{ "length", "width", "height" }` in cm, all three required when sent. |
| `shipper.latlng`, `destination.latlng` | string | no | `"latitude,longitude"` in decimal degrees, e.g. `"-6.2245,106.8296"`. Sits next to `zipcode`/region, never instead of it. Needed on **both** parties for instant couriers (section 4d). |
| `couriers` | string[] | no | Up to 14 codes from section 5. Omit to get all couriers (still 1 quota). |
| `sort` | string | no | `"cheapest"` (by cost) or `"fastest"` (by `etd_max_days`). |

- The field is `zipcode`, not `postal_code`. Unknown fields are silently dropped, so `{ "postal_code": "40132" }` arrives as an empty location and returns `400 validation_error`.
- Most precise: pass the `province`, `city`, `district` and `subdistrict` from the location the user picked. A kodepos alone works but can cover several kelurahan.

Real response (`200`), captured 2026-11-17 for `40132` → `10110`, 1000 g, all couriers, `sort: "cheapest"`. It had 37 lines from 11 couriers; shown here trimmed to the cheapest and the fastest line:

```json
{
  "success": true,
  "currency": "IDR",
  "data": {
    "rates": [
      {
        "courier_code": "sicepat",
        "courier_name": "SiCepat",
        "courier_logo_url": "https://assets-agenwebsite.b-cdn.net/images/couriers/sicepat.png",
        "service_code": "sicepat_halu",
        "service_name": "EKONOMIS",
        "service_type": "regular",
        "cost": 7500,
        "cost_formatted": "Rp 7.500",
        "etd_min_days": 3,
        "etd_max_days": 5,
        "etd_text": "3-5 days",
        "estimated_delivery": { "from": "2026-11-20", "to": "2026-11-22" },
        "cheapest": true,
        "fastest": false,
        "source": "live"
      },
      {
        "courier_code": "anteraja",
        "courier_name": "AnterAja",
        "courier_logo_url": "https://assets-agenwebsite.b-cdn.net/images/couriers/anteraja.png",
        "service_code": "anteraja_sd",
        "service_name": "Anteraja Same Day",
        "service_type": "regular",
        "cost": 35300,
        "cost_formatted": "Rp 35.300",
        "etd_min_days": 0,
        "etd_max_days": 0,
        "etd_text": "0 days",
        "estimated_delivery": { "from": "2026-11-17", "to": "2026-11-17" },
        "cheapest": false,
        "fastest": true,
        "source": "live"
      }
    ],
    "cheapest": { "service_code": "sicepat_halu", "cost": 7500 },
    "fastest": { "service_code": "anteraja_sd", "etd_max_days": 0 },
    "summary": { "count": 37, "cost_range": { "min": 7500, "max": 1200000 } }
  },
  "rate_limit": { "limit": 30000, "remaining": 29964, "reset_at": "2026-11-18T00:00:00+07:00" }
}
```

On that route SiCepat, POS, Lion, SPX, J&T, AnterAja, SAP, JNE, RPX, Paxel and J&T Cargo answered. TIKI had no service, and GoSend/Lalamove were left out because no coordinates were sent. The result also contains cargo and special services (e.g. `pos_kargo_motor` Rp 405.000, `jne_jtr_200` Rp 1.200.000); filter them in your UI if they don't fit the shop.

### 4c. Show the services

- One row per item in `data.rates`: logo (`courier_logo_url`), `courier_name` + `service_name`, price, estimate.
- Price: `cost` is an integer in Rupiah. Display `cost_formatted` ("Rp 14.000", dot as thousands separator). Never show decimals.
- Estimate: `etd_text` is English ("2-3 days", "1-3 hours"). For Indonesian UI build it from `etd_min_days`/`etd_max_days`: "2-3 hari" (or "3 hari" when equal, "hari ini" for 0). For `service_type: "instant"` the days are 0 and `etd_text` holds hours: show it as "1-3 jam". `estimated_delivery.from/to` are `YYYY-MM-DD` dates in WIB.
- Badges: `cheapest` and `fastest` are already computed per row; `data.cheapest`/`data.fastest` are shortcuts.
- `service_code` values carry the courier prefix (`jne_reg`, `sicepat_halu`, `lalamove_motorcycle`). Still store `courier_code` + `service_code` together for the chosen rate.
- Re-validate the chosen rate on your server at checkout (call `/v1/rates` again or read your cache). Never trust a price posted from the browser.

### 4d. Instant couriers and coordinates (optional)

Lalamove and GoSend (and Paxel's instant services) price by distance, so they need the exact pickup and drop-off point:

- Add `latlng: "latitude,longitude"` to **both** `shipper` and `destination`, next to the `zipcode` or region (never instead of it).
- Without coordinates they are left out of the result. If the request asks **only** for `lalamove` and/or `gosend` without them, the API returns `400 validation_error` with `field` `"shipper.latlng"` or `"destination.latlng"`. A malformed `latlng` is also a 400.
- Same-city routes only. On an intercity route they return no lines.
- Their lines have `service_type: "instant"`, `etd_min_days`/`etd_max_days` = 0, an hour range in `etd_text` ("1-3 hours"; GoSend Sameday "8-12 hours") and today's date in `estimated_delivery`. They usually win `fastest`.
- Service codes: `lalamove_motorcycle`, `lalamove_sedan`, `lalamove_mpv`, `lalamove_van`, `gosend_instantgojek`, `gosend_samedaygojek`.

Ask the user whether the shop wants instant delivery before building this. If yes:

1. Store the shop's pickup coordinates in server config next to its origin address.
2. After the buyer picks an address, ask for a map pin (or the browser's geolocation) and send it as `destination.latlng`. A kodepos alone is not enough for distance pricing.
3. Send `latlng` only when the buyer is in the shop's city; otherwise leave it out and show regular couriers.

```bash
curl -s -X POST https://api.agenwebsite.com/v1/rates \
  -H "x-api-key: $AGENWEBSITE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "shipper":     { "zipcode": "12190", "latlng": "-6.2245,106.8296" },
    "destination": { "zipcode": "10310", "latlng": "-6.1951,106.8231" },
    "weight": 3000,
    "couriers": ["lalamove", "gosend"],
    "sort": "cheapest"
  }'
```

Live result on 2026-11-17 (Jakarta Selatan → Jakarta Pusat, 3 kg): Lalamove Motorcycle Rp 11.446, Sedan Rp 47.932, MPV Rp 50.487, Van Rp 65.510 (all "1-3 hours"); GoSend Sameday Rp 16.800 ("8-12 hours"), GoSend Instant Rp 19.425 ("1-3 hours").

## 5. Couriers

`GET /v1/couriers` returns `data[]` with `courier_code`, `courier_name`, `logo_url`, `cod_supported`, `insurance_supported`. Valid codes for `couriers[]`:

| Code | Courier | Code | Courier |
|---|---|---|---|
| `jnt` | J&T Express | `gosend` | GoSend |
| `jne` | JNE | `rpx` | RPX |
| `sicepat` | SiCepat | `lion` | Lion Parcel |
| `pos` | POS Indonesia | `sap` | SAP Express |
| `anteraja` | AnterAja | `spx` | SPX Express |
| `tiki` | TIKI | `jtc` | J&T Cargo |
| `paxel` | Paxel | `lalamove` | Lalamove |

`cod_supported` means a shipment with that courier can be booked as cash on delivery through AgenWebsite; `insurance_supported` means shipping insurance can be added. COD is not available for POS Indonesia, Paxel, GoSend and Lalamove. Insurance is available for every courier except GoSend and Lalamove (TIKI and RPX are listed as supported). The Rate API itself never adds COD or insurance fees to `cost`. Read the flags from the endpoint rather than hardcoding them.

Any other code returns `422 unsupported_courier` (codes are case-insensitive). Not every courier serves every route; a courier with no service simply has no rows. Lalamove and GoSend also need coordinates (section 4d).

## 6. Errors, quota and retries

Every error has the same shape. Check `success`, not only the HTTP status, and log `request_id`.

```json
{ "success": false, "error": { "code": "validation_error", "message": "...", "field": "shipper", "request_id": "req_mwkix1miy8vj39u9" } }
```

| HTTP | `code` | Meaning | Do |
|---|---|---|---|
| 400 | `validation_error` | Bad body or query; `field` names the culprit (e.g. `shipper`, `weight`, `destination.latlng`). | Fix the input. Do not retry. |
| 401 | `unauthorized` | Key missing, malformed, unknown or revoked. | Stop. Ask the user to check the key. |
| 422 | `unsupported_courier` | A code outside the 14 above. | Fix `couriers[]`. |
| 429 | `rate_limit_exceeded` | Per-minute burst or daily quota used up. | Wait `Retry-After` seconds. |
| 502 | `courier_upstream_error` | No usable rate came back: courier outage, or a location that cannot be resolved / has no service. | Retry once or twice with backoff; if it persists for the same input, ask the user to pick the address again from location search. |
| 500 | `internal_error` | Server error. | Retry with backoff; report `request_id` if it persists. |

Rate limit headers on authenticated responses:

- `X-RateLimit-Limit`: daily quota of the plan.
- `X-RateLimit-Remaining`: requests left today.
- `X-RateLimit-Reset`: Unix time (seconds) of the next reset, 00:00 WIB (UTC+7).
- `Retry-After` (on 429 only): seconds to wait. About a minute for a burst limit; until 00:00 WIB when the daily quota is gone.
- On a burst 429, `X-RateLimit-Remaining` reads `0` even if daily quota is left. On 401 and other pre-auth errors these headers describe a per-IP guard (1200 requests/minute), not your plan.

| Plan | Requests/day | Requests/minute | Active keys | Price |
|---|---|---|---|---|
| Free | 150 | 20 | 2 | Rp 0 |
| Pro | 30.000 | 300 | 5 | Rp 129.000/month |
| Max | 60.000 | 600 | 20 | Rp 229.000/month |

Retry policy: retry only 429, 502, 500 and network errors. At most 3 attempts, exponential backoff with jitter (1 s, 2 s, 4 s), and always honour `Retry-After`. Never retry 400, 401 or 422. Use a request timeout of about 15 seconds.

## 7. Caching

- `/v1/couriers`: cache 24 hours.
- `/v1/locations/search`: cache per normalized `q` for 24 hours. Address data barely changes.
- `/v1/rates`: cache per (origin, destination, weight, couriers) for 15 to 30 minutes. The API caches identical requests for 30 minutes, but every call still costs quota, so cache on your side too.
- Call rates only when the user has an origin, a destination and a weight. Not on every keystroke, not on product listing pages.
- Request all couriers in one call instead of one call per courier.

---

## 8. Recipes

Pick the one that matches the project. Keep the key in the environment in every case.

### Node.js / Next.js (App Router route handlers)

`lib/agenwebsite.ts`:

```ts
const BASE = "https://api.agenwebsite.com/v1";

export class AgenWebsiteError extends Error {
  constructor(public status: number, public code: string, message: string, public requestId?: string) {
    super(message);
  }
}

export async function aw<T>(path: string, init: RequestInit = {}, attempt = 1): Promise<T> {
  const key = process.env.AGENWEBSITE_API_KEY;
  if (!key) throw new Error("AGENWEBSITE_API_KEY is not set");
  const res = await fetch(BASE + path, {
    ...init,
    headers: { "x-api-key": key, "Content-Type": "application/json", ...(init.headers || {}) },
    signal: AbortSignal.timeout(15000),
    cache: "no-store",
  });
  const json = await res.json().catch(() => null);
  if (res.ok && json?.success) return json as T;
  const retryable = res.status === 429 || res.status >= 500;
  if (retryable && attempt < 3) {
    const wait = Number(res.headers.get("retry-after")) * 1000 || 2 ** attempt * 500 + Math.random() * 250;
    if (wait <= 10000) {
      await new Promise((r) => setTimeout(r, wait));
      return aw<T>(path, init, attempt + 1);
    }
  }
  const e = json?.error ?? {};
  throw new AgenWebsiteError(res.status, e.code ?? "http_error", e.message ?? res.statusText, e.request_id);
}
```

`app/api/shipping/locations/route.ts`:

```ts
import { aw } from "@/lib/agenwebsite";

export async function GET(req: Request) {
  const q = new URL(req.url).searchParams.get("q")?.trim() ?? "";
  if (q.length < 3) return Response.json({ data: [] });
  const json = await aw<{ data: unknown[] }>(`/locations/search?q=${encodeURIComponent(q)}&limit=10`);
  return Response.json({ data: json.data }, { headers: { "Cache-Control": "public, max-age=86400" } });
}
```

`app/api/shipping/rates/route.ts`:

```ts
import { aw, AgenWebsiteError } from "@/lib/agenwebsite";

const cache = new Map<string, { at: number; body: unknown }>();
const TTL = 20 * 60 * 1000;

export async function POST(req: Request) {
  const { shipper, destination, weight, couriers } = await req.json();
  const body = { shipper, destination, weight: Math.max(1, Math.round(Number(weight))), couriers, sort: "cheapest" };
  const key = JSON.stringify(body);
  const hit = cache.get(key);
  if (hit && Date.now() - hit.at < TTL) return Response.json(hit.body);
  try {
    const json = await aw<{ data: unknown }>("/rates", { method: "POST", body: key });
    cache.set(key, { at: Date.now(), body: json.data });
    return Response.json(json.data);
  } catch (e) {
    if (e instanceof AgenWebsiteError) {
      return Response.json({ error: e.code, message: e.message }, { status: e.status === 401 ? 500 : e.status });
    }
    throw e;
  }
}
```

On serverless, the in-memory `Map` is per instance; use the platform cache (Redis/KV) if the project already has one. Express/Fastify: same `aw()` helper inside a route.

### Laravel

`config/services.php`: `'agenwebsite' => ['key' => env('AGENWEBSITE_API_KEY')],`

`app/Services/AgenWebsiteRates.php`:

```php
<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;

class AgenWebsiteRates
{
    private function client()
    {
        return Http::baseUrl('https://api.agenwebsite.com/v1')
            ->withHeaders(['x-api-key' => config('services.agenwebsite.key')])
            ->acceptJson()
            ->timeout(15)
            ->retry(3, fn (int $attempt) => 2 ** $attempt * 500, function ($e) {
                $status = optional($e->response ?? null)->status();
                return $status === null || $status === 429 || $status >= 500;
            }, throw: false);
    }

    public function searchLocations(string $q): array
    {
        return Cache::remember('aw:loc:' . md5(mb_strtolower(trim($q))), 86400,
            fn () => $this->client()->get('/locations/search', ['q' => $q, 'limit' => 10])->throw()->json('data'));
    }

    public function rates(array $shipper, array $destination, int $grams, ?array $couriers = null): array
    {
        $body = array_filter(compact('shipper', 'destination', 'couriers') + ['weight' => max(1, $grams), 'sort' => 'cheapest']);
        return Cache::remember('aw:rates:' . md5(json_encode($body)), 1200,
            fn () => $this->client()->post('/rates', $body)->throw()->json('data'));
    }
}
```

Expose it through your own controller (`Route::post('/shipping/rates', ...)`), validate the input with a FormRequest, and catch `Illuminate\Http\Client\RequestException` to map `error.code` to a friendly message.

### Plain PHP (cURL)

```php
<?php
function agenwebsite_request(string $method, string $path, ?array $body = null): array
{
    $ch = curl_init('https://api.agenwebsite.com/v1' . $path);
    curl_setopt_array($ch, [
        CURLOPT_CUSTOMREQUEST  => $method,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 15,
        CURLOPT_HTTPHEADER     => ['x-api-key: ' . getenv('AGENWEBSITE_API_KEY'), 'Content-Type: application/json'],
        CURLOPT_POSTFIELDS     => $body === null ? null : json_encode($body),
    ]);
    $raw    = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    $json = json_decode((string) $raw, true);
    if ($status !== 200 || empty($json['success'])) {
        $code = $json['error']['code'] ?? 'http_' . $status;
        throw new RuntimeException($code . ': ' . ($json['error']['message'] ?? 'request failed'), $status);
    }
    return $json;
}

$rates = agenwebsite_request('POST', '/rates', [
    'shipper'     => ['zipcode' => '40132'],
    'destination' => ['zipcode' => '10110'],
    'weight'      => 1000,
])['data']['rates'];
```

Wrap it in a retry for 429/5xx (honour `Retry-After`) and cache results in APCu, Redis or a file cache.

### Python

```python
import os, time, random, requests

BASE = "https://api.agenwebsite.com/v1"
session = requests.Session()
session.headers.update({"x-api-key": os.environ["AGENWEBSITE_API_KEY"]})

class AgenWebsiteError(Exception):
    def __init__(self, status, code, message, request_id=None):
        super().__init__(f"{status} {code}: {message}")
        self.status, self.code, self.request_id = status, code, request_id

def aw(method, path, **kwargs):
    for attempt in range(1, 4):
        r = session.request(method, BASE + path, timeout=15, **kwargs)
        body = r.json() if r.headers.get("content-type", "").startswith("application/json") else {}
        if r.ok and body.get("success"):
            return body
        if (r.status_code == 429 or r.status_code >= 500) and attempt < 3:
            wait = float(r.headers.get("Retry-After") or (2 ** attempt * 0.5 + random.random() / 4))
            if wait <= 10:
                time.sleep(wait)
                continue
        err = body.get("error", {})
        raise AgenWebsiteError(r.status_code, err.get("code", "http_error"), err.get("message", r.reason), err.get("request_id"))

locations = aw("GET", "/locations/search", params={"q": "coblong", "limit": 5})["data"]
rates = aw("POST", "/rates", json={
    "shipper": {"zipcode": "40132"},
    "destination": {"zipcode": "10110"},
    "weight": 1000,
})["data"]["rates"]
```

In Django/Flask/FastAPI, call `aw()` from your own endpoint and cache with the framework cache (`django.core.cache`, Redis, `functools.lru_cache` with a TTL wrapper).

### Headless WooCommerce

The storefront (Next.js, Nuxt, etc.) talks to WooCommerce through its REST API; rates come from the Rate API through your backend:

1. Checkout address form uses your `/api/shipping/locations` route (recipe above) for kecamatan/kelurahan autocomplete.
2. Origin = the store's warehouse address (store it in server config). Weight = sum of `weight × quantity` of the cart items in grams. WooCommerce stores weight in the unit set under WooCommerce > Settings > Products (often kg), so convert.
3. Call your `/api/shipping/rates` route and let the buyer pick a service.
4. When creating the order server-side (`POST /wp-json/wc/v3/orders` with the store's consumer key, never from the browser), re-fetch the rate and add it as a shipping line:

```json
"shipping_lines": [
  { "method_id": "agenwebsite_rate_api", "method_title": "JNE - Layanan Reguler (2-3 hari)", "total": "14000" }
]
```

If the store uses the normal WooCommerce checkout (not headless), tell the user that the AgenWebsite Shipping plugin already does this inside WooCommerce: https://www.agenwebsite.com/products/agenwebsite-shipping/. Only build a custom `WC_Shipping_Method` on the Rate API if they still want it.

### Joomla / EasyStore

Keep the key on the server in a Joomla plugin and let the checkout call it through `com_ajax`. System plugin `plugins/system/agenwebsiterates/agenwebsiterates.php` (Joomla 4/5; add the usual XML manifest with a `api_key` field of `type="password"`):

```php
<?php
defined('_JEXEC') or die;

use Joomla\CMS\Factory;
use Joomla\CMS\Http\HttpFactory;
use Joomla\CMS\Plugin\CMSPlugin;

class PlgSystemAgenwebsiterates extends CMSPlugin
{
    public function onAjaxAgenwebsiterates()
    {
        $input = Factory::getApplication()->getInput();
        $key   = getenv('AGENWEBSITE_API_KEY') ?: $this->params->get('api_key');
        $http  = HttpFactory::getHttp();
        $head  = ['x-api-key' => $key, 'Content-Type' => 'application/json'];
        $base  = 'https://api.agenwebsite.com/v1';

        if ($input->getCmd('task') === 'locations') {
            $res = $http->get($base . '/locations/search?limit=10&q=' . rawurlencode($input->getString('q')), $head, 15);
        } else {
            $body = [
                'shipper'     => ['zipcode' => $this->params->get('origin_zipcode')],
                'destination' => ['zipcode' => $input->getString('zipcode')],
                'weight'      => max(1, $input->getInt('weight')),
            ];
            $res = $http->post($base . '/rates', json_encode($body), $head, 15);
        }

        return json_decode($res->body, true);
    }
}
```

Call it from the checkout with `index.php?option=com_ajax&plugin=agenwebsiterates&group=system&format=json&task=rates&zipcode=10110&weight=1200`. For EasyStore, find how the installed version defines shipping methods (look in the site's `plugins/` folder and EasyStore's settings) and feed the chosen rate into it. Ask the user before editing EasyStore's own files; prefer a separate plugin that survives updates.

---

## 9. Done checklist

Confirm each item before you report:

- [ ] `AGENWEBSITE_API_KEY` is read from the server environment; `grep -rE "awk_(live|test)_[0-9a-f]{32}" .` finds no key in the code, and no client-side bundle references it.
- [ ] `GET /v1/usage` returns `200` with the user's plan.
- [ ] Location search returns results for "coblong" and the UI shows `label`.
- [ ] A rates call for `40132` to `10110`, 1000 g returns at least one rate, shown with Rupiah price and estimate.
- [ ] If instant delivery was wanted: a same-city call with `latlng` on both parties returns Lalamove/GoSend lines, shown with "jam" estimates.
- [ ] Errors map to messages (400/401/422/429/502), retries only on 429/5xx, `Retry-After` honoured.
- [ ] Couriers, locations and rates are cached as in section 7.
- [ ] The chosen rate is re-checked server-side before an order is saved.

Then tell the user:

```
┌─ AgenWebsite Rate API ready ─────────────────────────┐
│  ✓ Key      AGENWEBSITE_API_KEY (…last4), <plan>     │
│  ✓ Verify   GET /v1/usage → 200, <remaining> left    │
│  ✓ Flow     locations → rates → services UI          │
│  ✓ Files    <files you changed>                      │
│  ✓ Cache    couriers 24h · locations 24h · rates Nm  │
│                                                      │
│  Quota resets 00:00 WIB · plans: agenwebsite.com     │
└──────────────────────────────────────────────────────┘
```

---

## Links

- Docs index for AI: https://www.agenwebsite.com/developer-api/llms.txt
- Full docs in one file: https://www.agenwebsite.com/developer-api/llms-full.txt
- OpenAPI spec: https://api.agenwebsite.com/v1/openapi.json
- Human docs (Bahasa Indonesia): https://www.agenwebsite.com/documentation/agenwebsite-rate-api/ (each page has a Markdown version at `<page-url>index.md`)
- Account, keys and plans: https://www.agenwebsite.com/account/developer-api/ · https://www.agenwebsite.com/products/developer-api/
- Support: https://support.agenwebsite.com/
