faceping.aidocs

Examples

Copy-paste integrations for popular frameworks: create an enrolment link at sign-up or checkout, show the widget, accept signed check results, handle withdrawals.

Every integration does the same two things on your server, with your API key kept in an environment variable (FACEPING_API_KEY):

  1. When someone signs up, joins or buys a ticket, create an enrolment link for them and render the widget on the confirmation page.
  2. When a person withdraws consent or asks for erasure, remove them from the list.

Pick your stack; the choice is remembered across the docs.

Show the widget after sign-up or checkout#

These examples use a ticket shop's order confirmation page, with the ticket number as the personId. For a gym or membership app it's the same pattern: create the link on your welcome or account page and pass your membership number as the personId.

// npm i express (Node 18+ has fetch built in)
import express from "express";
const app = express();
const FACEPING = "https://api-eu.faceping.ai";

async function enrollmentToken(listId, personId) {
  const res = await fetch(`${FACEPING}/v1/lists/${listId}/enrollment-links`, {
    method: "POST",
    headers: { "X-Api-Key": process.env.FACEPING_API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ personId }),
  });
  if (!res.ok) throw new Error(`FacePing ${res.status}: ${await res.text()}`); // some errors (429) have no body
  return (await res.json()).token;
}

app.get("/orders/:id/confirmation", async (req, res) => {
  const order = await orders.find(req.params.id);             // your code
  const token = await enrollmentToken(order.faceListId, order.ticketNumber);
  res.send(`
    <h1>You're going!</h1>
    <div data-faceping-token="${token}"></div>
    <script src="https://faceping.ai/widget.js" async></script>`);
});
// app/orders/[id]/confirmation/page.tsx: a Server Component, so the key never reaches the browser
const FACEPING = "https://api-eu.faceping.ai";

async function enrollmentToken(listId: string, personId: string) {
  const res = await fetch(`${FACEPING}/v1/lists/${listId}/enrollment-links`, {
    method: "POST",
    headers: { "X-Api-Key": process.env.FACEPING_API_KEY!, "Content-Type": "application/json" },
    body: JSON.stringify({ personId }),
    cache: "no-store",
  });
  if (!res.ok) throw new Error(`FacePing ${res.status}`);
  return (await res.json()).token as string;
}

export default async function Confirmation({ params }: { params: Promise<{ id: string }> }) {
  const order = await getOrder((await params).id);            // your code
  const token = await enrollmentToken(order.faceListId, order.ticketNumber);
  return (
    <>
      <h1>You&apos;re going!</h1>
      <div data-faceping-token={token} />
      <script src="https://faceping.ai/widget.js" async />
    </>
  );
}
# pip install flask requests
import os, requests
from flask import Flask, render_template_string

app = Flask(__name__)
FACEPING = "https://api-eu.faceping.ai"

def enrollment_token(list_id: str, person_id: str) -> str:
    r = requests.post(f"{FACEPING}/v1/lists/{list_id}/enrollment-links",
                      headers={"X-Api-Key": os.environ["FACEPING_API_KEY"]},
                      json={"personId": person_id}, timeout=15)
    r.raise_for_status()
    return r.json()["token"]

@app.get("/orders/<order_id>/confirmation")
def confirmation(order_id):
    order = get_order(order_id)                                 # your code
    token = enrollment_token(order.face_list_id, order.ticket_number)
    return render_template_string("""
      <h1>You're going!</h1>
      <div data-faceping-token="{{ token }}"></div>
      <script src="https://faceping.ai/widget.js" async></script>""", token=token)
# views.py: pip install requests
import os, requests
from django.shortcuts import get_object_or_404, render
from .models import Order

FACEPING = "https://api-eu.faceping.ai"

def enrollment_token(list_id, person_id):
    r = requests.post(f"{FACEPING}/v1/lists/{list_id}/enrollment-links",
                      headers={"X-Api-Key": os.environ["FACEPING_API_KEY"]},
                      json={"personId": person_id}, timeout=15)
    r.raise_for_status()
    return r.json()["token"]

