# Adquivo integration guide

Use an integration when your own application should verify a visitor's Adquivo checkpoint before granting access. Your application keeps authority over the reward, account, nonce, and grant. The current integration supports the sponsor checkpoint and an optional Adquivo Premium entitlement check.

## Configure the integration

1. In **Creator workspace → API**, create a **Sandbox** integration and copy its `vy_int_` API key to your backend secret store. The key is shown once. The existing creator link API uses separate credentials and endpoints.
2. Set `VEYLO_ORIGIN` on your backend to `https://adquivo.com` and `VEYLO_INTEGRATION_KEY` to the new key. Local Node and Python examples also accept `http://localhost:3000`. Existing API keys, `X-Veylo-*` headers, `veylo_session` and `veylo_token` query fields, and previous SDK exports retain their names.
3. For a redirect flow, register your application's exact HTTPS return URL when creating the integration, such as `https://app.example.com/adquivo/return`. The return URL is fixed for that integration. You can omit it in Sandbox and copy the short-lived proof from the hosted completion screen. A live application can configure an HTTPS completion webhook and store the distinct webhook secret as `VEYLO_WEBHOOK_SECRET`.
4. Create an integration link or connect a Adquivo link owned by your creator account. Save the returned `id` as `VEYLO_LINK_ID`. The link API reports recorded activity and, for live links, credited earnings. Sandbox activity comes from test sessions.
5. In Sandbox, finish a test session and verify the resulting code with the sandbox credential. Use a separate Live integration and key for real visitors. Deploy live sponsor activity only after an approved sponsor is available. The live Premium path checks Adquivo entitlement only on a link with Premium allowed. A sandbox result must leave real app access, keys, balances, and billing untouched.

Keep bearer credentials and webhook secrets on your backend. A browser, distributed client, game script, or end user only needs the returned visitor URL. Avoid placing sensitive data in `reference`; use a fresh random value and map it to the relevant user or action in your backend.

## Integration API

All endpoints use `Authorization: Bearer <integration-key>`. For writes, send `Content-Type: application/json`. The response body is JSON. `environment` binds the workflow to `sandbox` or `live`.

| Method and path | Request and result |
| --- | --- |
| `GET /api/v1/integrations/status` | Reports `integrationId`, `environment`, supported `checkpoints`, `premiumCheck`, and `sponsorAvailable`. |
| `POST /api/v1/integrations/links` | Send `title`, `destination`, `checkpoint: "sponsor"`, and optionally `expires` and `premiumAllowed`. Returns the link representation. |
| `POST /api/v1/integrations/links/connect` | Send the existing owned Adquivo link's `url` and optionally `premiumAllowed`. Returns the link representation. |
| `GET /api/v1/integrations/links/{id}` | Returns the link ID, URL, checkpoint, Premium setting, expiration, and activity. Live links also return `settledEarnings` in integer USD cents by source for that link. The legacy `earnings` field remains `null` for compatibility. |
| `POST /api/v1/integrations/sessions` | Send `linkId` and a nonblank `reference` of up to 128 printable ASCII characters. Sandbox also accepts `testOutcome: "sponsor"` or `"premium"`. Returns `sessionId`, `visitorUrl`, and `expiresAt`. Use this `visitorUrl` to start the integration flow. |
| `POST /api/v1/integrations/completions/verify` | Send `sessionId`, `linkId`, and `token`. A successful response returns `verified: true`, the matching identifiers and `reference`, the verified `method`, `environment`, and `completedAt`. Verification consumes the code. |

Specify link expiration at UTC minute precision as `YYYY-MM-DDTHH:mm`. A visitor session lasts up to 30 minutes. A completion code lasts five minutes by default, or the verification duration saved for an eligible live link, and can be consumed once. A used code produces `completion_used` (`409`). Unissued, mismatched, or expired codes produce `completion_unavailable` (`409`). If the browser return is interrupted, the original visitor browser can retry the same unconsumed result before it expires. Your return handler should treat repeated requests for a session it has already granted as expected retries. Keep the code out of logs, metrics, and client storage.

