Al klant bij Spur?

Inloggen
Examples

React and Svelte

One backend route mints tokens; one component loads the frame, listens to it and switches records. Copy them as they are. Both components are the ones we run against Spur in our own test app.

Your backend

Two routes: one returns a fresh embedUrl, the other hands the conversation between Spur’s AI agent and your team. The components below call the first; your page calls the second from the frame’s events.

server.js
// Your CRM's backend (Node + Express). The Spur API key lives here and never
// reaches the browser; neither do customers' phone numbers.
import express from 'express';

const SPUR_API = 'https://api.spurnow.com';
// A workspace API key used only for the embed.
const SPUR_KEY = process.env.SPUR_EMBED_API_KEY;
const SPUR_USER_ID = 318; // the Spur user the frame acts as
const CRM_ORIGIN = 'https://crm.acme.com'; // on your allowed list in Spur

const app = express();
app.use(express.json());
// requireCrmLogin, canSeeContact and canSeeConversation are your CRM's own checks.

function spur(path, body) {
  return fetch(`${SPUR_API}${path}`, {
    method: 'POST',
    headers: {
      Authorization: `Bearer ${SPUR_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(body),
  });
}

// A fresh, single-use embed URL for every frame load (valid 60 seconds).
app.post('/api/spur/embed-url', requireCrmLogin, async (req, res) => {
  // codeChallenge is the SHA-256 of a verifier the page keeps; Spur checks its format.
  const { contactId, channelId, codeChallenge } = req.body;
  // The browser names the record: check this CRM user may see it.
  if (!(await canSeeContact(req.user, contactId))) return res.sendStatus(403);
  const r = await spur('/embed/tokens', {
    user: { id: SPUR_USER_ID },
    contact: { id: Number(contactId) },
    channelId: Number(channelId), // which of your WhatsApp numbers
    origin: CRM_ORIGIN,
    codeChallenge,
  });
  const data = await r.json();
  if (!r.ok) return res.status(r.status).json(data);
  res.json({ embedUrl: data.embedUrl });
});

// AI handoff: "user" pauses Spur's AI agent here, "ai" hands it back.
app.post('/api/spur/handoff', requireCrmLogin, async (req, res) => {
  const { conversationId, to } = req.body;
  // Same here: the conversation must belong to a record this user may see.
  if (!(await canSeeConversation(req.user, conversationId))) return res.sendStatus(403);
  const r = await spur(
    `/conversations/${Number(conversationId)}/assign`,
    to === 'user' ? { to: 'user', userId: SPUR_USER_ID } : { to: 'ai' },
  );
  res.status(r.status).json(await r.json());
});

app.listen(3000);

React

SpurConversation.tsx
import { useEffect, useRef, useState } from 'react';

const SPUR_ORIGIN = 'https://embed.spurnow.com';

const base64url = (bytes: ArrayBuffer | Uint8Array) =>
  btoa(String.fromCharCode(...new Uint8Array(bytes)))
    .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

// A new code verifier for every token. It stays in this page: only its SHA-256
// goes to your server, and the verifier itself only to the frame.
async function newVerifier() {
  const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
  return { codeVerifier, codeChallenge: base64url(digest) };
}

export type SpurEvent = { type: `spur:${string}`; [key: string]: unknown };

type Props = {
  contactId: number; // Spur IDs only: phone numbers stay on your server
  channelId: number; // which of your WhatsApp numbers
  onEvent?: (event: SpurEvent) => void;
};

/** One Spur WhatsApp conversation. Switching contacts reuses the session. */
export function SpurConversation({ contactId, channelId, onEvent }: Props) {
  const frame = useRef<HTMLIFrameElement>(null);
  const signedIn = useRef(false);
  const target = useRef({ contactId, channelId });
  target.current = { contactId, channelId };
  const handler = useRef(onEvent);
  handler.current = onEvent;
  const loads = useRef(0);
  const retries = useRef<number[]>([]);
  const verifier = useRef('');
  const [failed, setFailed] = useState(false);

  // A fresh single-use URL from your backend for every load.
  async function load() {
    const request = ++loads.current;
    signedIn.current = false;
    const { codeVerifier, codeChallenge } = await newVerifier();
    let embedUrl: string | undefined;
    try {
      const r = await fetch('/api/spur/embed-url', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...target.current, codeChallenge }),
      });
      if (r.ok) ({ embedUrl } = await r.json());
    } catch {
      // No connection: handled like a refused mint below.
    }
    // A newer load started meanwhile: it has the record on screen now.
    if (request !== loads.current) return;
    // Minting can fail (403, 429, an outage): keep the frame and say so.
    setFailed(!embedUrl);
    if (!embedUrl) return;
    // Signed in only once this new page says so.
    signedIn.current = false;
    verifier.current = codeVerifier;
    if (frame.current) frame.current.src = embedUrl;
  }

  useEffect(() => {
    if (signedIn.current) {
      // Already signed in: switch threads without a new token.
      frame.current?.contentWindow?.postMessage(
        { type: 'spur:openConversation', contactId, channelId },
        SPUR_ORIGIN,
      );
    } else {
      load();
    }
  }, [contactId, channelId]);

  useEffect(() => {
    function onMessage(e: MessageEvent) {
      if (e.origin !== SPUR_ORIGIN) return;
      if (e.source !== frame.current?.contentWindow) return;
      const event = e.data as SpurEvent;
      if (event.type === 'spur:ready' && verifier.current) {
        // The frame asks for the verifier of the token it was given.
        frame.current?.contentWindow?.postMessage(
          { type: 'spur:verify', codeVerifier: verifier.current },
          SPUR_ORIGIN,
        );
      }
      if (event.type === 'spur:authenticated') signedIn.current = true;
      if (event.type === 'spur:authRequired') {
        // Session over: mint again, a few times a minute at most. Other reasons
        // (a removed site, an inactive user) need an admin, not a retry.
        const now = Date.now();
        retries.current = [...retries.current, now].filter((t) => now - t < 60_000);
        const { reason } = event;
        const fixable = reason === 'expired' || reason === 'invalidToken';
        if (fixable && retries.current.length <= 3) load();
      }
      handler.current?.(event);
    }
    window.addEventListener('message', onMessage);
    return () => window.removeEventListener('message', onMessage);
  }, []);

  return (
    <>
      {failed && <p role="alert">Couldn't open this conversation. Try again in a moment.</p>}
      <iframe
        ref={frame}
        title="WhatsApp conversation"
        allow="clipboard-write; microphone"
        style={{ width: '100%', height: '100%', border: 0 }}
      />
    </>
  );
}

Use it on your record page. Here the page pauses the AI agent when the conversation opens and hands it back when someone closes the ticket in the frame:

LeadPage.tsx
function onSpurEvent(event: SpurEvent) {
  switch (event.type) {
    case 'spur:conversationOpened': // someone has the lead open: pause the AI
      return handoff(event.conversationId, 'user');
    case 'spur:conversationStatusChanged': // closed in the frame: back to the AI
      if (event.conversationStatus !== 'CLOSED') return;
      return handoff(event.conversationId, 'ai');
  }
}

<SpurConversation
  contactId={lead.spurContactId}
  channelId={lead.spurChannelId}
  onEvent={onSpurEvent}
/>

Svelte

Svelte 5, with runes.

SpurConversation.svelte
<script lang="ts">
  const SPUR_ORIGIN = 'https://embed.spurnow.com';

  const base64url = (bytes: ArrayBuffer | Uint8Array) =>
    btoa(String.fromCharCode(...new Uint8Array(bytes)))
      .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

  // A new code verifier for every token. It stays in this page: only its SHA-256
  // goes to your server, and the verifier itself only to the frame.
  async function newVerifier() {
    const codeVerifier = base64url(crypto.getRandomValues(new Uint8Array(32)));
    const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
    return { codeVerifier, codeChallenge: base64url(digest) };
  }

  type SpurEvent = { type: `spur:${string}`; [key: string]: unknown };

  type Props = {
    contactId: number; // Spur IDs only: phone numbers stay on your server
    channelId: number; // which of your WhatsApp numbers
    onevent?: (event: SpurEvent) => void;
  };

  let { contactId, channelId, onevent }: Props = $props();

  let frame: HTMLIFrameElement | undefined = $state();
  let signedIn = false;
  let loads = 0;
  let retries: number[] = [];
  let verifier = '';
  let failed = $state(false);

  // A fresh single-use URL from your backend for every load.
  async function load() {
    const request = ++loads;
    signedIn = false;
    const { codeVerifier, codeChallenge } = await newVerifier();
    let embedUrl: string | undefined;
    try {
      const r = await fetch('/api/spur/embed-url', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ contactId, channelId, codeChallenge })
      });
      if (r.ok) ({ embedUrl } = await r.json());
    } catch {
      // No connection: handled like a refused mint below.
    }
    // A newer load started meanwhile: it has the record on screen now.
    if (request !== loads) return;
    // Minting can fail (403, 429, an outage): keep the frame and say so.
    failed = !embedUrl;
    if (!embedUrl) return;
    // Signed in only once this new page says so.
    signedIn = false;
    verifier = codeVerifier;
    if (frame) frame.src = embedUrl;
  }

  $effect(() => {
    const target = { contactId, channelId };
    if (!frame) return;
    if (signedIn) {
      // Already signed in: switch threads without a new token.
      const command = { type: 'spur:openConversation', ...target };
      frame.contentWindow?.postMessage(command, SPUR_ORIGIN);
    } else {
      load();
    }
  });

  function onMessage(e: MessageEvent) {
    if (e.origin !== SPUR_ORIGIN) return;
    if (e.source !== frame?.contentWindow) return;
    const event = e.data as SpurEvent;
    if (event.type === 'spur:ready' && verifier) {
      // The frame asks for the verifier of the token it was given.
      const answer = { type: 'spur:verify', codeVerifier: verifier };
      frame?.contentWindow?.postMessage(answer, SPUR_ORIGIN);
    }
    if (event.type === 'spur:authenticated') signedIn = true;
    if (event.type === 'spur:authRequired') {
      // Session over: mint again, a few times a minute at most. Other reasons
      // (a removed site, an inactive user) need an admin, not a retry.
      const now = Date.now();
      retries = [...retries, now].filter((t) => now - t < 60_000);
      const { reason } = event;
      const fixable = reason === 'expired' || reason === 'invalidToken';
      if (fixable && retries.length <= 3) load();
    }
    onevent?.(event);
  }
</script>

<svelte:window onmessage={onMessage} />

{#if failed}
  <p role="alert">Couldn't open this conversation. Try again in a moment.</p>
{/if}
<iframe
  bind:this={frame}
  title="WhatsApp conversation"
  allow="clipboard-write; microphone"
  style="width: 100%; height: 100%; border: 0"
></iframe>
LeadPage.svelte
<script lang="ts">
  function onSpurEvent(event: SpurEvent) {
    switch (event.type) {
      case 'spur:conversationOpened': // someone has the lead open: pause the AI
        return handoff(event.conversationId, 'user');
      case 'spur:conversationStatusChanged': // closed in the frame: back to the AI
        if (event.conversationStatus !== 'CLOSED') return;
        return handoff(event.conversationId, 'ai');
    }
  }
</script>

<SpurConversation
  contactId={lead.spurContactId}
  channelId={lead.spurChannelId}
  onevent={onSpurEvent}
/>

The handoff helper

handoff.ts
// Calls your backend's /api/spur/handoff route above.
export async function handoff(conversationId: unknown, to: 'user' | 'ai') {
  await fetch('/api/spur/handoff', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ conversationId, to }),
  });
}

Why both calls matter is in the handoff sequence.

Vue, Angular and the rest

The pattern doesn’t depend on the framework. Whatever you use, keep to these rules:

  • ✓ Mint a fresh token for every frame load. Never cache embedUrl, and drop a URL that arrives after a newer one was requested.
  • ✓ Make a new code verifier for every token, and answer spur:ready with spur:verify, sent to Spur’s origin only.
  • ✓ On spur:authRequired, mint again only for expired or invalidToken, and only a few times a minute. originMismatch and userInactive need an admin.
  • ✓ Check event.origin and event.source before you read event.data.
  • ✓ Once the frame is signed in, switch records with spur:openConversation, not a new token.
  • ✓ Keep phone numbers on your server. The browser only ever needs Spur IDs.

To put text in the reply box, for example from a CRM template, send spur:prefill. The user still reviews it and presses Send:

crm-page.js
frame.contentWindow.postMessage(
  { type: 'spur:prefill', text: 'Hi Rahul, your consult is confirmed for 4 pm.' },
  'https://embed.spurnow.com',
);

Every event and command is in Frame events.