def confirmation(request, order_id):
    order = get_object_or_404(Order, pk=order_id, user=request.user)
    token = enrollment_token(order.face_list_id, order.ticket_number)
    return render(request, "orders/confirmation.html", {"faceping_token": token})

# orders/confirmation.html:
#   <div data-faceping-token="{{ faceping_token }}"></div>
#   <script src="https://faceping.ai/widget.js" async></script>
<?php
// app/Http/Controllers/OrderConfirmationController.php
namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Support\Facades\Http;

class OrderConfirmationController extends Controller
{
    private const FACEPING = 'https://api-eu.faceping.ai';

    public function __invoke(Order $order)
    {
        $token = Http::withHeaders(['X-Api-Key' => config('services.faceping.key')])
            ->post(self::FACEPING . "/v1/lists/{$order->face_list_id}/enrollment-links", [
                'personId' => $order->ticket_number,
            ])
            ->throw()
            ->json('token');

        return view('orders.confirmation', ['facepingToken' => $token]);
    }
}

// config/services.php: 'faceping' => ['key' => env('FACEPING_API_KEY')],
// resources/views/orders/confirmation.blade.php:
//   <div data-faceping-token="{{ $facepingToken }}"></div>
//   <script src="https://faceping.ai/widget.js" async></script>
// Program.cs: register once:
// builder.Services.AddHttpClient("faceping", c => {
//     c.BaseAddress = new Uri("https://api-eu.faceping.ai/");
//     c.DefaultRequestHeaders.Add("X-Api-Key", builder.Configuration["FACEPING_API_KEY"]);
// });

app.MapGet("/orders/{id}/confirmation", async (string id, IHttpClientFactory http, OrderStore orders) =>
{
    var order = await orders.FindAsync(id);                     // your code
    var res = await http.CreateClient("faceping").PostAsJsonAsync(
        $"v1/lists/{order.FaceListId}/enrollment-links", new { personId = order.TicketNumber });
    res.EnsureSuccessStatusCode();
    var token = (await res.Content.ReadFromJsonAsync<EnrollmentLink>())!.Token;

    return Results.Content($"""
        <h1>You're going!</h1>
        <div data-faceping-token="{token}"></div>
        <script src="https://faceping.ai/widget.js" async></script>
        """, "text/html");
});

record EnrollmentLink(string Token, DateTimeOffset ExpiresAt, string Url);
// ConfirmationController.java: Spring Boot 3.2+ (RestClient)
@Controller
class ConfirmationController {
    private final RestClient faceping;
    private final OrderRepository orders;

    ConfirmationController(@Value("${FACEPING_API_KEY}") String apiKey, OrderRepository orders) {
        this.orders = orders;
        this.faceping = RestClient.builder()
            .baseUrl("https://api-eu.faceping.ai")
            .defaultHeader("X-Api-Key", apiKey)
            .build();
    }

    record EnrollmentLink(String token, String expiresAt, String url) {}

    @GetMapping("/orders/{id}/confirmation")
    String confirmation(@PathVariable String id, Model model) {
        var order = orders.findById(id).orElseThrow();
        var token = faceping.post()
            .uri("/v1/lists/{listId}/enrollment-links", order.getFaceListId())
            .contentType(MediaType.APPLICATION_JSON)
            .body(Map.of("personId", order.getTicketNumber()))
            .retrieve()
            .body(EnrollmentLink.class);
        model.addAttribute("facepingToken", token.token());
        return "confirmation"; // <div th:attr="data-faceping-token=${facepingToken}"></div> + the widget.js script tag
    }
}
// Go 1.22+ (net/http routing with path values)
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "html/template"
    "net/http"
    "os"
)

const faceping = "https://api-eu.faceping.ai"