Creation calls can have effects before the caller receives a response. If you lose a response, check for the resulting record before issuing another create. On `429` (`rate_limited`), use `Retry-After` when present. Integration errors have the form `{ "error": { "code": "…", "message": "…" } }`; use the code in program logic. Expected failure codes include `invalid_request`, `invalid_credentials`, `not_found`, `link_limit`, `completion_unavailable`, `completion_used`, `rate_limited`, and `service_unavailable`. The SDKs raise `AdquivoError` with the HTTP status, code, message, and retry header. `status` 0 represents a transport failure or timeout.

## Save the expected session before showing its URL

1. Authenticate the visitor with your own backend. Generate a new correlation `reference` and call the session endpoint with your saved link ID.
2. Associate the returned `sessionId` with the authenticated subject, link ID, `reference`, expected environment, and intended reward. Persist that record before returning `visitorUrl` to the visitor.
3. In the HTTPS return handler, read `veylo_session` and `veylo_token` from the query string. Look up the expected session for the authenticated subject and verify the code from your backend. Compare session ID, link ID, reference, and environment with the stored expected values. Check the verified method against your app's eligibility rules if applicable.
4. For a Live success, update app access in your own database with a uniqueness constraint on the Adquivo session ID. A Sandbox success should only record a test receipt. Respond with a redirect to a URL without the verification parameters. Set `Cache-Control: no-store` and `Referrer-Policy: no-referrer` on the callback and configure request logging to redact the query string.

A retry after successful verification may return `completion_used`. Consult your persisted grant for that authenticated subject. A conflict by itself does not establish an app grant. Use the signed live webhook to reconcile a verified session if the browser-return flow failed after Adquivo consumed its code.

For a Sandbox integration without a return URL, open `visitorUrl`, finish the hosted test checkpoint, and copy the displayed proof to your test backend. Call `verifyCompletion` with the original `sessionId`, `linkId`, and copied `token`, then compare the response with the saved session. Try the built-in test flow from **API → Integrations** to run this verification inside Adquivo.

## Node.js server quickstart

Copy [the JavaScript SDK](/docs/integrations/adquivo.mjs) and its optional [TypeScript declarations](/docs/integrations/adquivo.d.mts) into your backend. This sample shows the onboarding call and handlers. Adapt the `store` calls to your database. `findSessionForSubject` must bind to a signed-in subject from trusted application middleware, and `grantOnce` must be an atomic operation keyed by `sessionId`.

```js
import { randomUUID } from 'node:crypto';
import { AdquivoClient } from './adquivo.mjs';

const adquivo = new AdquivoClient({
  origin: process.env.VEYLO_ORIGIN,
  apiKey: process.env.VEYLO_INTEGRATION_KEY,
});

export async function configure() {
  // Run once. Persist the returned ID as VEYLO_LINK_ID.
  // To reuse an existing owned link instead, call adquivo.connectLink({ url }).
  return adquivo.createLink({
    title: 'Release download',
    destination: 'https://example.com/releases',
    checkpoint: 'sponsor',
    premiumAllowed: true,
  });
}

export async function startUnlock(subjectId, store) {
  const { environment, integrationId } = await adquivo.getStatus();
  const linkId = process.env.VEYLO_LINK_ID;
  const reference = randomUUID();
  const args = { linkId, reference };
  if (environment === 'sandbox') args.testOutcome = 'sponsor';
  const session = await adquivo.createSession(args);
  await store.saveSession({ subjectId, integrationId, linkId, reference, environment,
    sessionId: session.sessionId, expiresAt: session.expiresAt });
  return session.visitorUrl;
}

export async function onReturn(request, subjectId, store) {
  const url = new URL(request.url);
  const sessions = url.searchParams.getAll('veylo_session');
  const tokens = url.searchParams.getAll('veylo_token');
  if (sessions.length !== 1 || tokens.length !== 1 || !sessions[0] || !tokens[0]) {
    throw new Error('Invalid completion parameters');
  }
  const [sessionId] = sessions;
  const [token] = tokens;

  const expected = await store.findSessionForSubject(sessionId, subjectId);
  if (!expected) throw new Error('Unknown session');

  const proof = await adquivo.verifyCompletion({ sessionId, linkId: expected.linkId, token });
  if (proof.verified !== true || proof.sessionId !== expected.sessionId ||
      proof.linkId !== expected.linkId || proof.reference !== expected.reference ||
      proof.environment !== expected.environment) throw new Error('Mismatched completion');

  if (proof.environment === 'live') await store.grantOnce(expected, proof);
  else await store.recordTestReceipt(expected, proof);
  return new Response(null, {
    status: 303,
    headers: {
      Location: '/unlock/result',
      'Cache-Control': 'no-store',
      'Referrer-Policy': 'no-referrer',
    },
  });
}
```

