Skip to content
中文

Embed with one line

Add one loader script to display a Praxis-hosted iframe chat interface. Save its appearance in the Dashboard while users stay on your page. “One line” describes frontend installation; your backend still issues one-time grant codes for signed-in users, and the iframe exchanges and renews the customer access token itself. Your backend issues that code with the organization API key at POST /customer/v1/grant_codes, naming agent:<id>:chat in resources; see Customer sign-in.

Prepare an HTTPS host

You need an HTTPS website whose pages and backend you can change, Bun, an API key in the agent’s organization, and a service agent with a short number. Your demo HTTPS entry point must forward to 127.0.0.1:4242 and preserve the original Host header. Your host supplies its domain and TLS certificate.

In the Dashboard, open 服务智能体 → your agent → 接入 → 接入方式与外观 → 嵌入设置. Add the actual HTTPS origin under 允许嵌入的网站, and click 保存嵌入设置. For example, use https://support.example.com, without a path. Embed settings can be configured in the Dashboard or through the API; see embed settings.

Enabling 允许 localhost(本地开发) alone does not authorize iframe embedding. This guide requires a saved HTTPS origin. For HTTP-only local testing, start with the Kit quickstart.

Record two identifiers. Grant code requests use the public ID, agent_…. The script’s data-agent uses the short number copied from the Dashboard header: 5–8 letters or digits. Do not put the full ID in the short-number attribute.

Runtime environment and vaults come from the agent version pinned by the grant code. Set environment_id and vault_ids in the agent configuration, save and apply it, then issue a new grant code. The old embed-policy fields are deprecated and do not choose the session environment.

Provide a grant code endpoint

Save this as server.ts behind your HTTPS entry point. It uses two password-protected test accounts. For production, replace authenticate with your host’s session validation and retain CSRF protection. Set HOST_ORIGIN to the actual HTTPS origin, without a trailing slash. Configure all environment variables only on the backend.

import { timingSafeEqual } from "node:crypto";
const apiKey = process.env.PRAXIS_API_KEY;
const agentId = process.env.PRAXIS_AGENT_ID;
const password = process.env.DEMO_PASSWORD;
if (!apiKey || !agentId || !password) throw new Error("Set the three server variables");
const origin = process.env.HOST_ORIGIN;
if (!origin || new URL(origin).protocol !== "https:") throw new Error("Set HOST_ORIGIN to your HTTPS origin");
const noStore = { "Cache-Control": "no-store" };
function authenticate(request: Request): string | undefined {
const supplied = Buffer.from(request.headers.get("Authorization") ?? "");
for (const id of ["customer_123", "customer_456"]) {
const expected = Buffer.from("Basic " + Buffer.from(`${id}:${password}`).toString("base64"));
if (supplied.length === expected.length && timingSafeEqual(supplied, expected)) return id;
}
}
Bun.serve({
hostname: "127.0.0.1", port: 4242,
async fetch(request) {
const url = new URL(request.url);
if (request.headers.get("Host") !== new URL(origin).host) return new Response("Host rejected", { status: 403 });
const userId = authenticate(request);
if (!userId) return new Response("Sign in", {
status: 401, headers: { ...noStore, "WWW-Authenticate": 'Basic realm="Local demo"' },
});
if (request.method === "GET" && url.pathname === "/") {
return new Response(Bun.file("index.html"), { headers: noStore });
}
if (request.method !== "POST" || url.pathname !== "/api/praxis-grant-code") {
return new Response("Not found", { status: 404 });
}
if (request.headers.get("Origin") !== origin) {
return new Response("Origin rejected", { status: 403 });
}
try {
// Kit sends an anonymous visitor's token here when one signs in; pass it on to merge the visitor.
const input = await request.json().catch(() => ({}));
const anonymous = typeof input?.anonymous_access_token === "string" ? input.anonymous_access_token : undefined;
const response = await fetch("https://api.deepraxis.com/customer/v1/grant_codes", {
method: "POST",
headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" },
body: JSON.stringify({ customer_id: userId, resources: [{ scope: `agent:${agentId}:chat` }], origin, ...(anonymous ? { anonymous_access_token: anonymous } : {}) }),
signal: AbortSignal.timeout(30_000),
});
if (!response.ok) return new Response("Grant code failed", {
status: response.status, headers: noStore,
});
const data = await response.json();
if (typeof data.code !== "string") throw new Error("Invalid grant code response");
return Response.json({ code: data.code }, { headers: noStore });
} catch {
return new Response("Sign-in service unavailable", { status: 502, headers: noStore });
}
},
});
console.log(origin);