func enrollmentToken(listID, personID string) (string, error) {
    body, _ := json.Marshal(map[string]string{"personId": personID})
    req, _ := http.NewRequest("POST", fmt.Sprintf("%s/v1/lists/%s/enrollment-links", faceping, listID), bytes.NewReader(body))
    req.Header.Set("X-Api-Key", os.Getenv("FACEPING_API_KEY"))
    req.Header.Set("Content-Type", "application/json")
    res, err := http.DefaultClient.Do(req)
    if err != nil {
        return "", err
    }
    defer res.Body.Close()
    if res.StatusCode != http.StatusCreated {
        return "", fmt.Errorf("faceping: %s", res.Status)
    }
    var out struct{ Token string `json:"token"` }
    if err := json.NewDecoder(res.Body).Decode(&out); err != nil {
        return "", err
    }
    return out.Token, nil
}

var page = template.Must(template.New("c").Parse(`<h1>You're going!</h1>
<div data-faceping-token="{{.}}"></div>
<script src="https://faceping.ai/widget.js" async></script>`))

func main() {
    http.HandleFunc("GET /orders/{id}/confirmation", func(w http.ResponseWriter, r *http.Request) {
        order := findOrder(r.PathValue("id")) // your code
        token, err := enrollmentToken(order.FaceListID, order.TicketNumber)
        if err != nil {
            http.Error(w, "face check-in unavailable", http.StatusBadGateway)
            return
        }
        page.Execute(w, token)
    })
    http.ListenAndServe(":8080", nil)
}
# app/controllers/confirmations_controller.rb
require "net/http"

class ConfirmationsController < ApplicationController
  FACEPING = URI("https://api-eu.faceping.ai")

  def show
    order = current_user.orders.find(params[:order_id])
    @faceping_token = enrollment_token(order.face_list_id, order.ticket_number)
  end

  private

  def enrollment_token(list_id, person_id)
    uri = FACEPING.dup.tap { |u| u.path = "/v1/lists/#{list_id}/enrollment-links" }
    res = Net::HTTP.post(uri, { personId: person_id }.to_json,
                         "X-Api-Key" => ENV.fetch("FACEPING_API_KEY"), "Content-Type" => "application/json")
    raise "FacePing #{res.code}" unless res.is_a?(Net::HTTPSuccess)
    JSON.parse(res.body).fetch("token")
  end
end

# app/views/confirmations/show.html.erb:
#   <div data-faceping-token="<%= @faceping_token %>"></div>
#   <script src="https://faceping.ai/widget.js" async></script>

POST /v1/lists/{listId}/enrollment-links →

Accept a signed check result#

When a check-in device's result has to count on your server (a member check-in, a door, a payout), the app sends signedResult and your server asks FacePing whether it's genuine. Issue a nonce for each check first and send it along, so a result can only answer the check it was made for. See Signed check results.

import { randomBytes } from "node:crypto";
app.use(express.json());

app.post("/checks/nonce", requireDevice, async (req, res) => {    // your device auth
  const nonce = randomBytes(16).toString("base64url");
  await nonces.save(nonce, { expiresAt: Date.now() + 5 * 60_000 });  // your store, single use
  res.json({ nonce });
});

app.post("/checks", requireDevice, async (req, res) => {
  const { signedResult, nonce, badge } = req.body;
  if (!(await nonces.take(nonce))) return res.status(400).json({ error: "Unknown or expired nonce" });
  const fp = await fetch(`${FACEPING}/v1/check-results/verify`, {
    method: "POST",
    headers: { "X-Api-Key": process.env.FACEPING_API_KEY, "Content-Type": "application/json" },
    body: JSON.stringify({ signedResult, nonce }),
  });
  if (fp.status === 409 || fp.status === 422) return res.status(400).json(await fp.json());   // { reason, message }
  if (!fp.ok) throw new Error(`FacePing ${fp.status}: ${await fp.text()}`);
  const check = await fp.json();
  if (!check.match || check.personId !== badge) return res.json({ recorded: false, outcome: check.outcome });
  await checkIns.record(check.personId, check.checkedAt, check.deviceLabel);   // your code
  res.json({ recorded: true });
});
import os, secrets, time
import requests
from flask import Flask, request, jsonify

