# LOKASIGN.md — integration context for AI assistants

> **For the developer.** Attach this file to a chat with your AI assistant (Claude, ChatGPT,
> Gemini…), or save it in your repository as `docs/LOKASIGN.md` and point your coding agent at it
> from `AGENTS.md`, `CLAUDE.md` or `.cursor/rules` (a snippet is at the end). Download a fresh
> copy from `https://lokasign.net/docs/LOKASIGN.md` whenever the API changes; the facts about the host below were filled in
> when you downloaded it.

## Instructions for the assistant

You are helping a developer integrate their application with **Lokasign**, an e-signature
platform, over its REST API. A common shape, and the one the examples below use: a **framework
agreement** is signed once when a partner joins, then a shorter **per-transaction contract** for
every piece of work — here a music release carrying its list of songs, but the pattern is the same
for orders, projects or services.

- Treat this file as authoritative for how Lokasign behaves. For anything not covered here,
  consult the OpenAPI 3.1 document at `https://lokasign.net/docs/api.json`, which is the complete contract. **Never
  invent** endpoints, fields, headers, event names or error codes; if unsure, say so and point to
  the spec.
- If the Lokasign MCP server is connected (`https://lokasign.net/mcp`), call its tools to look things up and to test
  against the sandbox instead of guessing. Tool names equal the `operationId`s below.
- Answer in the developer's language (often Indonesian). Keep identifiers, field names and
  error codes exactly as written here.
- Prefer the developer's existing stack and conventions. The examples below are Laravel, Node.js,
  browser JavaScript and Flutter; translate them faithfully rather than inventing a different flow.
- Refuse to put the API key in browser or mobile code, even "just for testing".

## This host

**Host ini adalah production: `https://lokasign.net`.** Setiap tanda tangan di sini sah dan mengikat para pihak. Bangun dan uji integrasi Anda di sandbox dulu.

| | |
|---|---|
| REST base URL | `https://lokasign.net/api/v1` |
| Auth | `Authorization: Bearer <api_key>` on every call (or `X-Api-Key: <api_key>` where `Authorization` is taken) |
| OpenAPI (complete contract) | `https://lokasign.net/docs/api.json` |
| Human reference | `https://lokasign.net/docs/api` |
| MCP server (Streamable HTTP, same key) | `https://lokasign.net/mcp` |
| Guides (Indonesian) | `https://lokasign.net/docs/quickstart`, `https://lokasign.net/docs/signing`, `https://lokasign.net/docs/templates` |
| Everything as one text file | `https://lokasign.net/llms-full.txt` |

Rate limit: 120 requests per minute per key (`429 rate_limited` with `Retry-After`).

## Mental model