## Python server quickstart

Copy the [Python SDK](/docs/integrations/adquivo.py) into your backend. It uses the standard library. Adapt the same storage and subject checks to your web framework. In your return route, add the no-store and no-referrer headers and use the returned clean path for a `303` redirect.

```python
import os
import uuid
from urllib.parse import parse_qs, urlsplit
from adquivo import AdquivoClient

adquivo = AdquivoClient(origin=os.environ["VEYLO_ORIGIN"], api_key=os.environ["VEYLO_INTEGRATION_KEY"])

def configure():
    # Run once and save the result["id"] as VEYLO_LINK_ID.
    # To reuse an existing owned link instead, call adquivo.connect_link(url=url).
    return adquivo.create_link(title="Release download", destination="https://example.com/releases",
                             premium_allowed=True)

def start_unlock(subject_id, store):
    status = adquivo.get_status()
    environment = status["environment"]
    link_id = os.environ["VEYLO_LINK_ID"]
    reference = str(uuid.uuid4())
    session = adquivo.create_session(link_id=link_id, reference=reference,
                                  test_outcome="sponsor" if environment == "sandbox" else None)
    store.save_session({"subjectId": subject_id, "integrationId": status["integrationId"],
                        "sessionId": session["sessionId"], "linkId": link_id,
                        "reference": reference, "environment": environment,
                        "expiresAt": session["expiresAt"]})
    return session["visitorUrl"]

def on_return(request_url, subject_id, store):
    query = parse_qs(urlsplit(request_url).query)
    sessions, tokens = query.get("veylo_session", []), query.get("veylo_token", [])
    if len(sessions) != 1 or len(tokens) != 1:
        raise ValueError("Invalid completion parameters")

    expected = store.find_session_for_subject(sessions[0], subject_id)
    if expected is None:
        raise ValueError("Unknown session")

    proof = adquivo.verify_completion(session_id=sessions[0], link_id=expected["linkId"], token=tokens[0])
    fields = ("sessionId", "linkId", "reference", "environment")
    if proof.get("verified") is not True or any(proof.get(field) != expected[field] for field in fields):
        raise ValueError("Mismatched completion")

    if proof["environment"] == "live":
        store.grant_once(expected, proof)
    else:
        store.record_test_receipt(expected, proof)
    return "/unlock/result"
```

## Verify completion webhooks

A Live integration can receive `completion.verified`. The event has `id`, `type`, `integrationId`, `sessionId`, `linkId`, `reference`, `method`, `environment`, and `completedAt`. Adquivo queues it when the checkpoint is verified, so it can arrive before the visitor returns. Use the raw request body bytes and the `X-Veylo-Timestamp` and `X-Veylo-Signature` headers. The MAC is HMAC-SHA256 with the webhook secret over the timestamp string, a period, and the raw body. The signature format is `sha256=<lowercase hex>`. The SDKs use constant-time comparison and a five-minute clock tolerance. The `X-Veylo-Event-Id` header matches the signed body `id`.