FACEPING = "https://api-eu.faceping.ai"
app = Flask(__name__)

@app.post("/checks/nonce")
def new_nonce():
    nonce = secrets.token_urlsafe(16)
    nonces.save(nonce, expires_at=time.time() + 300)        # your store, single use
    return jsonify(nonce=nonce)

@app.post("/checks")
def record_check():
    body = request.get_json()
    if not nonces.take(body["nonce"]):
        return jsonify(error="Unknown or expired nonce"), 400
    fp = requests.post(f"{FACEPING}/v1/check-results/verify",
                       headers={"X-Api-Key": os.environ["FACEPING_API_KEY"]},
                       json={"signedResult": body["signedResult"], "nonce": body["nonce"]}, timeout=15)
    if fp.status_code in (409, 422):
        return jsonify(fp.json()), 400                       # {"reason": ..., "message": ...}
    fp.raise_for_status()
    check = fp.json()
    if not check["match"] or check["personId"] != body["badge"]:
        return jsonify(recorded=False, outcome=check["outcome"])
    clock_ins.record(check["personId"], check["checkedAt"], check["deviceLabel"])   # your code
    return jsonify(recorded=True)
// using System.Buffers.Text; using System.Net; using System.Security.Cryptography; using System.Text.Json;
// builder.Services.AddHttpClient("faceping", c => { c.BaseAddress = new("https://api-eu.faceping.ai/");
//     c.DefaultRequestHeaders.Add("X-Api-Key", builder.Configuration["FacePing:ApiKey"]); });
app.MapPost("/checks/nonce", async (INonceStore nonces) =>
{
    var nonce = Base64Url.EncodeToString(RandomNumberGenerator.GetBytes(16));
    await nonces.SaveAsync(nonce, TimeSpan.FromMinutes(5));           // your store, single use
    return Results.Ok(new { nonce });
});

app.MapPost("/checks", async (CheckRequest req, INonceStore nonces, IHttpClientFactory http, ICheckIns checkIns) =>
{
    if (!await nonces.TakeAsync(req.Nonce)) return Results.BadRequest(new { error = "Unknown or expired nonce" });
    var fp = await http.CreateClient("faceping").PostAsJsonAsync("v1/check-results/verify", new { req.SignedResult, req.Nonce });
    if (fp.StatusCode is HttpStatusCode.Conflict or HttpStatusCode.UnprocessableEntity)
        return Results.BadRequest(await fp.Content.ReadFromJsonAsync<JsonElement>());   // { reason, message }
    fp.EnsureSuccessStatusCode();
    var check = (await fp.Content.ReadFromJsonAsync<CheckResult>())!;
    if (!check.Match || check.PersonId != req.Badge) return Results.Ok(new { recorded = false, outcome = check.Outcome });
    await checkIns.RecordAsync(check.PersonId, check.CheckedAt, check.DeviceLabel);  // your code
    return Results.Ok(new { recorded = true });
});

record CheckRequest(string SignedResult, string Nonce, string Badge);
record CheckResult(bool Match, string Outcome, string PersonId, DateTimeOffset CheckedAt, string DeviceLabel);

Remove someone's face data#

Call this when a person withdraws consent or asks for erasure, for example from your account page or support tooling. Check the answer: 204 means removed, 404 means no one with that personId is on the list (nothing to erase), and anything else means it didn't happen, so log it and retry. A personId with a slash works URL-encoded (%2F) or as it is.