Start the server after saving index.html in the next section. DEMO_PASSWORD is your chosen test-account password, not an API key. Sign in through the browser as customer_123 or customer_456.

终端窗口
export HOST_ORIGIN="https://support.example.com"
export PRAXIS_AGENT_ID="agent_REPLACE_ME"
# Set PRAXIS_API_KEY and DEMO_PASSWORD in the server process.
bun server.ts

Whenever the iframe needs to sign in, the loader sends a POST request to data-grant-code-endpoint with browser credentials and a JSON body that is empty, or carries anonymous_access_token when an anonymous visitor is merged. That endpoint must derive the user ID from validated authentication on every issuance and use HOST_ORIGIN as the grant code origin. After Praxis returns HTTP 201, the host returns only code to the loader. The iframe exchanges it for a customer access token and renews that token; when the token is refused it asks the endpoint for one new code. Keep the API key out of HTML.

Install the loader

Save this as index.html, replacing ABC123 with the actual short number. For an existing page, insert only the script tag where you want chat to appear.

<!doctype html>
<html lang="en">
<meta charset="utf-8">
<title>Order assistant</title>
<body>
<h1>Order support</h1>
<script src="https://cdn.deepraxis.com/v1/loader.js" data-agent="ABC123" data-grant-code-endpoint="/api/praxis-grant-code" async></script>
</body>
</html>

The loader creates the iframe and passes it the grant code. Opening or pasting an iframe address alone does not supply the host user’s identity.

Script attributePurpose
data-agentRequired agent short number
data-grant-code-endpointRequired for signed-in users; the host grant code endpoint, same-origin in this example
data-publishable-keyFor anonymous visitors instead of data-grant-code-endpoint; give exactly one of the two
data-layoutOptional: inline, popup, sidebar, or modal
data-launcherOptional: bubble, none, or an existing button’s CSS selector

When layout and launcher attributes are absent, the loader uses saved Dashboard appearance. Without a saved layout, it uses popup. Explicit attributes override the corresponding settings. With inline, the script’s location determines insertion; reserve enough height in its containing element.

Save appearance

Open 接入 → 接入方式与外观 → iframe. Adjust the name, greeting, and layout, then click 保存. Expect confirmation that changes apply after refreshing the embedded page. Refresh your host page to verify. Persistent appearance can currently only be configured in the Dashboard.

With data-launcher="none", a floating layout has no default opening button. Supply an existing button’s CSS selector, or control opening in host code. In this example, the button exists before the loader executes:

<button id="open-support" type="button">Open support</button>
<script src="https://cdn.deepraxis.com/v1/loader.js" data-agent="ABC123" data-grant-code-endpoint="/api/praxis-grant-code" data-layout="popup" data-launcher="#open-support" async></script>

This replaces the previous script. Keep only one loader script for the same agent on a page.

Verify and troubleshoot

Open your HTTPS page and sign in. Confirm that chat or its launcher appears, send a question, and receive a reply. Use a separate browser to sign in as the second test account. Confirm it cannot see the first account’s conversations.

In the network panel, check that loader.js loads, the iframe comes from agent.praxisusercontent.com, the host grant code endpoint returns only code, and the iframe then calls /customer/v1/access_tokens successfully. The API key belongs only in server-to-server requests; it must not appear in browser network records.

  • Browser blocks the frame: check that the saved origin matches the page. Your host CSP must allow https://agent.praxisusercontent.com in frame-src and the script CDN in script-src. Do not disable the entire CSP to troubleshoot.
  • Console reports Invalid Praxis loader configuration: check the short number format, the script domain, and that exactly one of the grant code endpoint or publishable key is set.
  • Host endpoint returns HTTP 401 or 403: restore host authentication or correct the same-origin check. Retrying does not sign the user in.

Test origin rejection by loading the script from another HTTPS site outside the allowlist; expect the browser to block embedding. After signing out of your host, request its grant code endpoint again and expect rejection. A hidden button does not prove authorization.

On sign-out, first call await window.PraxisKit.get("ABC123").signOut() to end the Praxis sign-in, then reload the host page so the backend issues for the new identity. Opening or closing the loader only changes visibility; it does not sign the user out of your host.

Next steps