```js
import { verifyWebhookSignature } from './adquivo.mjs';

export async function onWebhook(request, store) {
  const raw = new Uint8Array(await request.arrayBuffer());
  if (!verifyWebhookSignature(raw, {
    timestamp: request.headers.get('X-Veylo-Timestamp'),
    signature: request.headers.get('X-Veylo-Signature'),
    secret: process.env.VEYLO_WEBHOOK_SECRET,
  })) return new Response(null, { status: 401 });

  let event;
  try { event = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(raw)); }
  catch { return new Response(null, { status: 400 }); }
  if (typeof event?.id !== 'string' || event.id !== request.headers.get('X-Veylo-Event-Id') ||
      typeof event.sessionId !== 'string' || event.type !== 'completion.verified' ||
      event.environment !== 'live' || !['sponsor', 'premium'].includes(event.method)) {
    return new Response(null, { status: 400 });
  }

  const expected = await store.findSession(event.sessionId);
  if (!expected || ['integrationId', 'sessionId', 'linkId', 'reference', 'environment'].some(
    (field) => expected[field] !== event[field],
  )) return new Response(null, { status: 404 });

  // In one transaction: deduplicate event.id, record its evidence, and grant at most once by sessionId.
  await store.recordEventAndGrantOnce(expected, event);
  return new Response(null, { status: 204 });
}
```

In Python, pass the raw body before JSON parsing and use your framework's case-insensitive header accessor. Return the handler's status with an empty response body.

```python
import json
import os
from adquivo import verify_webhook_signature

def on_webhook(raw, headers, store):
    if not verify_webhook_signature(raw, timestamp=headers.get("X-Veylo-Timestamp"),
                                    signature=headers.get("X-Veylo-Signature"),
                                    secret=os.environ["VEYLO_WEBHOOK_SECRET"]):
        return 401

    try:
        event = json.loads(raw.decode("utf-8"))
    except ValueError:
        return 400
    if (not isinstance(event, dict) or not isinstance(event.get("id"), str)
            or event["id"] != headers.get("X-Veylo-Event-Id")
            or not isinstance(event.get("sessionId"), str)
            or event.get("type") != "completion.verified" or event.get("environment") != "live"
            or event.get("method") not in ("sponsor", "premium")):
        return 400

    expected = store.find_session(event["sessionId"])
    fields = ("integrationId", "sessionId", "linkId", "reference", "environment")
    if expected is None or any(expected[field] != event.get(field) for field in fields):
        return 404

    store.record_event_and_grant_once(expected, event)
    return 204
```

Acknowledge with a `2xx` after durable processing or durable enqueue. Deduplicate event IDs and enforce a unique session grant across the webhook and return handler. Adquivo retries transport failures and `408`, `425`, `429`, or `5xx` responses with backoff, up to eight delivery attempts. See [webhook delivery and operator setup](integration-webhooks.md).

## Luau public helper

The [Luau module](/docs/integrations/Adquivo.luau) builds a standard public link or returns a hosted session URL from your own backend. Pass your backend transport as a function. Keep session creation, verification, webhook handling, and key issuance on your backend.

```lua
local Adquivo = require(path.To.Adquivo)
local origin = "https://adquivo.com"

local publicUrl = Adquivo.publicLink(origin, "release-notes")
local visitorUrl = Adquivo.forwardToBackend(yourBackendStartSession, origin, {
    action = "release-download",
})
```

`yourBackendStartSession(payload)` represents your application's authenticated backend client and must return a table with `visitorUrl`. If you already have the response, call `Adquivo.visitorUrl(origin, session)` directly. Use the SDK only where your Roblox experience and audience can use its allowed external flows.