const res = await fetch(`${FACEPING}/v1/lists/${listId}/people/${encodeURIComponent(personId)}`, {
  method: "DELETE",
  headers: { "X-Api-Key": process.env.FACEPING_API_KEY },
});
if (res.status !== 204 && res.status !== 404) throw new Error(`FacePing erasure failed: ${res.status} ${await res.text()}`);
// app/actions.ts
"use server";
export async function removeFaceData(listId: string, personId: string) {
  const res = await fetch(`https://api-eu.faceping.ai/v1/lists/${listId}/people/${encodeURIComponent(personId)}`, {
    method: "DELETE",
    headers: { "X-Api-Key": process.env.FACEPING_API_KEY! },
  });
  // 204 = removed, 404 = not on the list; anything else didn't happen
  if (res.status !== 204 && res.status !== 404) throw new Error(`FacePing erasure failed: ${res.status} ${await res.text()}`);
}
from urllib.parse import quote
res = requests.delete(f"{FACEPING}/v1/lists/{list_id}/people/{quote(person_id, safe='')}",
                      headers={"X-Api-Key": os.environ["FACEPING_API_KEY"]}, timeout=15)
if res.status_code not in (204, 404):  # 204 = removed, 404 = not on the list
    raise RuntimeError(f"FacePing erasure failed: {res.status_code} {res.text}")
from urllib.parse import quote
res = requests.delete(f"{FACEPING}/v1/lists/{list_id}/people/{quote(person_id, safe='')}",
                      headers={"X-Api-Key": os.environ["FACEPING_API_KEY"]}, timeout=15)
if res.status_code not in (204, 404):  # 204 = removed, 404 = not on the list
    raise RuntimeError(f"FacePing erasure failed: {res.status_code} {res.text}")
$res = Http::withHeaders(['X-Api-Key' => config('services.faceping.key')])
    ->delete('https://api-eu.faceping.ai/v1/lists/' . $listId . '/people/' . rawurlencode($personId));
if (! in_array($res->status(), [204, 404])) { // 204 = removed, 404 = not on the list
    throw new RuntimeException("FacePing erasure failed: {$res->status()} {$res->body()}");
}
var res = await http.CreateClient("faceping").DeleteAsync($"v1/lists/{listId}/people/{Uri.EscapeDataString(personId)}");
if (res.StatusCode is not (System.Net.HttpStatusCode.NoContent or System.Net.HttpStatusCode.NotFound)) // 204 = removed, 404 = not on the list
    throw new InvalidOperationException($"FacePing erasure failed: {(int)res.StatusCode} {await res.Content.ReadAsStringAsync()}");
// 204 = removed; 404 = not on the list; anything else throws (RestClientResponseException)
faceping.delete()
    .uri("/v1/lists/{listId}/people/{personId}", listId, personId)
    .retrieve()
    .onStatus(s -> s.value() == 404, (request, response) -> { })
    .toBodilessEntity();
// import ("io"; "net/url")
req, _ := http.NewRequest("DELETE",
    fmt.Sprintf("%s/v1/lists/%s/people/%s", faceping, listID, url.PathEscape(personID)), nil)
req.Header.Set("X-Api-Key", os.Getenv("FACEPING_API_KEY"))
res, err := http.DefaultClient.Do(req)
if err != nil {
    return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusNoContent && res.StatusCode != http.StatusNotFound { // 204 = removed, 404 = not on the list
    body, _ := io.ReadAll(res.Body)
    return fmt.Errorf("FacePing erasure failed: %d %s", res.StatusCode, body)
}
uri = URI("https://api-eu.faceping.ai/v1/lists/#{list_id}/people/#{ERB::Util.url_encode(person_id)}")
res = Net::HTTP.start(uri.host, uri.port, use_ssl: true) do |http|
  http.delete(uri.path, "X-Api-Key" => ENV.fetch("FACEPING_API_KEY"))
end
# 204 = removed, 404 = not on the list
raise "FacePing erasure failed: #{res.code} #{res.body}" unless %w[204 404].include?(res.code)

DELETE /v1/lists/{listId}/people/{personId} →