- **Tenant**: the developer's organisation in the Lokasign dashboard. Created by signing up at `https://lokasign.net/register`. Only OWNER/ADMIN can issue API keys.
- **Application**: one client system (their backend). Owns its API keys, webhook, templates, and data; nothing crosses applications (another application's `gid` answers `404`, never `403`).
- **Template** (`code`, e.g. `PERJANJIAN_KEANGGOTAAN`): an agreement authored once in the dashboard from a `.docx` with tags. Declares **roles** (`key`, e.g. `mitra`, `operator`), **merge tags** (`signer1.party_name`, `agreement_date`), and **collections** (repeating table rows; the name is whatever prefix the template author chose — `songs`, `sessions`, `participants`, `items` — read it from `GET /templates/{code}` → `collections[].name`). Must be **active** to be used.
- **Signature request** (`gid`): one agreement being signed. Carries documents (rendered from templates, or uploaded PDFs), signers, and the client's own `external_ref`.
- **Signer**: `name`, `email`, `role_key`, `order_index`, `verification_method` (`none` / `otp` / `email_link`), and `delivery` (`email` = Lokasign emails the invitation; `embedded` = the client opens a signing session itself and nothing but OTP codes and the executed copy is emailed).
- **Signing session**: a single-use URL (5 minutes, one opening) to show the signing page inside the client's web page (iframe) or mobile app (WebView). Ends with an **exchange code** the client's backend redeems.
- **Webhook**: signed POSTs to the client's HTTPS endpoint for every lifecycle event.
- **Final documents**: sealed PDFs (PAdES + timestamp), available after `completed` as 72-hour links.
- **Test mode**: a key is `live` (`esk_live_…`) or `test` (`esk_test_…`); `GET /application` says which in `api_key.mode`. With a test key the API behaves identically, but every request/document is test data (invisible to live keys, own `external_ref` namespace), **no email is sent** (read it from `GET /test-mail`, which extracts `codes` and `links`), executed documents carry a SPECIMEN watermark and no platform seal, webhooks say `"test": true`, and signers can be simulated. Develop, run CI and let agents work with a test key; switch to a live key only for production.

## Lifecycle

```
draft ──send / send_when_ready──► sent ──first signature──► partially_signed ──last signature + seal──► completed
  │                                 │                             │
  └── void ──► voided               └── void / decline / expiry ──┴──► voided / declined / expired
```

Terminal: `completed`, `declined`, `expired`, `voided`. Template requests start as `draft` with
`documents_pending > 0` while rendering on a queue; `send_when_ready: true` sends them as soon as
rendering finishes. Status is read from the API or webhooks, **never** from the browser.

## Endpoints

| operationId | Method & path | Use |
|---|---|---|
| getApplication | `GET /application` | First call: proves the key, names the application, returns limits. |
| listTemplates / getTemplate | `GET /templates`, `GET /templates/{code}` | Discover templates; full contract of one (roles, merge fields with `required`/`default_value`/formats, collections). |
| checkTemplateData | `POST /templates/{code}/check` | Dry-run `merge_fields`, `merge_rows`, `signer_role_keys`. Nothing is created. Reports every problem at once; `ready: true` when a request would be accepted. |
| activateTemplate / deactivateTemplate | `POST /templates/{code}/activate` · `/deactivate` | Human review step; do not call from unattended code. |
| createSignatureRequest | `POST /signature-requests` | Create (send `Idempotency-Key`). |
| listSignatureRequests / getSignatureRequest | `GET /signature-requests[?external_ref=…&status=…]`, `GET /signature-requests/{gid}` | Read status and signers. |
| sendSignatureRequest | `POST /signature-requests/{gid}/send` | Send a reviewed draft. |
| voidSignatureRequest | `POST /signature-requests/{gid}/void` | Withdraw; frees the `external_ref`. |
| remindSignatureRequest | `POST /signature-requests/{gid}/remind` | Email reminder (once per signer per 24 h; not for `embedded` signers). |
| updateSigner | `PATCH /signature-requests/{gid}/signers/{signerGid}` | Fix a mistyped name/email of a signer who has not acted. |
| getDocumentPreviews | `GET /signature-requests/{gid}/documents` | Preview links of rendered documents before/while signing. |
| getFinalDocuments | `GET /signature-requests/{gid}/document` | Sealed PDFs after `completed`: `download_url`, `sealed_hash`, `final_hash`, `filename`. |
| getAuditTrail | `GET /signature-requests/{gid}/audit-trail` | Evidence to archive beside the PDF. |
| uploadDocument / listDocuments / getDocument | `POST /documents` (multipart), `GET /documents[/{gid}]` | For PDFs you already have (no template). |
| createDocumentUpload / getDocumentUpload | `POST /document-uploads`, `GET /document-uploads/{gid}` | A single-use, 15-minute `upload_url` for a PDF you cannot send as multipart or URL — the person opens it, or you `PUT` the bytes (no API key). `uploaded_by: "agent"` when you send it yourself. |
| listTestMail | `GET /test-mail[?to=…&signature_request_gid=…]` | Test keys only: the email a test request would have sent, with extracted `codes` and `links`. |
| simulateSigner | `POST /signature-requests/{gid}/signers/{signerGid}/simulate` | Test keys only: sign (`{"action":"sign"}`) or decline (`{"action":"decline","reason":"…"}`) for a signer, through the real signing path. |
| createSigningSession | `POST /signing-sessions` | Embedded signing URL for one signer (send `Idempotency-Key`). |
| exchangeSigningSession | `POST /signing-sessions/exchange` | Redeem the exchange code for the verified outcome. |
| getWebhook / updateWebhook | `GET /webhook`, `PUT /webhook` | Configure the endpoint; the creating call returns `secret` once. |
| rotateWebhookSecret / pingWebhook | `POST /webhook/rotate-secret`, `POST /webhook/ping` | New secret (breaks the receiver until deployed); test delivery `webhook.ping`. |
| listWebhookDeliveries / retryWebhookDelivery | `GET /webhook-deliveries`, `POST /webhook-deliveries/{delivery_id}/retry` | Debug deliveries; replay one. |

## Build it in this order

1. `.env`: `LOKASIGN_BASE_URL=https://lokasign.net/api/v1`, `LOKASIGN_API_KEY` (a **test** key, `esk_test_…`, while building), `LOKASIGN_WEBHOOK_SECRET`. Call `GET /application` until it answers `200` and check `api_key.mode`.
2. Webhook receiver (verify, dedupe, queue), then `PUT /webhook` and `POST /webhook/ping`.
3. Templates in the dashboard (samples below), activated. Read `GET /templates/{code}` and build the mapper from the client's data to `merge_fields` / `merge_rows` / signers.
4. A `contracts`-like table in the client app: `external_ref`, `lokasign_request_gid`, signer gids, `status`, `signed_file_path`, `sealed_hash`, `idempotency_key`, `completed_at`.
5. Create requests (`checkTemplateData` first in development).
6. Signing: email (nothing to build) or embedded (session endpoint + iframe/WebView + exchange).
7. On `signature_request.completed`: download, verify `sealed_hash`, store.
8. Handle `declined`, `expired`, `voided`, `processing_failed`, not only `completed`.

## Laravel reference code

```php
// config/services.php
'lokasign' => [
    'url' => env('LOKASIGN_BASE_URL'),
    'key' => env('LOKASIGN_API_KEY'),
    'webhook_secret' => env('LOKASIGN_WEBHOOK_SECRET'),
],
```

```php
// app/Services/LokasignClient.php
namespace App\Services;

use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;

class LokasignClient
{
    private function http(): PendingRequest
    {
        return Http::baseUrl(config('services.lokasign.url'))
            ->withToken(config('services.lokasign.key'))
            ->acceptJson()
            ->timeout(30);
    }

    /** Create a request. Store $idempotencyKey on your row *before* calling, and reuse it on retries. */
    public function createRequest(array $payload, string $idempotencyKey): array
    {
        return $this->http()->withHeaders(['Idempotency-Key' => $idempotencyKey])
            ->post('/signature-requests', $payload)->throw()->json('data');
    }

    public function request(string $gid): array
    {
        return $this->http()->get("/signature-requests/{$gid}")->throw()->json('data');
    }

    public function signingUrl(string $requestGid, string $signerGid, ?string $embedderOrigin, ?string $returnUrl = null): string
    {
        return $this->http()->withHeaders(['Idempotency-Key' => (string) str()->uuid()])
            ->post('/signing-sessions', array_filter([
                'signature_request_gid' => $requestGid,
                'signer_gid' => $signerGid,
                'embedder_origin' => $embedderOrigin,   // web iframe only; omit for a native WebView
                'return_url' => $returnUrl,             // e.g. "myapp://signing-done" for a native WebView
                'locale' => app()->getLocale(),
            ]))->throw()->json('data.signing_url');
    }

    public function exchange(string $code): array
    {
        return $this->http()->post('/signing-sessions/exchange', ['code' => $code])->throw()->json('data');
    }

    /** @return list<array{filename: string, download_url: string, sealed_hash: string, final_hash: string}> */
    public function finalDocuments(string $gid): array
    {
        return $this->http()->get("/signature-requests/{$gid}/document")->throw()->json('data');
    }
}
```

Errors: `->throw()` raises `Illuminate\Http\Client\RequestException`; branch on
`$e->response->json('error.code')` (stable) and log `error.message` plus the `X-Request-Id`
header. `error.field` names the first invalid input (`documents.0.merge_fields`).

```php
// Webhook receiver: verify HMAC over the RAW body, answer fast, dedupe on X-Delivery-Id.
public function __invoke(Request $request): JsonResponse
{
    $parts = [];
    foreach (explode(',', (string) $request->header('X-Signature')) as $pair) {
        [$k, $v] = array_pad(explode('=', trim($pair), 2), 2, '');
        $parts[$k] = $v;
    }
    $expected = hash_hmac('sha256', ($parts['t'] ?? '').'.'.$request->getContent(), config('services.lokasign.webhook_secret'));
    if (! hash_equals($expected, $parts['v1'] ?? '') || abs(time() - (int) ($parts['t'] ?? 0)) > 300) {
        return response()->json(['error' => 'invalid signature'], 400);
    }

    $event = LokasignWebhookEvent::firstOrCreate(
        ['delivery_id' => $request->header('X-Delivery-Id')],   // UNIQUE column
        ['payload' => $request->getContent()],
    );
    if ($event->wasRecentlyCreated) {
        ProcessLokasignWebhook::dispatch($event->id);
    }

    return response()->json(['received' => true]);             // within 10 seconds
}
```

```php
// In the queued job: re-read the request (the webhook is a trigger, the API is the truth),
// ignore events older than what you already applied (order by occurred_at), then act.
$payload = json_decode($event->payload, true);   // {event, signature_request_gid, external_ref, occurred_at, data}
$contract = Contract::where('external_ref', $payload['external_ref'])->firstOrFail();
if ($contract->last_event_at && $contract->last_event_at->gte($payload['occurred_at'])) {
    return;
}
$remote = $client->request($payload['signature_request_gid']);
$contract->update(['status' => $remote['status'], 'last_event_at' => $payload['occurred_at']]);

if ($remote['status'] === 'completed') {
    foreach ($client->finalDocuments($remote['gid']) as $doc) {
        $bytes = Http::get($doc['download_url'])->throw()->body();       // signed link, no API key
        if (! hash_equals($doc['sealed_hash'], hash('sha256', $bytes))) { // sealed_hash, NOT final_hash
            throw new RuntimeException("Hash mismatch for {$doc['filename']}");
        }
        Storage::put("contracts/{$contract->id}/{$doc['filename']}", $bytes);
    }
}
```

## Node.js reference code

The same pieces for Node.js 18+ (built-in `fetch`), with Express for the HTTP side. Adapt to the
developer's framework (Fastify, NestJS, Next.js route handlers) without changing the rules.

```js
// lokasign.js — a thin client. Store an Idempotency-Key on your own row before creating
// anything, and reuse it on retries.
import crypto from 'node:crypto';

export async function lokasign(method, path, body, headers = {}) {
  const res = await fetch(`${process.env.LOKASIGN_BASE_URL}${path}`, {
    method,
    headers: {
      Authorization: `Bearer ${process.env.LOKASIGN_API_KEY}`,
      Accept: 'application/json',
      ...(body ? { 'Content-Type': 'application/json' } : {}),
      ...headers,
    },
    body: body ? JSON.stringify(body) : undefined,
  });
  const json = await res.json().catch(() => ({}));

  if (!res.ok) {
    const error = new Error(json.error?.message ?? `HTTP ${res.status}`);
    // Branch on error.code (stable); log message + requestId.
    Object.assign(error, { code: json.error?.code, field: json.error?.field, requestId: res.headers.get('x-request-id') });
    throw error;
  }

  return json;
}

export const createRequest = (payload, idempotencyKey) =>
  lokasign('POST', '/signature-requests', payload, { 'Idempotency-Key': idempotencyKey }).then((r) => r.data);

export const getRequest = (gid) => lokasign('GET', `/signature-requests/${gid}`).then((r) => r.data);

export const signingUrl = (requestGid, signerGid, { embedderOrigin, returnUrl, locale = 'id' } = {}) =>
  lokasign('POST', '/signing-sessions', {
    signature_request_gid: requestGid,
    signer_gid: signerGid,
    ...(embedderOrigin ? { embedder_origin: embedderOrigin } : {}), // web iframe only; omit for a native WebView
    ...(returnUrl ? { return_url: returnUrl } : {}),                // e.g. "myapp://signing-done" for a native WebView
    locale,
  }, { 'Idempotency-Key': crypto.randomUUID() }).then((r) => r.data.signing_url);

export const exchange = (code) => lokasign('POST', '/signing-sessions/exchange', { code }).then((r) => r.data);

export const finalDocuments = (gid) => lokasign('GET', `/signature-requests/${gid}/document`).then((r) => r.data);
```

```js
// Webhook receiver: verify HMAC over the RAW body (express.raw, never express.json), answer
// fast, dedupe on X-Delivery-Id.
import crypto from 'node:crypto';
import express from 'express';

app.post('/webhooks/lokasign', express.raw({ type: '*/*' }), async (req, res) => {
  const parts = Object.fromEntries(String(req.get('X-Signature') ?? '').split(',').map((p) => p.trim().split('=')));
  const expected = crypto.createHmac('sha256', process.env.LOKASIGN_WEBHOOK_SECRET)
    .update(`${parts.t}.${req.body.toString('utf8')}`).digest('hex');
  const valid = parts.v1?.length === expected.length
    && crypto.timingSafeEqual(Buffer.from(parts.v1), Buffer.from(expected))
    && Math.abs(Date.now() / 1000 - Number(parts.t)) <= 300;

  if (!valid) return res.status(400).json({ error: 'invalid signature' });

  // Insert with a UNIQUE delivery_id; a duplicate insert means "already seen".
  const isNew = await db.webhookEvents.insertIgnore({ deliveryId: req.get('X-Delivery-Id'), payload: req.body.toString('utf8') });
  if (isNew) queue.add('lokasign-webhook', { deliveryId: req.get('X-Delivery-Id') });

  res.json({ received: true }); // within 10 seconds
});
```

```js
// The queued job: re-read the request (the webhook is a trigger, the API is the truth), skip
// events older than what you already applied (order by occurred_at), then act.
import crypto from 'node:crypto';
import fs from 'node:fs/promises';
import { getRequest, finalDocuments } from './lokasign.js';

export async function processLokasignWebhook(payload) {
  const { signature_request_gid: gid, external_ref: ref, occurred_at: occurredAt } = payload;
  const contract = await db.contracts.findByExternalRef(ref);
  if (contract.lastEventAt && new Date(contract.lastEventAt) >= new Date(occurredAt)) return;

  const remote = await getRequest(gid);
  await db.contracts.update(contract.id, { status: remote.status, lastEventAt: occurredAt });

  if (remote.status !== 'completed') return;

  for (const doc of await finalDocuments(gid)) {
    const bytes = Buffer.from(await (await fetch(doc.download_url)).arrayBuffer()); // signed link, no API key
    const hash = crypto.createHash('sha256').update(bytes).digest('hex');
    if (hash !== doc.sealed_hash) throw new Error(`Hash mismatch for ${doc.filename}`); // sealed_hash, NOT final_hash
    await fs.mkdir(`storage/contracts/${contract.id}`, { recursive: true });
    await fs.writeFile(`storage/contracts/${contract.id}/${doc.filename}`, bytes);
  }
}
```

## Embedded signing, front ends

Web (iframe). Register the page origin on the API key first (dashboard → API & Webhook → key → origins).

```js
const iframe = document.querySelector('#lokasign');
iframe.src = signingUrl;                       // fetched from your backend just before showing it
window.addEventListener('message', async (e) => {
  if (e.origin !== new URL(signingUrl).origin || e.data?.source !== 'lokasign') return;
  if (e.data.type === 'esign:completed' || e.data.type === 'esign:declined') {
    await fetch('/your-backend/lokasign/exchange', { method: 'POST', headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ code: e.data.exchangeCode }) });   // backend calls POST /signing-sessions/exchange
  }
});
```

Messages: `esign:ready`, `esign:field-completed` (`remaining`), `esign:completed` and
`esign:declined` (both with `requestId`, `exchangeCode`). They are cues, never results.

Mobile (Flutter `webview_flutter`). Create the session **without** `embedder_origin` and with
`return_url: "myapp://signing-done"`; the page navigates there with
`?lokasign_event=esign:completed|esign:declined&request_id=…&exchange_code=…`.

```dart
WebViewController()
  ..setJavaScriptMode(JavaScriptMode.unrestricted)
  ..setNavigationDelegate(NavigationDelegate(onNavigationRequest: (req) {
    final uri = Uri.parse(req.url);
    if (uri.scheme == 'myapp' && uri.host == 'signing-done') {
      Navigator.of(context).pop(uri.queryParameters['exchange_code']); // send to your backend
      return NavigationDecision.prevent;
    }
    return NavigationDecision.navigate;
  }))
  ..addJavaScriptChannel('LokasignBridge', onMessageReceived: (m) { /* same messages, as JSON strings */ })
  ..loadRequest(Uri.parse(signingUrl));
```

Other bridges the page also calls when top-level: `window.webkit.messageHandlers.lokasign`
(iOS, object), `window.ReactNativeWebView.postMessage` (JSON string), `flutter_inappwebview`
handler `lokasign` (object). An `https://` `return_url` must be on the key's allowed origins; app
schemes are accepted; `javascript:`/`data:`/`file:` are refused (`403 return_url_not_allowed`).

## Sample payloads (tested against real templates)

Membership agreement, template `PERJANJIAN_KEANGGOTAAN`, roles `mitra` + `operator`, both signers by email:

```json
{
    "title": "Perjanjian Keanggotaan — PT Contoh Musik Nusantara",
    "external_ref": "membership:mitra-0001",
    "sequential": true,
    "send_when_ready": true,
    "locale": "id",
    "documents": [
        {
            "template_code": "PERJANJIAN_KEANGGOTAAN",
            "merge_fields": {
                "agreement_number": "001/PK/IX/2026",
                "agreement_date": "2026-09-29",
                "signer1.party_name": "PT Contoh Musik Nusantara",
                "signer1.party_address": "Jl. Contoh Raya No. 1, Jakarta Selatan",
                "signer1.party_tax_id": "01.234.567.8-901.000",
                "signer1.signatory_name": "Rina Contoh",
                "signer1.signatory_title": "Direktur",
                "signer2.party_name": "PT Operator Platform Contoh",
                "signer2.party_address": "Jl. Platform No. 2, Jakarta Pusat",
                "signer2.signatory_name": "John Doe",
                "signer2.signatory_title": "Direktur",
                "term_years": "3",
                "revenue_share_percent": "70"
            }
        }
    ],
    "signers": [
        { "name": "Rina Contoh", "email": "rina@contoh-musik.example", "role_key": "mitra", "order_index": 1, "verification_method": "otp" },
        { "name": "John Doe", "email": "legal@operator.example", "role_key": "operator", "order_index": 2 }
    ]
}
```

Release contract, template `KONTRAK_RILIS_LAGU`, repeating `songs` rows, the partner signs inside the app:

```json
{
    "title": "Kontrak Rilis — Senja di Kota (EP)",
    "external_ref": "release:rilis-0042",
    "sequential": true,
    "send_when_ready": true,
    "locale": "id",
    "documents": [
        {
            "template_code": "KONTRAK_RILIS_LAGU",
            "merge_fields": {
                "contract_number": "042/KR/IX/2026",
                "contract_date": "2026-09-29",
                "membership_agreement_number": "001/PK/IX/2026",
                "signer1.party_name": "PT Contoh Musik Nusantara",
                "signer1.signatory_name": "Rina Contoh",
                "signer2.party_name": "PT Operator Platform Contoh",
                "signer2.signatory_name": "John Doe",
                "release_title": "Senja di Kota",
                "release_artist": "Band Contoh",
                "release_upc": "0123456789012",
                "release_date": "2026-11-01",
                "territory": "Seluruh dunia"
            },
            "merge_rows": {
                "songs": [
                    { "NO": "1", "TITLE": "Senja di Kota", "ARTIST": "Band Contoh", "ISRC": "IDA012600001", "DURATION": "03:41" },
                    { "NO": "2", "TITLE": "Pulang", "ARTIST": "Band Contoh", "ISRC": "IDA012600002", "DURATION": "04:05" },
                    { "NO": "3", "TITLE": "Hujan Pertama", "ARTIST": "Band Contoh feat. Penyanyi Tamu", "ISRC": "IDA012600003", "DURATION": "03:18" }
                ]
            }
        }
    ],
    "signers": [
        { "name": "Rina Contoh", "email": "rina@contoh-musik.example", "role_key": "mitra", "order_index": 1, "delivery": "embedded" },
        { "name": "John Doe", "email": "legal@operator.example", "role_key": "operator", "order_index": 2 }
    ]
}
```

The `.docx` files for both templates: `https://lokasign.net/docs/templates/samples/perjanjian-keanggotaan.docx`,
`https://lokasign.net/docs/templates/samples/kontrak-rilis-lagu.docx`.

## Template tags (for editing the .docx)

`{{type|arg|arg}}`, arguments in any order. Types: `data` (value from the API), `sig`, `initial`,
`date` (auto-filled signing date), `text`, `check`, `materai`. Arguments: `signerN` (slot; slot N
maps to the N-th role in the template's role list), `name:<key>` (case-sensitive), `req`/`opt`
(default `req`), `style:upper|lower|title`, `format:date_long|date_short|date_numeric|date_dayname|date_day_words|date_month|date_year_words|number_words`.

- `{{data|signer1|name:party_name}}` → sent as `merge_fields["signer1.party_name"]`.
- Repeating row: a table row whose tags all share one prefix, `{{data|name:<collection>.COLUMN}}` → `documents[].merge_rows.<collection>[]` of `{ "COLUMN": "…" }`. The collection name is free-form and case-sensitive; `songs` in the samples is only an example (an attendance table tagged `sessions.DATE` is filled with `merge_rows.sessions`). Row columns may declare `format:` like any tag, and the same value rules apply (`"YYYY-MM-DD"` dates, whole numbers); an unreadable row value is refused at create (`documents.N.merge_rows`) and reported by `/check` as `unreadable_row_values` with `collection`, zero-based `row` and `column`. A column you leave out prints an empty cell; a collection you leave out removes its row; unknown collection or column keys are ignored by the renderer and reported by `/check` as `unknown_collections` / `unknown_columns` (not blocking).
- Optional block: `{{?block1}}…{{/block1}}` disappears when every `data` tag inside is empty; tags inside must be `opt`. Fill every tag in a block or none: a partly filled block is refused at create (`documents.N.merge_fields`) and reported by `/check` as `incomplete_optional_blocks` (`filled`, `missing`).
- Send every value as a **string** (`"028"`, `"3"`, dates as `"YYYY-MM-DD"`).

## Rules that are easy to get wrong

- API key only on the server. Mobile/web ask your backend for a `signing_url`.
- If `api_key.mode` is `live`, every request you create invites real people and yields binding documents: do not experiment with it — ask the developer for a test key.
- Production webhook receivers should ignore or separate events with `"test": true`.
- Send `Idempotency-Key` on `POST /signature-requests`, `/documents`, `/document-uploads`, `/signing-sessions`: same key for a retry of the same call, a new key for a new call. Same key + different body → `409 idempotency_key_reused`.
- Always set `external_ref` to your own id. A live or completed request reserves it (`422 external_ref_taken`) — look the existing one up with `?external_ref=` instead of creating a twin. Void/decline/expiry frees it.
- Status comes from `GET /signature-requests/{gid}`, webhooks, or `POST /signing-sessions/exchange` — never from `redirect_url` arrival or a `postMessage`.
- Webhook HMAC is over the raw body bytes; verify before parsing; 5-minute tolerance; ack with 2xx within 10 s; dedupe on `X-Delivery-Id`; order by `occurred_at`.
- A signing session URL lives 5 minutes and opens once: create it right before showing it. Creating one rotates that signer's emailed link, so give such signers `"delivery": "embedded"`.
- In a sequential request a session can only be opened for the signer whose turn it is (`422 signer_not_pending`). `embedded` signers get no email when their turn comes: listen for `signer.signed` of the previous signer.
- Final document links expire after 72 h: store the file, not the URL. Compare the download with `sealed_hash`; `final_hash` is pre-seal and never matches.
- `field` placement (`fields[]`) is only for uploaded PDFs; template documents place their own fields.
- Place fields by the PDF's own words: `"anchor": {"text": "Pihak Pertama,"}` with no `offset_y` centres the box in the gap under that line. Copy the text exactly, punctuation included; an absent text answers `422 anchor_not_found`. Scanned PDFs have no text layer — use `page_number`/`x`/`y`.
- As an MCP agent, a chat attachment cannot travel in a tool call: `createDocumentUpload`, then `PUT` the file to `upload_url` if you can read it (`uploaded_by: "agent"`), else hand the person the link.
- For the person in the conversation who signs: `delivery: "embedded"`, then `createSigningSession` without `embedder_origin`; they open `signing_url` in their own browser.
- Only the first validation failure is reported per call (`error.field`); use `checkTemplateData` to get all template problems at once.

## Error codes worth handling explicitly

| Code | Status | Meaning → action |
|---|---|---|
| `unauthorized` | 401 | Wrong/revoked key. |
| `application_inactive` | 403 | Application deactivated in the dashboard. |
| `validation_failed` | 422 | Read `error.field` + `error.message`; fix input. |
| `external_ref_taken` | 422 | Reuse the existing request. |
| `anchor_not_found` | 422 | `fields.N.anchor.text` is not in the PDF: copy it exactly, or use coordinates. |
| `upload_link_used` / `upload_link_expired` / `upload_link_invalid` | 409 / 410 / 404 | From `upload_url` itself: read the document with `getDocumentUpload`, or create a new link. |
| `idempotency_key_reused` | 409 | Same key, different body — generate a new key for a new call. |
| `request_not_draft` / `request_not_voidable` / `request_not_remindable` | 409 | Wrong state for the action; re-read the request. |
| `reminder_cooldown` | 429 | Reminded < 24 h ago. |
| `signer_embedded` | 409 | Remind an embedded signer in your own UI. |
| `signer_not_pending` | 422 | Signer already acted or it is not their turn. |
| `embedder_origin_not_allowed` / `return_url_not_allowed` | 403 | Register the origin on the key. |
| `exchange_code_invalid` | 422 | Used/expired code; read the request instead. |
| `request_not_completed` / `documents_not_sealed` | 409 | Final documents not ready yet; wait for `completed` webhook. |
| `test_mode_only` | 403 | `GET /test-mail` / `…/simulate` need a test key (or the request is live data). |
| `rate_limited` | 429 | Honour `Retry-After`. |
| `server_error` | 500 | Retry with backoff; quote `X-Request-Id`. |

The full catalogue is `components.schemas.ErrorCode` in `https://lokasign.net/docs/api.json`.

## Webhook events

`signature_request.sent`, `signer.viewed`, `signer.signed`, `signer.declined`,
`signature_request.completed`, `signature_request.declined`, `signature_request.expired`,
`signature_request.voided`, `signature_request.processing_failed`,
`signature_request.reminder_sent`, and `webhook.ping` (test only). Envelope:
`{ event, signature_request_gid, external_ref, test, occurred_at, data }`; signer events carry
`data.signer` (`gid`, `name`, `email`, `status`, `order_index`, `role_key`).

## Snippet for AGENTS.md / CLAUDE.md / .cursor/rules

```md
## Lokasign (e-signature)
- Read docs/LOKASIGN.md before touching anything under the Lokasign integration. The full API
  contract is the OpenAPI document linked there; do not invent endpoints, fields or error codes.
- The API key lives only in server env (`LOKASIGN_API_KEY`); never in frontend or mobile code.
- Status comes from the API/webhooks, never from the browser. Webhooks are verified over the raw body.
- Every create call sends `Idempotency-Key`; every signature request carries our `external_ref`.
```

## Good first prompts

- "Pakai LOKASIGN.md. Buatkan service Laravel untuk mengirim perjanjian keanggotaan saat mitra disetujui, lengkap dengan migration kolom yang dibutuhkan."
- "Buatkan controller + job webhook Lokasign yang memverifikasi tanda tangan, dedup, dan mengarsipkan PDF final."
- "Buatkan layar Flutter untuk menandatangani kontrak rilis di dalam aplikasi memakai return_url."
- "Ini respons error dari Lokasign: … Apa penyebabnya dan apa yang harus saya ubah?"
