Stop card testing before it reaches your gateway.
Cardvera scores every checkout at the edge — browser, transport, velocity, and the order context your server sends — and gives your server an allow or block before you authorize the card. This reference is everything you need to integrate it.
How it works
A Cardvera integration is one SDK tag on your payment page and three calls from your server, each authenticated with your API key. The key never leaves your backend, and Cardvera never sees a card number.
- Create a session. When your server renders the payment page, it calls
POST /api/sessionswith the order: id, amount (if the page knows it), currency, flow and identity. It gets back{ sid, scriptUrl, expiresAt }, stores thesidon the order, and putsscriptUrlin the page. - Load the SDK. The page loads
<script src="{scriptUrl}" async crossorigin="anonymous">in its<head>. The SDK collects device and behaviour signals and solves a small proof of work in the background. - Assess at submit. The page calls
await Cardvera.assess(), then submits. It resolves with nothing: the browser never learns the verdict, so allow and block look the same there. - Read the verdict, then charge. Your server calls
GET /api/verdict/{sid}with thesidfrom its own order record. Only"action": "allow"authorizes the card. - Report the outcome. After your PSP responds, and again if a chargeback lands later, your server sends it to
POST /api/outcome, with the amount charged. This trains the blocks that stop the next attempt.
sid from Cardvera before the browser was involved, so the verdict it reads is already bound to its order. Never take a session id, order id or result from the browser.<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- scriptUrl from POST /api/sessions for this order (see Quickstart) -->
<script src="https://edge.cardvera.dev/v1/cv.js?sid=3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f" async crossorigin="anonymous"></script>
</head>
<body>
<form id="checkout" method="post" action="/checkout/ORD-1234/pay">
<!-- your payment fields, e.g. your PSP's card element -->
<button type="submit">Pay</button>
</form>
<script>
const form = document.getElementById('checkout');
let submitted = false;
form.addEventListener('submit', async (e) => {
e.preventDefault();
if (submitted) return; // one assess() per page load
submitted = true;
form.querySelector('button').disabled = true;
if (await cardveraAssess(10000) === 'reload') {
location.reload(); // expired or used: a fresh page gets a fresh session
return;
}
form.submit(); // your server reads the verdict, then charges or declines
});
// 'done', 'reload' or 'failed'. Never rejects: your server reads the verdict either way.
async function cardveraAssess(ms) {
try {
const until = Date.now() + ms;
while (!window.Cardvera) { // the async tag may still be loading
if (Date.now() > until) return 'failed'; // never loaded: offline, blocked, CSP
await new Promise((r) => setTimeout(r, 50));
}
const timeout = new Promise((_, fail) =>
setTimeout(() => fail(new Error('timeout')), ms));
await Promise.race([window.Cardvera.assess(), timeout]);
return 'done';
} catch (err) {
return err.code === 'session_expired' || err.code === 'session_used' ? 'reload' : 'failed';
}
}
</script>
</body>
</html>Authentication
Your server authenticates every API call with an API key, sent as a bearer token: Authorization: Bearer cv_ak_…. There is no other header and no query parameter. The browser never needs a key: the SDK works from the session your server created.
Creating a key
In the Cardvera Portal, open API keys and create a key. You choose:
- A name, such as
checkout-server. - Its scopes: one or more of the three below.
- Its IP allowlist: any public IP, or a list of addresses and ranges (below). There's no default; you pick one.
The key is shown once. Copy it straight into your secret store. It works straight away. A key's name and scopes can't change later (create another key instead); its allowlist can. An account can have up to 20 active keys.
Scopes
| Scope | Allows |
|---|---|
sessions:write | POST /api/sessions |
verdicts:read | GET /api/verdict/{sid} |
outcomes:write | POST /api/outcome |
Give each service only what it calls. A checkout server needs sessions:write and verdicts:read; an outcome worker needs only outcomes:write.
Storing keys
- Keep keys in your secret store (Azure Key Vault, AWS Secrets Manager, Vault, …) and give them to your app as an environment variable, such as
CARDVERA_API_KEY. - Never put a key in browser code, a mobile app, a URL, a log line or your repository.
- Use one key per service or environment, so you can revoke one without touching the others.
Revoking and replacing a key
Revoke a key in the Portal. Requests with it stop working within 5 minutes, and a revoke can't be undone. To replace a key without downtime:
- Create the new key, with the same scopes and allowlist.
- Deploy it to every server and job that used the old one.
- Revoke the old key once its Last used time in the Portal stops moving.
If a key may have leaked, revoke it at once, then create a new one.
IP allowlist
Every key has an allowlist, set when you create it. It's either any (any public IP may use the key, and it can't be combined with entries) or a list of 1 to 50 public IPv4 entries, each:
- a single IP, such as
34.120.10.7, or - a CIDR range, such as
34.120.0.0/16.
The Portal rejects, with a message saying why:
- Non-public addresses: private, loopback, link-local, carrier-grade NAT, multicast, reserved and documentation ranges, or anything overlapping one.
- Ranges that are too broad: shorter than
/8. To allow everything, chooseany. - Host bits set: write the network,
34.120.10.0/24, not34.120.10.7/24. - IPv6 addresses: Cardvera's API is reached over IPv4 only, so an IPv6 entry can't match. An IPv4-mapped IPv6 address (
::ffff:34.120.10.7) counts as its IPv4 address. - Ports, duplicates and overlapping entries.
The allowlist is checked against the address your request arrives from: your servers' public egress IP (a NAT gateway, load balancer or proxy), not their private addresses. A request from anywhere else gets 403. The Portal shows each key's last denied IP and time next to its last used IP: compare it with the list to tell whether to fix the list or the route. Allowlist changes take effect within 5 minutes.
Order of checks
Every endpoint checks the key, then the IP, then the scope, and answers with the first failure: 401 for an invalid key, then 403 for an IP not on the key's allowlist, then 403 for a missing scope. None of them has a body. An invalid key is refused before the allowlist is looked at. None of them is worth retrying; see Errors.
# Every call: the key as a bearer token, from your server only.
curl -sS -w ' %{http_code}\n' "https://api.cardvera.dev/api/verdict/$SID" \
-H "Authorization: Bearer $CARDVERA_API_KEY"
# Checked in this order; the first failure answers, with no body:
# 401 invalid key: missing, malformed, unknown or revoked
# 403 this IP isn't on the key's allowlist
# 403 the key lacks this endpoint's scope
# Both 403s look the same: check the key's Last denied and scopes in the Portal.# One entry per line in the Portal. Either the single word: any # or 1 to 50 public IPv4 addresses and ranges: 34.120.0.0/16 52.94.76.10
Quickstart
A complete server-side integration is three functions: create a session, read the verdict, and report the outcome. Each is one HTTPS call with your API key. The samples in this section are a self-contained module in your language: set CARDVERA_API_KEY and wire the three call sites.
1 · Render the checkout
Call createSession on every render of the payment page. Store the sid on the order, overwriting the previous one, and put scriptUrl in the page's <script> tag. The same order gets the same session back until it's assessed, expires or its cart changes, so a reload or a repeated call is safe. Send the page with Cache-Control: no-store. If the call fails, store no sid and render the page without the tag: the pay step then declines (see Failure handling).
2 · Gate the charge
The page awaits Cardvera.assess() and submits. Your pay handler calls getVerdict(sid) with the sid from your order record. It allows only an allow; anything else comes back with a reason: log it and decline. Then open a payment attempt, unique on the sid, so a double submit can't charge twice (see Read the verdict), and authorize.
3 · Close the loop
After the PSP responds, queue a reportOutcome job with the amount charged and the PSP's event time and id. A background worker sends it and retries on 429, 5xx and network errors (see Report outcomes). Report chargebacks and refunds the same way. This feed drives the blocks that stop repeat and follow-on attempts.
@/lib/orders. Anything marked STAND-IN: in-memory stores and stubs that must become your database or gateway client. And the placeholder values, such as the order id ORD-1234.CARDVERA_API_KEY. The module uses one key for all three calls; you can split them by scope. If you send subject, you also need a subject key that you generate (see Session context).# Your API key from the Portal (API keys), injected from your secret store.
API_HOST="https://api.cardvera.dev"
AUTH="Authorization: Bearer $CARDVERA_API_KEY"
# 1 · CREATE a session on every render of the payment page. Store "sid" on the
# order (overwrite) and put "scriptUrl" in the page. The same order gets the
# same session back until it's assessed, expires, or the cart changes. Leave
# "amount" out when the page doesn't know it yet (a donation or a tip).
curl -sS -m 3 -X POST "$API_HOST/api/sessions" -H "$AUTH" -H 'Content-Type: application/json' \
-d '{ "orderId":"ORD-1234", "amount":2599, "currency":"USD",
"flow":"full_checkout", "identity":"guest" }'
# 200 {"sid":"3f9a...","scriptUrl":"https://edge.cardvera.dev/v1/cv.js?sid=3f9a...","expiresAt":"..."}
# 2 · VERDICT after the page's assess(), before you charge. SID is the one on
# YOUR order record, never one from the browser. Charge only on 200 with
# "action":"allow". 202 = pending: ask again after Retry-After (1 s), up to
# 3 times, then decline. Anything else: decline.
curl -sS -m 3 -w ' %{http_code}\n' "$API_HOST/api/verdict/$SID" -H "$AUTH"
# 3 · REPORT - ONE delivery attempt. amount + currency = what the PSP charged;
# occurredAt = when the PSP event happened; outcomeId = the PSP's id for it.
# 202 = accepted. Your queue worker retries 429 (after Retry-After), 5xx and
# network errors.
curl -sS -m 5 -o /dev/null -w '%{http_code}\n' -X POST "$API_HOST/api/outcome" \
-H "$AUTH" -H 'Content-Type: application/json' -d @- <<JSON
{ "sessionId":"$SID","outcomeType":"auth","outcome":"approved",
"amount":2599,"currency":"USD",
"occurredAt":"2026-11-17T10:04:00Z","outcomeId":"psp_abc" }
JSON// cardvera.mjs — the server side of a Cardvera integration. Node 18+ (global fetch).
const API_HOST = "https://api.cardvera.dev";
const API_KEY = process.env.CARDVERA_API_KEY; // cv_ak_… from the Portal; server-side only
const headers = { authorization: `Bearer ${API_KEY}`, "content-type": "application/json" };
// 1 · CREATE — on every render of the payment page. Resolves { sid, scriptUrl, expiresAt }.
// Store sid on the order (overwrite) and put scriptUrl in the page's script tag.
// Throws on any failure: store no sid, render without the tag, and pay declines.
// amount: number | null, in minor units; null (or left out) when the page doesn't know it yet.
export async function createSession({ orderId, amount, currency, flow = "full_checkout",
identity = "guest", subject, shopperIp }) {
const body = { orderId, amount, currency, flow, identity };
if (subject) body.subject = subject;
if (shopperIp) body.shopperIp = shopperIp;
const res = await fetch(`${API_HOST}/api/sessions`, {
method: "POST", headers, body: JSON.stringify(body), signal: AbortSignal.timeout(3000),
}); // network errors and timeouts throw
if (res.status !== 200) throw apiError(res.status, await res.text(), res.headers.get("retry-after"));
return res.json();
}
// 2 · VERDICT — at pay, with the sid from YOUR order record (never the browser's).
// Resolves { allow: true, verdict } only for an allow. Otherwise { allow: false,
// reason }: the block reason, or why there's no verdict. Log the reason; decline.
export async function getVerdict(sid, retries = 3) {
for (let attempt = 0; ; attempt++) {
let res;
try {
res = await fetch(`${API_HOST}/api/verdict/${encodeURIComponent(sid)}`,
{ headers, signal: AbortSignal.timeout(3000) });
} catch { return { allow: false, reason: "unavailable" }; } // network error or timeout
const body = await res.json().catch(() => ({}));
if (res.status === 200) {
return body.action === "allow" ? { allow: true, reason: null, verdict: body }
: { allow: false, reason: body.reason ?? "block", verdict: body };
}
if (res.status === 202 && attempt < retries) { // pending: ask again shortly
const wait = Number(res.headers.get("retry-after") ?? 1);
await new Promise((r) => setTimeout(r, wait * 1000));
continue;
}
// 401 / 403 have no body: their reason is http_401 / http_403.
return { allow: false, reason: res.status === 202 ? "pending" : body.error ?? `http_${res.status}` };
}
}
// 3 · REPORT — ONE delivery attempt (the HTTP call only). Your queue worker owns
// retries; see "Report outcomes". occurredAt is when the PSP event happened and
// outcomeId is the PSP's id for it: keep both the same on every attempt.
// amount and currency are what was charged, refunded or disputed: always send them.
// Throws on failure: err.retryable is false for 400/401/403 (fix, don't retry),
// and err.retryAfter holds the seconds a 429 asked you to wait.
export async function reportOutcome({ sid, outcomeType, outcome, amount, currency, occurredAt, outcomeId }) {
const res = await fetch(`${API_HOST}/api/outcome`, {
method: "POST", headers,
body: JSON.stringify({ sessionId: sid, outcomeType, outcome, amount, currency, occurredAt, outcomeId }),
signal: AbortSignal.timeout(5000),
}); // network errors and timeouts throw: retry them
if (res.status === 202) return; // accepted (a duplicate is accepted too)
throw apiError(res.status, await res.text(), res.headers.get("retry-after"));
}
function apiError(status, body, retryAfter) {
const err = new Error(`cardvera ${status}: ${body}`);
err.status = status;
err.retryable = ![400, 401, 403].includes(status); // 4xx: fix, don't retry
err.retryAfter = Number(retryAfter) || undefined;
return err;
}# cardvera.py - the server side of a Cardvera integration. Standard library only.
import json, os, time, urllib.error, urllib.parse, urllib.request
from typing import Optional
API_HOST = "https://api.cardvera.dev"
API_KEY = os.environ["CARDVERA_API_KEY"] # cv_ak_... from the Portal; server-side only
class CardveraError(Exception):
"""A non-success answer. retryable is False for 400/401/403 (fix, don't retry)."""
def __init__(self, status, body, retry_after=None):
super().__init__(f"cardvera {status}: {body!r}")
self.status = status
self.retryable = status not in (400, 401, 403)
self.retry_after = int(retry_after) if (retry_after or "").isdigit() else None
def _call(method, path, body=None, timeout=3):
"""One request. Returns (status, headers, JSON body or {}). Network errors raise OSError."""
req = urllib.request.Request(API_HOST + path, method=method,
data=None if body is None else json.dumps(body).encode(),
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as res:
status, headers, raw = res.status, res.headers, res.read()
except urllib.error.HTTPError as e:
with e:
status, headers, raw = e.code, e.headers, e.read()
try:
data = json.loads(raw) if raw else {}
except ValueError:
data = {}
return status, headers, data
# 1 · CREATE - on every render of the payment page. Returns {"sid", "scriptUrl", "expiresAt"}.
# Store sid on the order (overwrite) and put scriptUrl in the page's script tag.
# Raises on any failure: store no sid, render without the tag, and pay declines.
# amount is in minor units, or None when the page doesn't know it yet.
def create_session(order_id, amount: Optional[int], currency, flow="full_checkout", identity="guest",
subject=None, shopper_ip=None):
body = {"orderId": order_id, "amount": amount, "currency": currency,
"flow": flow, "identity": identity}
if subject: body["subject"] = subject
if shopper_ip: body["shopperIp"] = shopper_ip
status, headers, data = _call("POST", "/api/sessions", body)
if status != 200:
raise CardveraError(status, data, headers.get("Retry-After"))
return data
# 2 · VERDICT - at pay, with the sid from YOUR order record (never the browser's).
# Returns (allow, reason, verdict). allow is True only for an allow; otherwise
# reason is the block reason, or why there's no verdict. Log it, then decline.
def get_verdict(sid, retries=3):
for attempt in range(retries + 1):
try:
status, headers, data = _call("GET", "/api/verdict/" + urllib.parse.quote(sid, safe=""))
except OSError:
return False, "unavailable", None # network error or timeout
if status == 200:
allow = data.get("action") == "allow"
return allow, None if allow else data.get("reason") or "block", data
if status == 202 and attempt < retries: # pending: ask again shortly
wait = headers.get("Retry-After") or "1"
time.sleep(int(wait) if wait.isdigit() else 1)
continue
# 401 / 403 have no body: their reason is http_401 / http_403.
return False, "pending" if status == 202 else data.get("error") or f"http_{status}", None
# 3 · REPORT - ONE delivery attempt (the HTTP call only). Your queue worker owns
# retries; see "Report outcomes". occurred_at is when the PSP event happened and
# outcome_id is the PSP's id for it: keep both the same on every attempt.
# amount and currency are what was charged, refunded or disputed: always send them.
# Raises CardveraError: .retryable is False for 400/401/403 (fix, don't retry),
# and .retry_after holds the seconds a 429 asked you to wait.
def report_outcome(sid, outcome_type, outcome, amount: int, currency, occurred_at, outcome_id=None):
body = {"sessionId": sid, "outcomeType": outcome_type, "outcome": outcome,
"amount": amount, "currency": currency, "occurredAt": occurred_at}
if outcome_id: body["outcomeId"] = outcome_id
status, headers, data = _call("POST", "/api/outcome", body, timeout=5)
if status != 202: # 202: accepted (duplicates too)
raise CardveraError(status, data, headers.get("Retry-After"))
# Network errors and timeouts raise OSError as they are: retry them.<?php
// cardvera.php — the server side of a Cardvera integration. ext-curl, PHP 8.1+.
const CV_API_HOST = 'https://api.cardvera.dev';
function cv_key(): string { return getenv('CARDVERA_API_KEY'); } // cv_ak_… from the Portal
// A non-success answer. retryable() is false for 400/401/403 (fix, don't retry).
class CvError extends \RuntimeException {
public function __construct(public int $status, public array $body, public ?int $retryAfter = null) {
parent::__construct("cardvera $status: " . json_encode($body));
}
public function retryable(): bool { return !in_array($this->status, [400, 401, 403], true); }
}
// One request: [status, decoded body, Retry-After seconds]. Status 0 = network error or timeout.
function cv_call(string $method, string $path, ?array $body = null, int $timeout = 3): array {
$retryAfter = null;
$c = curl_init(CV_API_HOST . $path);
curl_setopt_array($c, [CURLOPT_CUSTOMREQUEST => $method, CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => $timeout,
CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . cv_key(), 'Content-Type: application/json'],
CURLOPT_HEADERFUNCTION => function ($c, $h) use (&$retryAfter) {
if (preg_match('/^Retry-After:\s*(\d+)/i', $h, $m)) $retryAfter = (int) $m[1];
return strlen($h);
}]);
if ($body !== null) curl_setopt($c, CURLOPT_POSTFIELDS, json_encode($body));
$resp = curl_exec($c);
$status = $resp === false ? 0 : curl_getinfo($c, CURLINFO_RESPONSE_CODE);
curl_close($c);
return [$status, $resp ? (json_decode($resp, true) ?: []) : [], $retryAfter];
}
// 1 · CREATE — on every render of the payment page. Returns ['sid', 'scriptUrl', 'expiresAt'].
// Store sid on the order (overwrite) and put scriptUrl in the page's script tag.
// Throws CvError on any failure: store no sid, render without the tag, and pay declines.
// $amount is in minor units, or null when the page doesn't know it yet.
function cv_create_session(string $orderId, ?int $amount, string $currency,
string $flow = 'full_checkout', string $identity = 'guest',
?string $subject = null, ?string $shopperIp = null): array {
$body = ['orderId' => $orderId, 'amount' => $amount, 'currency' => $currency,
'flow' => $flow, 'identity' => $identity];
if ($subject !== null) $body['subject'] = $subject;
if ($shopperIp !== null) $body['shopperIp'] = $shopperIp;
[$status, $data, $retryAfter] = cv_call('POST', '/api/sessions', $body);
if ($status !== 200) throw new CvError($status, $data, $retryAfter);
return $data;
}
// 2 · VERDICT — at pay, with the sid from YOUR order record (never the browser's).
// Returns [allow, reason, verdict]. allow is true only for an allow; otherwise
// reason is the block reason, or why there's no verdict. Log it, then decline.
function cv_get_verdict(string $sid, int $retries = 3): array {
for ($attempt = 0; ; $attempt++) {
[$status, $data, $retryAfter] = cv_call('GET', '/api/verdict/' . rawurlencode($sid));
if ($status === 200) {
$allow = ($data['action'] ?? null) === 'allow';
return [$allow, $allow ? null : ($data['reason'] ?? 'block'), $data];
}
if ($status === 202 && $attempt < $retries) { sleep($retryAfter ?? 1); continue; } // pending
$reason = match (true) {
$status === 0 => 'unavailable', // network error or timeout
$status === 202 => 'pending',
default => $data['error'] ?? "http_$status", // 401 / 403: no body, so http_401 / http_403
};
return [false, $reason, null];
}
}
// 3 · REPORT — ONE delivery attempt (the HTTP call only). Your queue worker owns
// retries; see "Report outcomes". $occurredAt is when the PSP event happened and
// $outcomeId is the PSP's id for it: keep both the same on every attempt.
// $amount and $currency are what was charged, refunded or disputed: always send them.
// Throws CvError: retryable() is false for 400/401/403 (fix, don't retry), and
// $retryAfter holds the seconds a 429 asked you to wait.
function cv_report(string $sid, string $type, string $outcome, int $amount, string $currency,
string $occurredAt, ?string $outcomeId = null): void {
$body = ['sessionId' => $sid, 'outcomeType' => $type, 'outcome' => $outcome,
'amount' => $amount, 'currency' => $currency, 'occurredAt' => $occurredAt];
if ($outcomeId !== null) $body['outcomeId'] = $outcomeId;
[$status, $data, $retryAfter] = cv_call('POST', '/api/outcome', $body, 5);
if ($status === 0) throw new CvError(0, ['error' => 'network']); // retry it
if ($status !== 202) throw new CvError($status, $data, $retryAfter); // 202: accepted (duplicates too)
}// Package cardvera is the server side of a Cardvera integration. Go 1.21+.
package cardvera
import ( "bytes"; "encoding/json"; "fmt"; "io"; "net/http"; "net/url"; "os"; "strconv"; "time" )
var apiHost = "https://api.cardvera.dev"
var httpClient = &http.Client{Timeout: 3 * time.Second} // outcomes may use 5 s
// APIError is a non-success answer. Retryable() is false for 400/401/403 (fix, don't retry).
type APIError struct { Status int; Code string; RetryAfter time.Duration }
func (e *APIError) Error() string { return fmt.Sprintf("cardvera %d: %s", e.Status, e.Code) }
func (e *APIError) Retryable() bool { return e.Status != 400 && e.Status != 401 && e.Status != 403 }
// call makes one request with the API key. A network error or timeout returns err.
func call(method, path string, body any) (*http.Response, []byte, error) {
var rd io.Reader
if body != nil { b, _ := json.Marshal(body); rd = bytes.NewReader(b) }
req, _ := http.NewRequest(method, apiHost+path, rd)
req.Header.Set("Authorization", "Bearer "+os.Getenv("CARDVERA_API_KEY")) // cv_ak_… from the Portal
req.Header.Set("Content-Type", "application/json")
res, err := httpClient.Do(req)
if err != nil { return nil, nil, err }
defer res.Body.Close()
raw, err := io.ReadAll(res.Body)
return res, raw, err
}
func apiError(res *http.Response, raw []byte) *APIError {
var e struct{ Error string `json:"error"` }
json.Unmarshal(raw, &e)
wait, _ := strconv.Atoi(res.Header.Get("Retry-After"))
return &APIError{res.StatusCode, e.Error, time.Duration(wait) * time.Second}
}
type SessionRequest struct {
OrderID string `json:"orderId"`
Amount *int64 `json:"amount"` // minor units; nil (sent as null) when not known yet
Currency string `json:"currency"`
Flow string `json:"flow"` // e.g. "full_checkout"
Identity string `json:"identity"` // e.g. "guest"
Subject string `json:"subject,omitempty"`
ShopperIP string `json:"shopperIp,omitempty"`
}
type Session struct {
Sid string `json:"sid"`
ScriptURL string `json:"scriptUrl"`
ExpiresAt string `json:"expiresAt"`
}
// 1 · CREATE — on every render of the payment page. Store Sid on the order (overwrite)
// and put ScriptURL in the page's script tag. Any error: store no sid, render without
// the tag, and pay declines.
func CreateSession(r SessionRequest) (*Session, error) {
res, raw, err := call("POST", "/api/sessions", r)
if err != nil { return nil, err } // network error or timeout
if res.StatusCode != http.StatusOK { return nil, apiError(res, raw) }
var s Session
if err := json.Unmarshal(raw, &s); err != nil { return nil, err }
return &s, nil
}
type Verdict struct {
Sid string `json:"sid"`
Txn string `json:"txn"`
Action string `json:"action"` // "allow" | "block"
Reason *string `json:"reason"` // null on an allow
StepUp *struct{ Reason, Result string } `json:"stepUp"`
Score *float64 `json:"score"`
Agent *struct{ Operator, Tier, Tag string } `json:"agent"`
DecidedAt string `json:"decidedAt"`
}
// 2 · VERDICT — at pay, with the sid from YOUR order record (never the browser's).
// allow is true only for an allow; otherwise reason is the block reason, or why
// there's no verdict. Log it, then decline.
func GetVerdict(sid string) (allow bool, reason string, v *Verdict) {
for attempt := 0; ; attempt++ {
res, raw, err := call("GET", "/api/verdict/"+url.PathEscape(sid), nil)
if err != nil { return false, "unavailable", nil } // network error or timeout
switch {
case res.StatusCode == http.StatusOK:
v = &Verdict{}
if json.Unmarshal(raw, v) != nil { return false, "unavailable", nil }
if v.Action == "allow" { return true, "", v }
if v.Reason != nil { return false, *v.Reason, v }
return false, "block", v
case res.StatusCode == http.StatusAccepted && attempt < 3: // pending: ask again shortly
wait, err := strconv.Atoi(res.Header.Get("Retry-After"))
if err != nil { wait = 1 }
time.Sleep(time.Duration(wait) * time.Second)
case res.StatusCode == http.StatusAccepted:
return false, "pending", nil
default:
if e := apiError(res, raw); e.Code != "" { return false, e.Code, nil }
return false, fmt.Sprintf("http_%d", res.StatusCode), nil // 401 / 403 have no body
}
}
}
// 3 · REPORT — ONE delivery attempt (the HTTP call only). Your queue worker owns
// retries; see "Report outcomes". occurredAt is when the PSP event happened and
// outcomeID is the PSP's id for it: keep both the same on every attempt.
// amount and currency are what was charged, refunded or disputed: always send them.
// A non-202 returns *APIError: Retryable() is false for 400/401/403 (fix, don't
// retry), and RetryAfter holds the wait a 429 asked for.
func ReportOutcome(sid, outcomeType, outcome string, amount int64, currency string,
occurredAt time.Time, outcomeID string) error {
b := map[string]any{ "sessionId": sid, "outcomeType": outcomeType, "outcome": outcome,
"amount": amount, "currency": currency, "occurredAt": occurredAt.UTC().Format(time.RFC3339) }
if outcomeID != "" { b["outcomeId"] = outcomeID }
res, raw, err := call("POST", "/api/outcome", b)
if err != nil { return err } // network error or timeout: retry it
if res.StatusCode == http.StatusAccepted { return nil } // accepted (duplicates too)
return apiError(res, raw)
}// Cardvera.cs — the server side of a Cardvera integration. .NET 8+, no packages.
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
public static class Cardvera {
public static string ApiHost { get; set; } = "https://api.cardvera.dev";
static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(3) };
static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web) {
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull };
static HttpRequestMessage Request(HttpMethod method, string path, object? body = null) {
var req = new HttpRequestMessage(method, ApiHost + path);
req.Headers.Authorization = new AuthenticationHeaderValue("Bearer",
Environment.GetEnvironmentVariable("CARDVERA_API_KEY")); // cv_ak_… from the Portal
if (body is not null) req.Content = JsonContent.Create(body, options: Json);
return req;
}
// A non-success answer. Retryable is false for 400/401/403: fix, don't retry.
public class CardveraException(HttpStatusCode status, string? code, TimeSpan? retryAfter)
: Exception($"cardvera {(int)status}: {code}") {
public HttpStatusCode Status => status;
public string? Code => code;
public bool Retryable => status is not (HttpStatusCode.BadRequest or HttpStatusCode.Unauthorized
or HttpStatusCode.Forbidden);
public TimeSpan? RetryAfter => retryAfter;
}
static async Task<CardveraException> Error(HttpResponseMessage res) {
string? code = null;
try { code = (await res.Content.ReadFromJsonAsync<JsonElement>()).GetProperty("error").GetString(); }
catch { } // empty or non-JSON body
return new CardveraException(res.StatusCode, code, res.Headers.RetryAfter?.Delta);
}
// Amount is in minor units, or null (left out of the body) when the page doesn't know it yet.
public record SessionRequest(string OrderId, long? Amount, string Currency,
string Flow = "full_checkout", string Identity = "guest",
string? Subject = null, string? ShopperIp = null);
public record Session(string Sid, string ScriptUrl, DateTimeOffset ExpiresAt);
// 1 · CREATE — on every render of the payment page. Store Sid on the order (overwrite)
// and put ScriptUrl in the page's script tag. Throws on any failure: store no sid,
// render without the tag, and pay declines.
public static async Task<Session> CreateSession(SessionRequest r) {
using var res = await Http.SendAsync(Request(HttpMethod.Post, "/api/sessions", r));
if (res.StatusCode != HttpStatusCode.OK) throw await Error(res);
return (await res.Content.ReadFromJsonAsync<Session>(Json))!;
}
public record VerdictStepUp(string Reason, string Result);
public record VerdictAgent(string Operator, string Tier, string Tag);
public record Verdict(string Sid, string Txn, string Action, string? Reason, VerdictStepUp? StepUp,
double? Score, VerdictAgent? Agent, DateTimeOffset DecidedAt);
// 2 · VERDICT — at pay, with the sid from YOUR order record (never the browser's).
// Allow is true only for an allow; otherwise Reason is the block reason, or why
// there's no verdict. Log it, then decline.
public static async Task<(bool Allow, string? Reason, Verdict? Verdict)> GetVerdict(
string sid, int retries = 3) {
for (var attempt = 0; ; attempt++) {
HttpResponseMessage res;
try { res = await Http.SendAsync(Request(HttpMethod.Get, $"/api/verdict/{Uri.EscapeDataString(sid)}")); }
catch (Exception e) when (e is HttpRequestException or TaskCanceledException) {
return (false, "unavailable", null); // network error or timeout
}
using (res) {
if (res.StatusCode == HttpStatusCode.OK) {
var v = await res.Content.ReadFromJsonAsync<Verdict>(Json);
return v?.Action == "allow" ? (true, null, v) : (false, v?.Reason ?? "block", v);
}
if (res.StatusCode == HttpStatusCode.Accepted && attempt < retries) { // pending
await Task.Delay(res.Headers.RetryAfter?.Delta ?? TimeSpan.FromSeconds(1));
continue;
}
if (res.StatusCode == HttpStatusCode.Accepted) return (false, "pending", null);
var err = await Error(res);
return (false, err.Code ?? $"http_{(int)res.StatusCode}", null); // 401 / 403: no body
}
}
}
// 3 · REPORT — ONE delivery attempt (the HTTP call only). Your queue worker owns
// retries; see "Report outcomes" and the ASP.NET Core guide. occurredAt is when
// the PSP event happened and outcomeId is the PSP's id for it: keep both the
// same on every attempt. amount and currency are what was charged, refunded or
// disputed: always send them. A non-202 throws CardveraException: Retryable is false
// for 400/401/403 (fix, don't retry), and RetryAfter holds the wait a 429 asked for.
public static async Task ReportOutcome(string sid, string type, string outcome,
long amount, string currency, DateTimeOffset occurredAt, string? outcomeId = null) {
var body = new { sessionId = sid, outcomeType = type, outcome, amount, currency,
occurredAt = occurredAt.UtcDateTime.ToString("yyyy-MM-ddTHH:mm:ssZ"), outcomeId };
using var res = await Http.SendAsync(Request(HttpMethod.Post, "/api/outcome", body));
if (res.StatusCode == HttpStatusCode.Accepted) return; // accepted (duplicates too)
throw await Error(res); // network errors and timeouts throw: retry them
}
}Test your integration
Cardvera's decision reaches your server as one API answer, so the part of your code that matters is small: charge on an allow, decline on everything else. Test that offline against canned answers, then prove the wiring once against Cardvera.
Credentials
Create a separate API key for testing, with the three scopes and your staging servers' egress IPs on its allowlist. There are no separate test keys and no values that force a decision: test traffic is scored like any other. Give test orders a recognisable orderId, such as TEST-1042.
approved or declined_technical. A declined_fraud or a chargeback reported for test traffic can get your own test devices blocked.Deterministic tests
Run these in CI. Point the Quickstart module's API host at a local stub that answers each canned response in this section, and assert that only the allow charges and that every other answer declines with its reason. They don't call Cardvera, so the results never vary. The Python sample does this; the same table applies in any language.
Live smoke test
About fifteen minutes with the Quickstart module in your language. It proves the wiring end to end. Live traffic is scored for real, so a correct integration can get either allow or block: the test passes on any verdict, never on a particular action.
- Create. Call
createSessionfor a test order. Expect:200with asid, ascriptUrland anexpiresAt. Call it again with the same body. Expect: the samesid. - Load. Put the
scriptUrltag in the<head>of a test page. Any origin works, includinglocalhost. Expect:typeof Cardvera.assessin the browser console is"function", andawait Cardvera.ready()showsreachable: true. - Assess. Use the page like a shopper for a few seconds (move, click, type), then run
await Cardvera.assess()in the console. Expect: it resolves toundefined. That's the same for allow and block; a rejected promise has acodethat says what went wrong. - Verdict. Call
getVerdictwith thesidfrom step 1. Expect:200withaction"allow"or"block". Either passes.not_found,401or403means a bug or a setting to fix. - Replay. Run
await Cardvera.assess()again on the same page. Expect: it rejects withcode"session_used", and the verdict from step 4 doesn't change. - Report. Send an
approvedoutcome for thesid, with the amount and currency charged and anoutcomeId. Expect:202. Send the same body again. Expect:202; Cardvera stores it once. - Expire (optional). Create a session for another test order and wait 20 minutes before loading its page. Expect: the page logs
cardvera: This page's Cardvera session has expired…,assess()rejects withsession_expired, and the verdict is410 session_expired.
allow from live scoring. Judge the integration by the verdict read: a 200 with allow or block means it works.A 202 from /api/outcome means Cardvera accepted the request. It doesn't confirm that the outcome matched an existing session, so send the sid from your own record.
Scenarios to cover
| Scenario | How to produce it | Expected |
|---|---|---|
| Every verdict answer | Canned stub responses, in CI. | Only the allow charges. Every other answer declines with its reason. |
| The same order rendered twice | Reload the payment page before paying. | The same sid and scriptUrl; one session. |
| The cart changes | Render again with a different amount. | A new sid. Your record now holds the new one. |
| An open amount | Create without amount and render twice, then pay and report the amount charged. | The same sid both times; the outcome is 202. |
| A second assessment | Call assess() twice on one page load. | The second rejects with session_used; the page reloads. |
| Expired before load | Load a scriptUrl more than 20 minutes after creating it. | The stand-in script; assess() rejects with session_expired; verdict 410 session_expired. |
| Expired during checkout | Load the page, wait 30 minutes, then pay. | assess() rejects with session_expired; the page reloads and gets a new session. |
| Loaded, never assessed | Load the page and leave it. | Verdict 202 while it could still be assessed, then 410 never_assessed. |
A bad scriptUrl | Change a character of the sid in the tag. | The stand-in script; assess() rejects with session_unknown. Your server declines. |
| Key and allowlist errors | Revoke the test key; call from an IP not on the list; use a key without verdicts:read. | 401 (within 5 minutes of the revoke); 403, with your IP as the key's Last denied in the Portal; 403. No body on any of them. Your server declines and alerts. |
| SDK can't load | In DevTools → Network, block the domain edge.cardvera.dev, or ship a CSP without it. | The page submits once its wait runs out; the verdict stays pending; your server declines, or applies your emergency switch if it's on. |
| Cardvera unreachable at submit | Load the page, then block the request URL */v1/assess. | assess() rejects with unreachable after its retries. The page submits; your server declines. |
| Assessment hangs | Load the page, then switch DevTools throttling to a custom profile with 20 s latency. | Your 10-second timeout fires. The page submits; your server declines. |
| Double submit | Double-click Pay, or replay the form POST. | One assess(), one charge. The replayed POST finds the first payment attempt. |
| Outcome errors | Send an unknown outcome; leave out amount; use a key without outcomes:write. | 400 invalid_outcome; 400 invalid_amount; 403. Your sender retries none of them. |
| Outcome outage | Point your sender at an unreachable host. | Retries with backoff, then alerts. Checkout is unaffected. |
Step-ups need no test of their own. The SDK solves them before assess() resolves, and the verdict your server reads is already final.
# What your pay step must do with each answer from GET /api/verdict/{sid}.
200 {"action":"allow","reason":null,...} -> charge
200 {"action":"block","reason":"velocity",...} -> decline (reason: velocity)
202 {"status":"pending","retryAfterSeconds":1} -> ask again; still 202 after 3 tries: decline
410 {"error":"session_expired"} -> decline
410 {"error":"never_assessed"} -> decline
404 {"error":"not_found"} -> decline (check the sid you store)
401 (no body) -> decline, alert
403 (no body) -> decline, alert
503 {"error":"storage_unavailable"} -> decline (or your emergency switch)
no answer within 3 s -> decline (or your emergency switch)# test_cardvera.py - your verdict handling against canned API answers. No Cardvera call.
import json, os, threading, unittest
from http.server import BaseHTTPRequestHandler, HTTPServer
os.environ.setdefault("CARDVERA_API_KEY", "stub-accepts-any-key")
import cardvera # the Quickstart module
VERDICT = {"txn": "ORD-1", "stepUp": None, "score": 0.9, "agent": None, "decidedAt": "2026-11-17T10:03:58Z"}
CANNED = { # sid -> (status, body): one sid per scenario
"allow": (200, {**VERDICT, "sid": "allow", "action": "allow", "reason": None}),
"block": (200, {**VERDICT, "sid": "block", "action": "block", "reason": "velocity"}),
"pending": (202, {"status": "pending", "retryAfterSeconds": 1}),
"expired": (410, {"error": "session_expired"}),
"never": (410, {"error": "never_assessed"}),
"unknown": (404, {"error": "not_found"}),
"badkey": (401, None), # 401 / 403: status only, no body
"denied": (403, None),
"down": (503, {"error": "storage_unavailable"}),
}
EXPECTED = {"allow": (True, None), "block": (False, "velocity"), "pending": (False, "pending"),
"expired": (False, "session_expired"), "never": (False, "never_assessed"),
"unknown": (False, "not_found"), "badkey": (False, "http_401"),
"denied": (False, "http_403"), "down": (False, "storage_unavailable")}
class Stub(BaseHTTPRequestHandler):
def do_GET(self):
status, body = CANNED[self.path.rsplit("/", 1)[1]]
data = b"" if body is None else json.dumps(body).encode()
self.send_response(status)
if status == 202:
self.send_header("Retry-After", "0") # the API says 1; 0 keeps the test fast
if data:
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
def log_message(self, *args):
pass
class VerdictHandlingTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.server = HTTPServer(("127.0.0.1", 0), Stub)
threading.Thread(target=cls.server.serve_forever, daemon=True).start()
cls.real_host, cardvera.API_HOST = cardvera.API_HOST, f"http://127.0.0.1:{cls.server.server_port}"
@classmethod
def tearDownClass(cls):
cls.server.shutdown()
cls.server.server_close()
cardvera.API_HOST = cls.real_host
def test_only_an_allow_charges(self):
for sid, want in EXPECTED.items():
with self.subTest(sid):
allow, reason, _ = cardvera.get_verdict(sid)
self.assertEqual((allow, reason), want)
def test_no_answer_declines(self):
stub, cardvera.API_HOST = cardvera.API_HOST, "http://127.0.0.1:9" # nothing listens there
try:
self.assertEqual(cardvera.get_verdict("allow")[:2], (False, "unavailable"))
finally:
cardvera.API_HOST = stub
if __name__ == "__main__":
unittest.main()# A test key: scopes sessions:write, verdicts:read, outcomes:write; allowlist = your egress IP.
AUTH="Authorization: Bearer $CARDVERA_API_KEY"; API="https://api.cardvera.dev"
BODY='{"orderId":"TEST-1042","amount":100,"currency":"USD","flow":"full_checkout","identity":"guest"}'
curl -sS -X POST "$API/api/sessions" -H "$AUTH" -H 'Content-Type: application/json' -d "$BODY"
# 200 {"sid":"…","scriptUrl":"…","expiresAt":"…"} run it again: the same sid
curl -s -o /dev/null -w '%{http_code}\n' "$SCRIPT_URL" # 200 (the SDK)
curl -sS -w ' %{http_code}\n' "$API/api/verdict/$SID" -H "$AUTH"
# before assess(): {"status":"pending","retryAfterSeconds":1} 202
# after assess(): {"sid":"…","action":"allow" or "block",…} 200Session context
When your server creates a session, it tells Cardvera what this checkout is: which order, how much, which kind of payment page, and whether the shopper is signed in. Cardvera keeps that copy and reads only it for every decision. It goes server to server, so the browser never sees or carries it. The fields and their rules are in Create a session.
Choosing a flow
Send the profile that matches the page the shopper is on. The single most common mistake is defaulting everything to full_checkout: a bare donation form scored as if it were a full checkout is the classic false positive.
| flow | Send it when |
|---|---|
full_checkout | A standard multi-field cart: name, address, card. Meaningful dwell and interaction. The default for normal e-commerce. |
express_checkout | A shortened, returning-customer path: wallet, saved card, one-tap (Apple Pay, Shop Pay). Less on-page interaction is expected and normal. |
minimal_payment | A small form with little behavioural surface: a "pay this invoice" link, an amount and a card field, not much else. |
donation | Often guest-accessible, a fixed or chosen amount, low navigation depth. Land, pick an amount, give. |
The flow sets the behavioural baseline (a donation page legitimately produces little mouse and keyboard evidence) and keeps detection cohorts apart, so a card-testing spike on your donation page is caught on its own baseline. An unknown flow is rejected; it never falls back to the most permissive profile.
Choosing an identity
State what is true about the shopper's session with you. identity selects which population the session is judged against; it is not a trust dial.
| identity | Send it when |
|---|---|
guest | No account, or not signed in for this purchase. Send no subject. |
authenticated_new | Signed in, but without earned history: a fresh account, or one that doesn't yet meet your "established" bar. Send a subject. |
authenticated_established | A signed-in account that meets criteria you define, such as N prior settled orders or an account-age threshold. Send a subject. |
Guest sessions are judged separately from signed-in ones, so guest card testing never borrows credibility from your customers. authenticated_established doesn't, by itself, relax any control: send it because it's accurate.
Deriving subject
For a signed-in customer, send a pseudonymous subject id: an HMAC of your immutable internal customer id under a dedicated key that you generate and keep, such as subject = hex(HMAC-SHA256(subjectKey, "subject:v1:" + internalCustomerId)). It's stable for that customer at your store, different at every other merchant, and not reversible by Cardvera. It enables account-level protection that survives IP and device rotation. Never send a raw id or an unsalted hash of an email.
What you never send
Card number, CVV, cardholder name, raw email or phone, addresses, raw customer ids. shopperIp is optional: the shopper's IP as your server saw it, used as a signal only.
Session lifecycle
A Cardvera session is one assessment of one order's checkout. Four rules cover almost every case:
- Ask on every render, store what you get. Call
POST /api/sessionseach time you render the payment page, and store the returnedsidon the order, overwriting the previous one. The same order gets the same session back while it's unused and valid and the cart (amount,currency,flow,identity,subject) is unchanged; otherwise you get a newsid. - Load within 20 minutes. A session that no page loads within 20 minutes of being created expires.
- Assess within 30 minutes of the first load. Reloads attach to the same session without restarting its clock.
expiresAtin each response is when the current window ends;cardvera:expiringfires five minutes before it. - One session, one assessment. The first
assess()uses the session up; a second rejects withsession_used. To try again, reload the page: your render gets a new session.
| Situation | What to do |
|---|---|
| The shopper reloads, or your page renders twice | Nothing. The same session comes back, and the SDK carries on with it. |
| Multi-page checkout (cart, shipping, payment) | Put the tag on every page of the flow, from a POST /api/sessions on each render. While the cart is unchanged they share one session, and its 30 minutes run from the first page that loaded it. Read the verdict for the sid you stored last. |
| Single-page app | Load the SDK once per document, and keep that session while the shopper moves between steps. Don't insert cv.js a second time: the second copy throws, and the first stays in charge. See React / Next.js. |
| The cart changes on the page, without a render | Nothing. Charge the amount on your own order record, never one the browser sends, and report that amount on the outcome. Your next render sends the new amount and gets a new session. |
| The amount is only known on the page (a donation, a tip, pay what you want) | Create the session without amount, and report the amount charged on the outcome (see Open amounts). |
| The order id changes | Create a session for the new order and store its sid on it. |
| The PSP declines and the shopper tries again | Report the decline for the current sid, then reload checkout. The used session is replaced by a new one automatically. |
| Double click, or the form posts twice | Call assess() once per page load, and let only one request per sid go on to charge (see Read the verdict). |
| Two tabs on the same order | They share the order's session. The first to pay uses it; the other gets session_used and reloads into a new one. |
| The shopper leaves and comes back | Nothing to clean up. A return within the window gets the same session back; later, a new one. |
| Checkout left open for 30 minutes | Reload on cardvera:expiring, or when assess() rejects with session_expired. |
Only a session you sent to your PSP has an outcome. A blocked or abandoned session needs no report.
Create a session
POST https://api.cardvera.dev/api/sessions, scope sessions:write. Call it from your server when you render the payment page. It answers 200 both for a new session and for the order's existing one.
Body
| Field | Req | |
|---|---|---|
orderId | yes | Your order id, 1–200 characters, no control characters. It comes back as txn in the verdict. |
amount | no | Integer in the currency's smallest unit: 31104 = $311.04 (USD, 2 digits), 1000 = ¥1000 (JPY, 0 digits), 5000 = 5.000 KWD (3 digits). Never a decimal or a string. Leave it out, or send null, when the page doesn't know the amount yet (see Open amounts). |
currency | yes | ISO-4217, upper-case, such as USD. Required even without an amount. |
flow | yes | full_checkout · express_checkout · minimal_payment · donation |
identity | yes | guest · authenticated_new · authenticated_established |
subject | no | Pseudonymous customer id, 1–128 characters (see Session context). Omit for guests. |
shopperIp | no | The shopper's IPv4 or IPv6 address, as your server saw it. A signal only. |
Unknown fields are rejected. The first field that fails is named: 400 { "error": "invalid_field", "field": "currency" }. A body that isn't a JSON object is 400 invalid_json.
Open amounts (donations, tips, pay what you want)
When the shopper chooses the amount on the page, create the session without amount, then report the amount you charged on the outcome. 0 is only for a real $0 authorization: never send 0 or a guess as a stand-in.
Response
| Field | |
|---|---|
sid | The session id: 32 lower-case hex characters. Store it on the order; your server reads the verdict and reports outcomes with it. |
scriptUrl | The SDK URL for this session. Put it in the page's script tag exactly as returned. |
expiresAt | When the session's current window ends (ISO-8601, UTC): 20 minutes after creation until a page loads it, then 30 minutes after that first load. |
Repeat calls
Calls are idempotent per order: while the order's session is unused and valid and the cart is the same, every call returns that session, so ten calls make one session. A new sid comes back when the session has been assessed, has expired, or the call sends a different amount, currency, flow, identity or subject. A different shopperIp doesn't count, and a missing amount is the same as null. Always store the sid from the latest response.
Rate limit
50 requests per second per API key. Over it: 429 { "error": "rate_limited", "retryAfterSeconds": 1 } with a Retry-After header.
$CARDVERA_API_KEY.curl -sS -m 3 -X POST https://api.cardvera.dev/api/sessions \
-H "Authorization: Bearer $CARDVERA_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"orderId": "ORD-1234",
"amount": 2599,
"currency": "USD",
"flow": "full_checkout",
"identity": "guest",
"shopperIp": "34.120.10.7"
}'
200 {"sid":"…","scriptUrl":"…","expiresAt":"…"} -> new or returned session
400 { "error": "invalid_field", "field": "currency" }
429 { "error": "rate_limited", "retryAfterSeconds": 1 }{
"sid": "3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f",
"scriptUrl": "https://edge.cardvera.dev/v1/cv.js?sid=3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f",
"expiresAt": "2026-11-17T10:20:00Z"
}The SDK & assess()
GET scriptUrl (https://edge.cardvera.dev/v1/cv.js?sid=…) returns the Cardvera SDK as JavaScript. Put it in a <script> tag in the <head> of the payment page, and of every page in the checkout flow, so the SDK has the whole visit to collect. It starts collecting and solving a small proof of work as soon as it runs.
The script tag
| Attribute | |
|---|---|
async | Downloads without blocking the page and runs as soon as it arrives, so the SDK starts work early. defer also works, but runs later. |
crossorigin="anonymous" | Loads the script without cookies, the same way the SDK makes its own calls. The browser can then reuse that connection for assess() instead of opening a new one when the shopper clicks pay. Without it everything still works, just a little slower at checkout. |
Use scriptUrl exactly as returned. It's served no-store; don't cache, bundle, self-host or proxy it, and don't cache a page that carries it (see Cached & headless pages). Load it once per page, as a classic script, not type="module": a second copy on the same page throws and doesn't replace the first.
Content Security Policy
If your checkout sets a CSP, allow https://edge.cardvera.dev in both script-src (to load the SDK) and connect-src (the SDK calls back to the domain it was loaded from), and blob: in worker-src (the SDK runs its device check in a background worker). Without worker-src blob:, Cardvera blocks the checkout.
Console messages
Every line the SDK writes to the console starts with cardvera:. cardvera: automation check (expected) appears on every page and needs nothing from you. If something was blocked, a warning names it and says what to change, for example a CSP directive.
Cardvera.assess()
Call it when the shopper submits. It resolves with nothing (undefined) once Cardvera has the assessment, and then your page submits. Allow and block look the same here: your server reads the verdict. Any step-up is solved inside the SDK before the promise settles.
It rejects with an Error whose code says why:
| code | Meaning | The page |
|---|---|---|
unreachable | No answer from Cardvera after the SDK's retries: network, CSP, an extension. | Submits. Your server declines. |
session_expired | The session's time ran out before or during checkout. | Reloads for a new session. |
session_used | This session was already assessed. | Reloads for a new session. |
session_unknown | Cardvera doesn't know this page's session. Usually the page's script URL isn't a scriptUrl from POST /api/sessions (edited, truncated, or from another environment); also a page that is hours old (cached, or left open). | Submits. Your server declines; the shopper's retry reloads the checkout. If it's frequent, look for the bug or a cached page. |
assess_failed | Any other failure. | Submits. Your server declines. |
- Call it once per page load. While a call is pending, or after one resolved, another call rejects with
session_used. Guard against double clicks. Afterunreachableorassess_faileda call may be made again. - It has no timeout of its own. Race it against yours; 10 seconds suits most checkouts. See Failure handling.
- Submit whatever happens, except for the two codes that call for a reload. Your server decides; the page only waits for the assessment.
Knowing when the SDK is ready
window.Cardvera exists as soon as cv.js has run, and assess() waits for its own background work, so you can call it any time after that. To know it can also reach Cardvera, listen for cardvera:ready (see Events). If the script fails to load (offline, blocked, a CSP that doesn't allow edge.cardvera.dev), window.Cardvera never appears and no event fires.
- Tag in the
<head>: at submit, wait briefly forwindow.Cardvera, as the client example does. - Inserted from JavaScript (single-page apps, cached pages): create the script element yourself, and use its
loadanderrorevents. See React / Next.js.
Session errors and the stand-in script
When a scriptUrl's session is expired, used or unknown, cv.js still answers 200, with a small stand-in script instead of the SDK. It defines window.Cardvera, fires cardvera:error once with the session code, logs one cardvera: warning, and its assess() rejects with the same code. It collects nothing and makes no requests, so your page's error handling runs the same way it does for the real SDK.
Events
The SDK fires these on window. The tag is async, so add your listeners before it. None carries the verdict: that's for your server.
| Event | detail | When |
|---|---|---|
cardvera:ready | { reachable, version } | Once per page load. reachable is false when assess() can't reach Cardvera from this page: a CSP without connect-src, an extension or the network. Cardvera.ready() returns the same detail, even after the event has fired. |
cardvera:error | { code, message } | Something will stop or spoil this checkout. code is unreachable, csp (your CSP blocked a request to Cardvera), device_check (your CSP blocked the SDK's worker; add worker-src blob:), assess_failed (assess() rejected), or, from the stand-in, session_expired, session_used or session_unknown. message matches the console line. Log it, and alert on a rise. |
cardvera:expiring | { expiresAt } | Five minutes before this page's session expires, unless it has already been assessed. Reload the page before checkout. |
TypeScript
Declarations for window.Cardvera are in this section, and served at types/cardvera.d.ts. Copy the file into your project.
Why there's no SRI hash
Subresource Integrity (integrity="sha384-…") makes the browser refuse a script whose bytes don't match a hash in the tag. That only works for a file that never changes. cv.js carries each session's own challenge and settings, and Cardvera updates the SDK without you changing your tag, so a fixed hash would block it on every load and your fraud screening would silently stop. What protects it instead: it's served only over HTTPS from Cardvera's edge network at edge.cardvera.dev, only for a session your server created, and you can restrict it with the CSP above. For a PCI DSS 4.0 requirement 6.4.3 script inventory, list cv.js from https://edge.cardvera.dev as authorized, with its purpose: fraud screening. crossorigin="anonymous" is not SRI; it's there only for connection reuse.
assess() or the page, so nothing from the browser counts. Your server charges only on the verdict it reads from the API.<!doctype html>
<html>
<head>
<meta charset="utf-8">
<!-- scriptUrl from POST /api/sessions for this order (see Quickstart) -->
<script src="https://edge.cardvera.dev/v1/cv.js?sid=3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f" async crossorigin="anonymous"></script>
</head>
<body>
<form id="checkout" method="post" action="/checkout/ORD-1234/pay">
<!-- your payment fields, e.g. your PSP's card element -->
<button type="submit">Pay</button>
</form>
<script>
const form = document.getElementById('checkout');
let submitted = false;
form.addEventListener('submit', async (e) => {
e.preventDefault();
if (submitted) return; // one assess() per page load
submitted = true;
form.querySelector('button').disabled = true;
if (await cardveraAssess(10000) === 'reload') {
location.reload(); // expired or used: a fresh page gets a fresh session
return;
}
form.submit(); // your server reads the verdict, then charges or declines
});
// 'done', 'reload' or 'failed'. Never rejects: your server reads the verdict either way.
async function cardveraAssess(ms) {
try {
const until = Date.now() + ms;
while (!window.Cardvera) { // the async tag may still be loading
if (Date.now() > until) return 'failed'; // never loaded: offline, blocked, CSP
await new Promise((r) => setTimeout(r, 50));
}
const timeout = new Promise((_, fail) =>
setTimeout(() => fail(new Error('timeout')), ms));
await Promise.race([window.Cardvera.assess(), timeout]);
return 'done';
} catch (err) {
return err.code === 'session_expired' || err.code === 'session_used' ? 'reload' : 'failed';
}
}
</script>
</body>
</html>// Type declarations for the Cardvera browser SDK (window.Cardvera).
// https://docs.cardvera.io/types/cardvera.d.ts - copy into your project, e.g. src/types/cardvera.d.ts.
export {};
declare global {
/** Codes on the cardvera:error event. More may be added. */
type CardveraErrorCode =
| "unreachable" | "csp" | "device_check" | "assess_failed"
| "session_expired" | "session_unknown" | "session_used" | (string & {});
/** The Error that assess() rejects with. */
interface CardveraAssessError extends Error {
/** unreachable: no answer from Cardvera after the SDK's retries.
* session_expired, session_used: reload the page for a new session.
* session_unknown: Cardvera doesn't know this page's session: the script URL isn't a
* scriptUrl from POST /api/sessions, or the page is hours old (cached, or left open).
* assess_failed: anything else. */
code: "unreachable" | "assess_failed" | "session_expired" | "session_unknown" | "session_used" | (string & {});
}
interface CardveraReady {
/** false when assess() can't reach Cardvera from this page (CSP connect-src, an extension, the network). */
reachable: boolean;
/** The SDK version, e.g. "0.10.0". */
version: string;
}
interface CardveraError {
code: CardveraErrorCode;
/** The same words as the SDK's console line. */
message: string;
}
interface CardveraSDK {
/** Assess this checkout. Call once per page load, when the shopper submits.
* Resolves with nothing once Cardvera has the assessment: allow and block look the
* same here, and your server reads the verdict. Rejects with a CardveraAssessError.
* Has no timeout of its own: race it against yours. */
assess(): Promise<void>;
/** The cardvera:ready detail, as a promise: resolves even if the event already fired. */
ready(): Promise<CardveraReady>;
/** The SDK version, e.g. "0.10.0". */
readonly version: string;
}
interface WindowEventMap {
"cardvera:ready": CustomEvent<CardveraReady>;
"cardvera:error": CustomEvent<CardveraError>;
/** expiresAt: milliseconds since the epoch, by the browser's clock. */
"cardvera:expiring": CustomEvent<{ expiresAt: number }>;
}
interface Window {
/** Set once cv.js has run. Undefined before that, or if it failed to load. */
Cardvera?: CardveraSDK;
}
}Content-Security-Policy: script-src 'self' https://edge.cardvera.dev; connect-src 'self' https://edge.cardvera.dev; worker-src 'self' blob:
Read the verdict
GET https://api.cardvera.dev/api/verdict/{sid}, scope verdicts:read. Call it from your pay handler after the page's assess(), and before you authorize the card, with the sid from your own order record. The Quickstart's getVerdict does all of this.
Answers
| Response | Meaning | Do |
|---|---|---|
| 200 | The verdict (below): allow, or block with a reason. | Charge only on allow. |
| 202 | { "status": "pending", "retryAfterSeconds": 1 }, with Retry-After: 1. The session hasn't loaded or hasn't been assessed yet, or a step-up is still open. | Ask again after 1 second, up to 3 times; then decline. |
| 410 | session_expired: no page loaded the session within 20 minutes of its creation. | Decline. |
| 410 | never_assessed: a page loaded it, but it wasn't assessed in time. | Decline. |
| 404 | not_found: no such session for your account. Another account's session looks the same, and so does one whose page was hours old. | Decline. If it's frequent, check which sid you store and that the payment page isn't cached. |
| 401 / 403 | No body. 401: the key is invalid. 403: this IP isn't on its allowlist, or it lacks verdicts:read. | Decline and alert: every checkout is failing. |
| 5xx | internal_error, storage_unavailable, or no answer in time. | Decline, or apply your emergency switch. |
Reads are idempotent: ask as often as you like and you get the same answer for the same state. Cardvera saves the session before assess() resolves in the browser, so a read right after the page submits is normally 200 straight away.
The verdict
| Field | Value |
|---|---|
sid | The session id you asked for. |
txn | The orderId the session was created with. |
action | allow · block. Always final: a step-up has resolved to one of them. |
reason | Why the session was blocked (below). null on an allow. |
stepUp | { reason, result } when the session was challenged (below); null when it wasn't. |
score | 0.0 to 1.0; higher means more likely human. null when the decision didn't depend on it. |
agent | { operator, tier, tag }, only for a verified AI agent; otherwise null. See Verified AI agents. |
decidedAt | When Cardvera decided, ISO-8601 UTC. |
Block reasons
| reason | Meaning |
|---|---|
agent_signature_invalid | An AI agent's signature was forged, or reused on another session. |
known_bad_network | The IP or network is on an abuse blocklist. Not merely a proxy or VPN. |
prior_fraud | Matches a device, network or account already tied to fraud. |
session_integrity | The session changed hands or was tampered with between page load and checkout. |
automation | Not a person using a normal browser. |
velocity | Too many attempts. |
risk_score | The overall score fell below the block threshold. |
incomplete_session | The SDK didn't run fully, so there was nothing to score. |
step_up_failed | The session was challenged, and the challenge came back invalid. |
step_up_abandoned | The session was challenged, and the challenge was never completed, for example because the session expired during it. |
stepUp.reason says why the session was challenged: risk_score (the overall score called for it), network (a proxy or VPN network) or merchant_under_attack (your store was under attack, so more sessions were challenged; it says nothing about this shopper). stepUp.result is passed, failed or abandoned.
Rules
- Use the
sidfrom your order record, never one the browser sends. That's what binds the verdict to the order: there's nothing else to compare. - Never show
reasonto the shopper. It tells a card tester what to change. Show the same neutral message as for any failure. - Charge what your order record says. The verdict doesn't carry the amount.
Payment attempts and PSP idempotency
A verdict can be read any number of times, so your server makes sure one session pays once. Make that a payment attempt record (SQL in this section):
- Create the attempt before you charge. One row per session, unique on the
sid, with statuspending. A duplicate-key error means another request got there first: answer it with the first attempt's result, without charging. - Charge with the attempt id as the PSP idempotency key, where your PSP supports one, so a retried call returns the first result instead of charging again.
- Persist the result (
approvedordeclined) in the same transaction as the outcome-outbox row. If the call failed or timed out, mark the attemptunknown. - Reconcile before charging again. While any attempt for the order is
pendingorunknown, ask the PSP what happened to it, by its idempotency key, before you render checkout or create another attempt.
The guides (ASP.NET Core, React / Next.js, Node.js, Python, PHP) implement this.
# $SID: the sid on YOUR order record, from POST /api/sessions.
curl -sS -m 3 -w ' %{http_code}\n' "https://api.cardvera.dev/api/verdict/$SID" \
-H "Authorization: Bearer $CARDVERA_API_KEY"{
"sid": "3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f",
"txn": "ORD-1234",
"action": "block",
"reason": "step_up_failed",
"stepUp": { "reason": "network", "result": "failed" },
"score": 0.62,
"agent": null,
"decidedAt": "2026-11-17T10:03:58Z"
}
// "reason" is null on an allow200 The verdict
{ "sid": "...", "txn": "ORD-1234", "action": "allow", "reason": null, ... }202 Pending — ask again shortly
{ "status": "pending", "retryAfterSeconds": 1 }410 session_expired · never_assessed
{ "error": "session_expired" } // never loaded in time
{ "error": "never_assessed" } // loaded, never assessed in time404 not_found
{ "error": "not_found" } // no such session for your account503 storage_unavailable
{ "error": "storage_unavailable" } // decline, or your emergency switch-- One row per Cardvera session that reached the PSP. The id doubles as the PSP idempotency key.
CREATE TABLE payment_attempts (
id uuid PRIMARY KEY,
order_id text NOT NULL,
cardvera_sid text NOT NULL UNIQUE, -- one charge per session
status text NOT NULL, -- pending | approved | declined | unknown | failed
psp_ref text,
created_at timestamptz NOT NULL DEFAULT now()
);
-- Outcomes waiting for delivery, written with the attempt's result.
CREATE TABLE outcome_outbox (
id uuid PRIMARY KEY,
sid text NOT NULL,
outcome_type text NOT NULL,
outcome text NOT NULL,
amount_minor bigint NOT NULL, -- what the PSP charged
currency text NOT NULL,
occurred_at timestamptz NOT NULL,
outcome_id text,
attempts int NOT NULL DEFAULT 0,
next_attempt_at timestamptz NOT NULL DEFAULT now(),
status text NOT NULL DEFAULT 'due', -- due | sent | parked
created_at timestamptz NOT NULL DEFAULT now()
);
-- Pay, after the verdict is an allow. A unique violation means a duplicate request.
INSERT INTO payment_attempts (id, order_id, cardvera_sid, status)
VALUES ($1, $2, $3, 'pending');
-- The PSP answered: record the result and the outcome together.
BEGIN;
UPDATE payment_attempts SET status = $2, psp_ref = $3 WHERE id = $1;
INSERT INTO outcome_outbox (id, sid, outcome_type, outcome, amount_minor, currency, occurred_at, outcome_id)
VALUES ($4, $5, 'auth', $6, $7, $8, $9, $3);
COMMIT;
-- Worker: claim due jobs with a 2-minute lease.
UPDATE outcome_outbox SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (SELECT id FROM outcome_outbox
WHERE status = 'due' AND next_attempt_at <= now()
ORDER BY next_attempt_at LIMIT 50 FOR UPDATE SKIP LOCKED)
RETURNING *;Report outcomes
POST https://api.cardvera.dev/api/outcome, scope outcomes:write. Tell Cardvera what your PSP decided. This is the feedback loop: confirmed declines and chargebacks train the blocks that stop the next attempt. Call it from your server after each PSP response, and again when a chargeback or refund lands later. Send it from a background queue, never inline in checkout, and retry until it's accepted (see Delivery and retries).
Cardvera joins the outcome to the session by sessionId. Every outcome carries the amount that was charged, refunded or disputed, even when the session already had one: it's the amount Cardvera uses if the session had none or the cart changed.
Body
| Field | Req | |
|---|---|---|
sessionId | yes | The sid on your order record. |
outcomeType | yes | auth · chargeback · refund |
outcome | yes | Closed vocabulary; see below. |
amount | yes | Integer in the currency's smallest unit, as in Create a session: the amount charged (auth), refunded (refund) or disputed (chargeback). |
currency | yes | ISO-4217, upper-case, such as USD. |
occurredAt | yes | ISO-8601, when the PSP event happened. |
outcomeId | no | Idempotency key (e.g. PSP txn id). Dedupes on (sessionId, outcomeType, outcomeId). Without it, Cardvera dedupes on (sessionId, outcomeType, outcome, occurredAt). |
pspName | no | Audit only, e.g. stripe. |
pspRawCode | no | Audit only: the PSP's own decline code, e.g. card_declined. |
Outcome vocabulary
| outcomeType | outcome values |
|---|---|
auth | approved, declined_fraud, declined_insufficient_funds, declined_do_not_honor, declined_card_invalid, declined_3ds_failed, declined_other, declined_technical |
chargeback | chargeback_fraud, chargeback_other |
refund | refund_customer, refund_merchant |
declined_technical (weight zero). Mapping outages to declined_other poisons your own signal and can add friction for real shoppers during an incident.Delivery and retries
The Quickstart's reportOutcome makes one delivery attempt. It tells you how that attempt failed (retryable or not, and any Retry-After), but it doesn't retry. Retrying is the job of the worker that calls it. The ASP.NET Core guide has a complete worker.
| Response | Meaning | Retry? |
|---|---|---|
| 202 | Accepted and stored. It's also the answer for a duplicate, and for a sessionId Cardvera hasn't seen, so a 202 doesn't prove the sid matched. Send the sid from your own record. | No |
| 400 | The body is invalid. Fix your mapping. | No |
| 401 / 403 | No body. 401: the key is invalid. 403: this IP isn't on its allowlist, or it lacks outcomes:write. Alert, fix the key, its allowlist or its scopes, then resend. | No |
| 429 | Too many requests, with a Retry-After header. | After Retry-After |
| 500 / 503 | internal_error / storage_unavailable. | Yes |
| — | Network error or timeout. Five seconds per attempt is plenty. | Yes |
- Queue it. Write the outcome job in the same database transaction that records the PSP result (an outbox), and send it from a worker. A crash then can't lose it, and checkout never waits on Cardvera.
- Back off. Retry with exponential backoff and jitter, starting around 1 second and capped around 5 minutes. Keep trying for a day, then park the job and alert. Cardvera accepts outcomes at any time, including chargebacks weeks later.
- Send the same body on every attempt.
- Bound the work. Send a few at a time (the ASP.NET Core worker uses 4), await every send, and handle each failure. Never start fire-and-forget tasks. Claim jobs with a lease, so one cut off by a crash or a deploy is retried rather than lost.
- Make it idempotent. Set
outcomeIdto the PSP's id for the event (the charge id forauth, the dispute id forchargeback, the refund id forrefund) and store it with the job. Without one, Cardvera dedupes onoccurredAt, so that must be the PSP's event time and identical on every attempt, never the time you send.
$CARDVERA_API_KEY.202 Accepted — recorded, move on
(empty body)
400 invalid_outcome
{ "error": "invalid_outcome" }
// also: missing_session_id, invalid_outcome_type, invalid_occurred_at, invalid_amount, invalid_currency401 / 403 invalid key · IP or scope refused
(empty body) // 401: invalid key. 403: IP not on the allowlist, or no outcomes:write
503 storage_unavailable
{ "error": "storage_unavailable" } // safe to retrycurl -sS -m 5 -X POST https://api.cardvera.dev/api/outcome \
-H "Authorization: Bearer $CARDVERA_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"sessionId": "3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f",
"outcomeType":"auth",
"outcome": "declined_fraud",
"amount": 2599,
"currency": "USD",
"occurredAt": "2026-11-17T10:04:00Z",
"outcomeId": "stripe_pi_3OABCxyz",
"pspName": "stripe"
}'
202 Accepted -> recorded, move on
400 { "error": "invalid_outcome" } -> or missing_session_id, invalid_outcome_type, invalid_occurred_at,
invalid_amount, invalid_currency
401 (no body) -> fix the key, don't retry
503 { "error": "storage_unavailable" } -> safe to retryVerified AI agents
AI agents that shop on a customer's behalf, like ChatGPT Agent or agents enrolled in Visa's Trusted Agent Protocol, drive a real browser through your checkout. Many sign every request with Web Bot Auth (RFC 9421 HTTP message signatures). That includes the requests the browser makes to Cardvera. You don't need to integrate anything. Cardvera verifies the signature on the SDK fetch and on assess().
What a verified agent gets
An agent isn't a human, so Cardvera stops judging it on the "is this a human browser?" layer (mouse, typing and automation markers). That's the only change. Proof of work, blocklists, velocity, decline history and card-testing detection still apply, and an agent can still be stepped up or blocked.
- Only allowlisted operators count. Cardvera trusts a signature only from a key directory on its reviewed list (payment networks and major AI operators). A valid signature from any other operator gets no special treatment.
- Forged, replayed or expired signatures are always blocked, with the verdict reason
agent_signature_invalid. No real client produces one. - Rollout is per merchant. Accounts start in
shadow: Cardvera verifies agents and records what it would have decided, but judges them like any other client. Ask us to switch your account toenforce.
The agent field
When a verified agent drove the session, the verdict carries agent with operator, tier (PaymentNetwork · MajorOperator · Registry · Platform, rented agent infrastructure: recognised, but judged like any other client) and tag (web-bot-auth · agent-browser-auth · agent-payer-auth). You can ignore it, log it, or apply your own policy, for example requiring a signed-in account for agent orders. null means no verified agent.
GET /v1/cv.js?sid=3f9a0c1e5b7d4a2c8e6f0b1d3a5c7e9f HTTP/2
Host: edge.cardvera.dev
Signature-Agent: "https://chatgpt.com"
Signature-Input: sig1=("@authority" "@method" "@path");
created=1787000000;expires=1787000060;
keyid="poqkLGiymh_W0uP6PZFw-dvez3QJT5SolqXBCW38r0U";
tag="web-bot-auth"
Signature: sig1=:jdq0SqOwHdyHr9+r5jw3iYZH6aNGKijYp/EstF4RQTQ=:
// Cardvera: fetch the operator's key directory (cached),
// rebuild the signature base, verify, reject replays.Errors
Every API error has the same body, { "error": "<code>" }, and a few codes carry one more field. The exception is a key failure: 401 and 403 have no body, only the status.
| HTTP | error | Endpoints | Meaning and what to do |
|---|---|---|---|
| 400 | invalid_json | sessions | The body isn't a JSON object. Fix the request. |
| 400 | invalid_field | sessions | A field is missing, unknown, the wrong type or out of range; field names it. Fix the request. |
| 400 | missing_session_id, invalid_outcome_type, invalid_outcome, invalid_occurred_at, invalid_amount, invalid_currency | outcome | The outcome body is invalid. Fix your mapping. |
| 401 | (no body) | all | The key is invalid: missing, malformed, unknown or revoked. Fix it; don't retry. |
| 403 | (no body) | all | The key is valid, but this IP isn't on its allowlist, or it lacks this endpoint's scope. Check the key's Last denied (the latest IP it was refused from) and its scopes in the Portal; fix the allowlist, the route or the key. Don't retry. |
| 404 | not_found | verdict | No such session for your account. Decline. |
| 410 | session_expired | verdict | The session was created, but no page loaded it in time. Decline. |
| 410 | never_assessed | verdict | A page loaded the session, but it wasn't assessed in time. Decline. |
| 429 | rate_limited | any | On sessions: over 50 requests per second for this key. On any endpoint: too many 401s from your IP in a short time; fix the key first. retryAfterSeconds and Retry-After say when to retry. Any endpoint can also answer 429 with a plain-text body and Retry-After; treat it the same way. |
| 500 | internal_error | all | Retry with backoff. At checkout: decline, or use your emergency switch. |
| 503 | storage_unavailable | all | Retry with backoff. At checkout: decline, or use your emergency switch. |
The SDK's own failures never reach your server as HTTP errors: assess() rejects with a code (see The SDK & assess()), and a forged AI-agent signature is refused as agent_auth_invalid on the SDK's requests. You'll still see those in the browser's network panel.
{ "error": "invalid_field", "field": "currency" }
// Some codes carry one more field:
// 400 { "error": "invalid_field", "field": "amount" } the field at fault
// 429 { "error": "rate_limited", "retryAfterSeconds": 1 } also as Retry-After
// 401 and 403 have no body: branch on the status.Failure handling
Cardvera sits in your payment path, so plan for each way it can fail. Underneath everything is one rule: your server charges only on a verdict that says allow. A missing assessment is exactly what an attacker produces by blocking cv.js, so a checkout that charges when there's no verdict lets every attack through.
What happens, and what to do
| Failure | What you see | What to do |
|---|---|---|
| Creating the session fails | POST /api/sessions times out, or answers 429 or 5xx. | Store no sid and render the page without the tag; the pay step declines. Alert if the rate rises. |
| A key or allowlist error | 401 or 403 on any call. | Every checkout is declining: alert at once. Usually a revoked key (401), or a new egress IP or a key with the wrong scopes (403: check the key's Last denied and scopes in the Portal). |
| SDK doesn't load | Offline, blocked by an extension or network, or a CSP that doesn't allow edge.cardvera.dev. window.Cardvera never appears. | Page: submit once your load wait runs out. Server: the verdict stays pending; decline. Alert if the rate rises. |
| A session error | The stand-in script loads; assess() rejects with session_expired, session_used or session_unknown. | Reload for the first two. session_unknown: submit and decline; usually a bug (the page's URL isn't a scriptUrl from the API), or a page hours old. |
| Assessment is slow | assess() has no timeout of its own. | Race it against a 10-second timeout, then submit. Your server declines a pending verdict. |
| Cardvera unreachable at submit | assess() rejects with unreachable after the SDK's own retries. | Submit. Don't call assess() again on that page. |
| The verdict read fails | A timeout, a network error or a 5xx from GET /api/verdict/{sid}. | Decline, or apply your emergency switch. |
| Block | 200 with "action": "block". | Decline before the PSP. See Blocked checkouts. |
| Outcome API errors | Non-202 responses or timeouts. | Retry from your queue. Checkout is never affected. See Delivery and retries. |
Time-box every call
POST /api/sessions: 3 seconds.- SDK load: give up after about 10 seconds, then let the shopper submit.
assess(): about 10 seconds. A step-up can add a second or two on a slow phone, so leave headroom.GET /api/verdict/{sid}: 3 seconds per request; on202, ask again afterRetry-After(1 second), up to 3 times, then decline./api/outcome: 5 seconds per attempt, off the checkout path.
Retries
- Don't retry
assess()on the same page. The SDK already retries its own request. (A second call afterunreachableorassess_failedwould run again; while one is pending, or after one resolved, it rejects withsession_used.) - To try again, reload the checkout. Your render gets the order a new session.
- Let shoppers retry. Each retry is assessed afresh. Cap retries with your own rules if you like, such as a few attempts per cart per hour.
What the shopper sees
Use one neutral message for every failure, whether SDK, timeout, verdict error or block, so the page tells an attacker nothing: "We couldn't complete this payment. Please try again, or use a different payment method." Offer a retry button that reloads the checkout.
Emergency switch
If Cardvera has an incident, you may decide to take payments unscreened rather than decline them. Build that as a switch your operators control on your server, not as a reaction to anything the browser does.
- One flag in your config or feature-flag service, such as
CARDVERA_ENFORCE. While it's off, your server charges without requiring an allow, as it did before Cardvera, and still logs each order's verdict result. - Flip it by hand, based on your alerts and status.cardvera.io. Don't flip it automatically on your own rate of pending or
never_assessedverdicts: an attacker can drive that rate up by blocking the SDK. - Rehearse it in staging, write it into your runbook, and turn enforcement back on once the incident is resolved.
While enforcement is off, card testing reaches your gateway unchecked. Keep the window short.
Monitoring
Count verdict results by reason: allow, each block reason, pending, never_assessed, session_expired, not_found, the key errors and unavailable. It's the cheapest health signal you have. Have the page report cardvera:error events and assessment timeouts to your own logging. Alert when:
- Any
401or403from Cardvera. A revoked key or a changed egress IP stops every checkout. pendingornever_assessedrises sharply across many orders. The SDK isn't loading or reaching Cardvera, or a deploy broke the tag or your CSP. Check status.cardvera.io.session_expiredornot_foundappears on many orders. Usually a cached payment page, or the wrongsidon the order.- The block rate jumps. Usually an attack in progress. If checkout conversion also drops, review the blocked sessions for false positives.
- Outcome delivery fails: any
401or403, a growing queue, or jobs given up.
Cached & headless pages
A scriptUrl belongs to one order's session. Anything that serves the same copy of the page to someone else, or later, breaks that.
- Never cache a page that carries the tag. Send
Cache-Control: no-storeon the payment page, and keep it out of your CDN, full-page cache and service worker. A cached copy hands the next shopper a session that's used, expired or another shopper's: both checkouts fail. - If the page must be cached or built ahead of time, keep the tag out of the HTML. After the page loads, ask your own server for the order's session and insert the script from JavaScript (sample in this section). Your endpoint calls
POST /api/sessions, stores thesidon the order, and returns onlyscriptUrl, withno-store. - Headless and single-page storefronts work the same way: your backend holds the API key and creates the session, and the frontend only receives
scriptUrl. Never call Cardvera's API from the browser or a mobile app. See React / Next.js. - Back and forward navigation. A page restored from the browser's back/forward cache may carry a session that's already used. Reload on
pageshowwithpersisted, as in the sample; otherwiseassess()rejects withsession_usedand the client reloads then.
// On a page that is cached or built ahead of time: ask your server for this order's
// session after the page loads, then insert cv.js. Your endpoint calls POST /api/sessions
// with your API key, stores the sid on the order and returns only { scriptUrl }, no-store.
async function loadCardvera(orderId) {
const res = await fetch('/cardvera/session', {
method: 'POST', cache: 'no-store',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ orderId }),
});
if (!res.ok) return; // no session: the pay step declines
const { scriptUrl } = await res.json();
const s = document.createElement('script');
s.src = scriptUrl; s.async = true; s.crossOrigin = 'anonymous';
document.head.appendChild(s);
}
// Restored from the back/forward cache: its session may already be used. Start over.
window.addEventListener('pageshow', (e) => { if (e.persisted) location.reload(); });React / Next.js
A single-page checkout keeps one document alive across steps, remounts and client-side navigation, so the rule of one session per page load needs a little structure. This recipe uses the Next.js App Router, with the Quickstart's Node module on the server. With Express, the two route handlers become app.post() handlers with the same bodies.
The pieces
lib/cardvera-client.tsfetches the order'sscriptUrlfrom your server and loadscv.jsonce per page load. ItscardveraAssess()returns"done"or"failed", and throwscardvera_needs_reloadwhen only a fresh page load can give a usable session.CheckoutFormstarts loading on mount, so the SDK has the whole visit to collect, and callscardveraAssess()once at submit./api/cardvera/sessioncreates the order's session and stores itssid. Creating it in a route handler, not in a server component, keeps the API key on the server and the page uncached./api/checkout/[orderId]/payreads the verdict, refuses to charge while an earlier attempt is unresolved, creates the payment attempt, charges with its idempotency key, and records the result with the outcome-outbox row.
Lifecycle rules
- Initialise once.
loadCardvera()keeps one promise per page load. React Strict Mode's double effects, remounts and navigating back to checkout all reuse it. - Loading state. Let the shopper fill in the form while the SDK loads. If it's still loading at submit,
cardveraAssess()waits for it (the load gives up after 10 seconds), then gives the assessment up to 10 seconds. Disable the button while it runs. - Retry with a full page load. After a decline, a block or an error, navigate with
window.location, notrouter.push(). The next attempt needs a fresh document and a fresh session. - Every failure path ends somewhere safe. The submit handler time-boxes the pay request and treats a network error, a timeout, a non-JSON body or an unexpected status as "outcome unknown". It clears the busy state and offers a reload instead of resubmitting, because the charge may have gone through. The reload lets your server reconcile the attempt first.
- Expiry. A
session_expiredat submit becomes a reload. To avoid it, listen forcardvera:expiringand offer a reload before the shopper pays. - Types. Add types/cardvera.d.ts to your project for
window.Cardvera.
https://edge.cardvera.dev, so the same script-src, connect-src and worker-src entries apply. With a nonce-based policy, set s.nonce on the element before inserting it.// lib/cardvera-client.ts — browser side. One Cardvera session per page load.
let loading: Promise<{ sdk: CardveraSDK; orderId: string }> | null = null;
let assessed = false;
// Ask your server for this order's session and load cv.js, once per page load. Later
// calls (a remount, a client-side navigation back to checkout) reuse the same one.
export function loadCardvera(orderId: string, timeoutMs = 10_000) {
if (loading) {
return loading.then((s) => {
if (s.orderId !== orderId) throw new Error("cardvera_needs_reload"); // another order
return s;
});
}
loading = (async () => {
const res = await fetch("/api/cardvera/session", {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ orderId }), signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) throw new Error("cardvera_session_failed");
const { scriptUrl } = (await res.json()) as { scriptUrl: string };
const sdk = await new Promise<CardveraSDK>((resolve, reject) => {
const s = document.createElement("script");
s.src = scriptUrl; s.async = true; s.crossOrigin = "anonymous";
const timer = setTimeout(() => reject(new Error("cardvera_load_timeout")), timeoutMs);
s.onload = () => { clearTimeout(timer);
window.Cardvera ? resolve(window.Cardvera) : reject(new Error("cardvera_load_failed")); };
s.onerror = () => { clearTimeout(timer); reject(new Error("cardvera_load_failed")); };
document.head.appendChild(s);
});
return { sdk, orderId };
})();
return loading;
}
// Assess this page's session once. "done" or "failed": submit either way, because your
// server reads the verdict. Throws "cardvera_needs_reload" when only a full page load can
// give a usable session (already assessed, expired or used, or another order).
export async function cardveraAssess(orderId: string, timeoutMs = 10_000): Promise<"done" | "failed"> {
if (assessed) throw new Error("cardvera_needs_reload"); // one assess() per page load
let s;
try { s = await loadCardvera(orderId); }
catch (e) {
if ((e as Error).message === "cardvera_needs_reload") throw e;
return "failed"; // didn't load: your server declines
}
assessed = true;
try {
const timeout = new Promise<never>((_, reject) =>
setTimeout(() => reject(new Error("cardvera_assess_timeout")), timeoutMs));
await Promise.race([s.sdk.assess(), timeout]);
return "done";
} catch (e) {
const code = (e as Partial<CardveraAssessError>).code;
if (code === "session_expired" || code === "session_used") throw new Error("cardvera_needs_reload");
return "failed"; // unreachable or timed out
}
}"use client";
// components/CheckoutForm.tsx
import { useEffect, useRef, useState, type FormEvent } from "react";
import { loadCardvera, cardveraAssess } from "@/lib/cardvera-client";
type PayResult = { status: "paid" | "declined" | "pending" };
export function CheckoutForm({ orderId }: { orderId: string }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const submitted = useRef(false); // one submission per page load
// Start early so the SDK has the whole visit to collect. Safe on every remount.
useEffect(() => {
loadCardvera(orderId).catch((e) => {
if (e.message === "cardvera_needs_reload") window.location.reload();
}); // other load failures surface at pay: your server declines
}, [orderId]);
async function onSubmit(e: FormEvent<HTMLFormElement>) {
e.preventDefault();
if (submitted.current) return; // double-click guard
submitted.current = true;
setBusy(true);
setError(null);
let leaving = false; // true once we navigate away
try {
try { await cardveraAssess(orderId); }
catch { leaving = true; window.location.reload(); return; } // used or expired session
const res = await fetch(`/api/checkout/${orderId}/pay`, {
method: "POST", headers: { "content-type": "application/json" },
body: JSON.stringify({ /* your PSP payment token */ }),
signal: AbortSignal.timeout(30_000),
});
const data = (await res.json().catch(() => null)) as PayResult | null; // non-JSON -> null
const status = res.ok ? data?.status : undefined;
// Full page loads, not router.push(): a new attempt needs a fresh Cardvera session.
if (status === "paid") { leaving = true; window.location.assign("/thanks"); return; }
if (status === "declined") { leaving = true; window.location.assign(`/checkout/${orderId}?declined=1`); return; }
if (status === "pending") { leaving = true; window.location.assign(`/orders/${orderId}`); return; }
throw new Error(`unexpected pay response ${res.status}`);
} catch {
// Network error, timeout, server error or malformed response. The charge may or may
// not have happened, so don't resubmit from this page: reloading checkout lets your
// server reconcile the attempt first and starts a fresh Cardvera session.
setError("We couldn't confirm your payment. Reload this page to see its status before trying again.");
} finally {
if (!leaving) setBusy(false);
}
}
return (
<form onSubmit={onSubmit}>
{/* your payment fields */}
{error && <p role="alert">{error} <button type="button" onClick={() => window.location.reload()}>Reload</button></p>}
<button type="submit" disabled={busy || submitted.current}>{busy ? "Processing…" : "Pay"}</button>
</form>
);
}// app/api/cardvera/session/route.ts — this order's Cardvera session, for the page.
import { createSession } from "@/lib/cardvera"; // the Quickstart module (Node)
import { getOrderForShopper, saveCardveraSid } from "@/lib/orders";
export async function POST(req: Request) {
const { orderId } = await req.json();
const order = await getOrderForShopper(req, orderId); // must belong to this shopper
if (!order) return Response.json({ error: "not_found" }, { status: 404 });
try {
const { sid, scriptUrl } = await createSession({
orderId: order.id, amount: order.amountMinor, currency: order.currency,
flow: "full_checkout", identity: "guest", // see "Session context"
});
await saveCardveraSid(order.id, sid); // overwrite: the latest session pays
return Response.json({ scriptUrl }, { headers: { "cache-control": "no-store" } });
} catch {
await saveCardveraSid(order.id, null); // no session: the pay step declines
return Response.json({ error: "unavailable" }, { status: 503 });
}
}// app/api/checkout/[orderId]/pay/route.ts — read the verdict, open a payment attempt, charge, record.
import { getVerdict } from "@/lib/cardvera";
import { getOrderForShopper, hasUnresolvedAttempt, createPaymentAttempt, findAttemptBySid,
setAttemptResult, charge, log } from "@/lib/orders";
export async function POST(req: Request, { params }: { params: Promise<{ orderId: string }> }) {
const { orderId } = await params;
const order = await getOrderForShopper(req, orderId);
if (!order?.cardveraSid) return Response.json({ status: "declined" });
const v = await getVerdict(order.cardveraSid); // the sid from YOUR record
log.info({ orderId, sid: order.cardveraSid, result: v.allow ? "allow" : v.reason }, "cardvera");
if (!v.allow) return Response.json({ status: "declined" });
// Never start a charge while an earlier one is unresolved (see "Read the verdict").
if (await hasUnresolvedAttempt(order.id)) return Response.json({ status: "pending" });
// One attempt per session: INSERT ... with UNIQUE (cardvera_sid). A duplicate request
// gets the first attempt's state instead of a second charge.
const attempt = await createPaymentAttempt(order.id, order.cardveraSid);
if (!attempt) {
const first = await findAttemptBySid(order.cardveraSid);
return Response.json({ status: first?.status === "approved" ? "paid"
: first?.status === "declined" ? "declined" : "pending" });
}
let psp;
try {
psp = await charge(order, { idempotencyKey: attempt.id }); // retries reuse the key
} catch (e) {
await setAttemptResult(attempt.id, { status: "unknown" }); // reconcile before any new charge
log.error({ orderId, attempt: attempt.id, err: String(e) }, "charge outcome unknown");
return Response.json({ status: "pending" });
}
// One transaction: the attempt's result and the outcome-outbox row a worker delivers.
await setAttemptResult(attempt.id, {
status: psp.outcome === "approved" ? "approved" : "declined",
outcome: { sid: order.cardveraSid, outcomeType: "auth", outcome: psp.outcome,
amount: psp.amountMinor, currency: psp.currency, // what the PSP charged
occurredAt: psp.at, outcomeId: psp.id },
});
return Response.json({ status: psp.outcome === "approved" ? "paid" : "declined" });
}ASP.NET Core
A minimal-API checkout built on the Quickstart's C# Cardvera class. It covers render, verdict, payment attempt, charge, and outcome delivery.
- Render first reconciles any unresolved payment attempt for the order with the PSP. Then it creates the order's session, stores its
sidon the order, and serves the complete checkout page from The SDK & assess() withno-store. If the session can't be created, it serves the page without the tag and clears the storedsid, so the pay step declines. - Pay reads the verdict for the stored
sidand logs the result with its reason. On an allow, it creates the payment attempt (the one-charge-per-session claim), then charges with the attempt id as the PSP idempotency key. It records the result and the outbox row together, or marks the attemptunknownif the charge failed. OutcomeSenderis a hosted service that drains the outbox. It claims due jobs with a lease and sends at most 4 at a time, awaiting each one. It retries with exponential backoff and jitter, or afterRetry-After. It parks jobs on a400,401or403, or after a day, and logs an error when it does. On shutdown it stops cleanly; a job cut off mid-send is retried after its lease.
STAND-IN keeps the example self-contained: Store, InMemoryOutbox and Psp. In production, replace them with your database (the tables are sketched in the comments and under Read the verdict) and your gateway client, so every server shares state and a restart loses nothing.Configuration
Keep the API key in your secret store, such as Azure Key Vault, and give it to the app as the CARDVERA_API_KEY environment variable. Never commit it in appsettings.json.
// Program.cs — ASP.NET Core minimal API, with the Cardvera class from the Quickstart (C#).
// STAND-INS: Store and InMemoryOutbox keep this file self-contained. Replace them with your
// database (tables sketched in the comments) so every server shares them and restarts lose nothing.
using System.Collections.Concurrent;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSingleton<Store>();
builder.Services.AddSingleton<IOutcomeOutbox, InMemoryOutbox>();
builder.Services.AddSingleton<Psp>();
builder.Services.AddHostedService<OutcomeSender>();
var app = builder.Build();
// Every render of the payment page asks Cardvera for the order's session, unless an earlier
// charge is unresolved. A reload gets the same session back until it's assessed or expires.
app.MapGet("/checkout/{orderId}", async (string orderId, HttpResponse http, Store db, Psp psp,
IOutcomeOutbox outbox, ILogger<Program> log) => {
var order = db.Orders.GetOrAdd(orderId, id => new Order(id, 2599, "USD"));
foreach (var a in db.AttemptsFor(order.Id).Where(a => a.Status is "pending" or "unknown"))
await Reconcile(a, psp, outbox); // never charge again before resolving
if (db.AttemptsFor(order.Id).Any(a => a.Status == "approved")) return Results.Redirect("/thanks");
if (db.AttemptsFor(order.Id).Any(a => a.Status is "pending" or "unknown"))
return Results.Content("<p>We're confirming your payment. Refresh in a moment.</p>", "text/html");
string? scriptUrl = null;
try {
var s = await Cardvera.CreateSession(new(order.Id, order.AmountMinor, order.Currency));
order.CardveraSid = s.Sid; // overwrite: the latest session pays
scriptUrl = s.ScriptUrl;
} catch (Exception e) {
order.CardveraSid = null; // no session: the pay step declines
log.LogWarning(e, "cardvera session failed order={Order}", order.Id);
}
http.Headers.CacheControl = "no-store"; // the page carries this order's session
return Results.Content(CheckoutPage(scriptUrl, order.Id), "text/html");
});
app.MapPost("/checkout/{orderId}/pay", async (string orderId, Store db, Psp psp,
IOutcomeOutbox outbox, ILogger<Program> log) => {
if (!db.Orders.TryGetValue(orderId, out var order) || order.CardveraSid is not { } sid)
return Results.Redirect($"/checkout/{orderId}?declined=1");
var (allow, reason, _) = await Cardvera.GetVerdict(sid); // the sid from YOUR record
log.LogInformation("cardvera order={Order} sid={Sid} result={Result}", order.Id, sid, allow ? "allow" : reason);
if (!allow) // decline; the reload gets a fresh session
return Results.Redirect($"/checkout/{order.Id}?declined=1");
// One payment attempt per session. In SQL: INSERT INTO payment_attempts (id, order_id,
// cardvera_sid, status) VALUES (...,'pending') with UNIQUE (cardvera_sid). A duplicate
// request finds the first attempt and is sent to its result, never charged again.
var attempt = new PaymentAttempt(Guid.NewGuid().ToString("N"), order.Id, sid);
if (!db.Attempts.TryAdd(sid, attempt)) return Results.Redirect($"/checkout/{order.Id}");
PspResult result;
try {
result = await psp.Charge(order, idempotencyKey: attempt.Id); // retries reuse the key
} catch (Exception e) {
attempt.Status = "unknown"; // timeout or error: outcome unknown
log.LogError(e, "charge outcome unknown attempt={Attempt}", attempt.Id);
return Results.Redirect($"/checkout/{order.Id}"); // the render reconciles it first
}
await Record(attempt, result, outbox);
return attempt.Status == "approved" ? Results.Redirect("/thanks")
: Results.Redirect($"/checkout/{order.Id}?declined=1");
});
app.Run();
// Ask the PSP what happened to an attempt, by its idempotency key, and record it.
static async Task Reconcile(PaymentAttempt a, Psp psp, IOutcomeOutbox outbox) {
var result = await psp.Lookup(a.Id);
if (result is null) a.Status = "failed"; // the PSP never saw it: safe to retry
else await Record(a, result, outbox);
}
// In SQL, update the attempt and insert the outbox row in ONE transaction.
static async Task Record(PaymentAttempt a, PspResult r, IOutcomeOutbox outbox) {
a.Status = r.Outcome == "approved" ? "approved" : "declined";
await outbox.AddAsync(new OutcomeJob(Guid.NewGuid(), a.CardveraSid, "auth", r.Outcome,
r.AmountMinor, r.Currency, r.At, r.Id, Attempts: 0, CreatedAt: DateTimeOffset.UtcNow));
}
// The complete client from "The SDK & assess()". No session: no tag, and pay declines.
static string CheckoutPage(string? scriptUrl, string orderId) {
var tag = scriptUrl is null ? ""
: $"""<script src="{System.Net.WebUtility.HtmlEncode(scriptUrl)}" async crossorigin="anonymous"></script>""";
return $$"""
<!doctype html>
<html>
<head>
<meta charset="utf-8">
{{tag}}
</head>
<body>
<form id="checkout" method="post" action="/checkout/{{orderId}}/pay">
<button type="submit">Pay</button>
</form>
<script>
const form = document.getElementById('checkout');
let submitted = false;
form.addEventListener('submit', async (e) => {
e.preventDefault();
if (submitted) return;
submitted = true;
form.querySelector('button').disabled = true;
if (await cardveraAssess(10000) === 'reload') {
location.reload();
return;
}
form.submit();
});
async function cardveraAssess(ms) {
try {
const until = Date.now() + ms;
while (!window.Cardvera) {
if (Date.now() > until) return 'failed';
await new Promise((r) => setTimeout(r, 50));
}
const timeout = new Promise((_, fail) => setTimeout(() => fail(new Error('timeout')), ms));
await Promise.race([window.Cardvera.assess(), timeout]);
return 'done';
} catch (err) {
return err.code === 'session_expired' || err.code === 'session_used' ? 'reload' : 'failed';
}
}
</script>
</body>
</html>
""";
}
class Order(string id, long amountMinor, string currency) {
public string Id => id;
public long AmountMinor => amountMinor;
public string Currency => currency;
public volatile string? CardveraSid;
}
// payment_attempts(id PK = PSP idempotency key, order_id, cardvera_sid UNIQUE, status)
class PaymentAttempt(string id, string orderId, string cardveraSid) {
public string Id => id;
public string OrderId => orderId;
public string CardveraSid => cardveraSid;
public volatile string Status = "pending"; // pending | approved | declined | unknown | failed
}
class Store { // STAND-IN for your database
public ConcurrentDictionary<string, Order> Orders { get; } = new();
public ConcurrentDictionary<string, PaymentAttempt> Attempts { get; } = new(); // keyed by sid
public IEnumerable<PaymentAttempt> AttemptsFor(string orderId) => Attempts.Values.Where(a => a.OrderId == orderId);
}
record OutcomeJob(Guid Id, string Sid, string Type, string Outcome, long AmountMinor, string Currency,
DateTimeOffset OccurredAt, string? OutcomeId, int Attempts, DateTimeOffset CreatedAt);
// outcome_outbox(id, sid, type, outcome, amount_minor, currency, occurred_at, outcome_id, attempts,
// created_at, next_attempt_at, status: due | sent | parked)
interface IOutcomeOutbox {
Task AddAsync(OutcomeJob job);
// Claim up to `max` due jobs and push their next_attempt_at out by `lease`, so a crash
// mid-send means a retry later, not a lost job. In SQL: UPDATE ... RETURNING, or
// SELECT ... FOR UPDATE SKIP LOCKED.
Task<IReadOnlyList<OutcomeJob>> ClaimDueAsync(int max, TimeSpan lease);
Task MarkSentAsync(OutcomeJob job);
Task RetryAtAsync(OutcomeJob job, DateTimeOffset at); // attempts + 1
Task ParkAsync(OutcomeJob job, string reason); // alert on parked jobs
}
// Delivers outcomes off the checkout path: at most MaxConcurrency sends at a time, every
// send awaited and its failure handled, backoff with jitter (or Retry-After), parking after
// a day, and a clean stop on shutdown (a job cut off mid-send is retried after its lease).
class OutcomeSender(IOutcomeOutbox outbox, ILogger<OutcomeSender> log) : BackgroundService {
const int MaxConcurrency = 4, BatchSize = 50;
static readonly TimeSpan Lease = TimeSpan.FromMinutes(2), GiveUpAfter = TimeSpan.FromHours(24),
MaxDelay = TimeSpan.FromMinutes(5), Idle = TimeSpan.FromSeconds(1);
protected override async Task ExecuteAsync(CancellationToken stop) {
var options = new ParallelOptions { MaxDegreeOfParallelism = MaxConcurrency, CancellationToken = stop };
while (!stop.IsCancellationRequested) {
try {
var due = await outbox.ClaimDueAsync(BatchSize, Lease);
if (due.Count == 0) { await Task.Delay(Idle, stop); continue; }
await Parallel.ForEachAsync(due, options, async (job, _) => await SendOnce(job));
} catch (OperationCanceledException) when (stop.IsCancellationRequested) {
break;
} catch (Exception e) {
log.LogError(e, "outcome outbox loop failed"); // e.g. database down: pause, go on
try { await Task.Delay(Idle * 5, stop); } catch (OperationCanceledException) { break; }
}
}
}
async Task SendOnce(OutcomeJob job) {
try {
await Cardvera.ReportOutcome(job.Sid, job.Type, job.Outcome, job.AmountMinor, job.Currency,
job.OccurredAt, job.OutcomeId);
await outbox.MarkSentAsync(job);
} catch (Cardvera.CardveraException e) when (!e.Retryable) {
log.LogError(e, "outcome rejected sid={Sid}", job.Sid); // 400/401/403: fix, then resend
await outbox.ParkAsync(job, e.Message);
} catch (Exception e) {
if (DateTimeOffset.UtcNow - job.CreatedAt > GiveUpAfter) {
log.LogError(e, "outcome gave up sid={Sid}", job.Sid);
await outbox.ParkAsync(job, e.Message);
return;
}
var backoff = TimeSpan.FromSeconds(Math.Min(Math.Pow(2, job.Attempts), MaxDelay.TotalSeconds));
var wait = (e as Cardvera.CardveraException)?.RetryAfter ?? backoff;
wait += TimeSpan.FromMilliseconds(Random.Shared.Next(1000)); // jitter
log.LogWarning(e, "outcome attempt {Attempt} failed sid={Sid}; retry in {Wait}", job.Attempts + 1, job.Sid, wait);
await outbox.RetryAtAsync(job, DateTimeOffset.UtcNow + wait);
}
}
}
class InMemoryOutbox : IOutcomeOutbox { // STAND-IN: lost on restart
readonly object _gate = new();
readonly Dictionary<Guid, (OutcomeJob Job, DateTimeOffset Next, string Status)> _rows = new();
public Task AddAsync(OutcomeJob job) {
lock (_gate) _rows[job.Id] = (job, DateTimeOffset.UtcNow, "due");
return Task.CompletedTask;
}
public Task<IReadOnlyList<OutcomeJob>> ClaimDueAsync(int max, TimeSpan lease) {
lock (_gate) {
var now = DateTimeOffset.UtcNow;
var due = _rows.Values.Where(r => r.Status == "due" && r.Next <= now).Take(max).Select(r => r.Job).ToList();
foreach (var j in due) _rows[j.Id] = (j, now + lease, "due");
return Task.FromResult<IReadOnlyList<OutcomeJob>>(due);
}
}
public Task MarkSentAsync(OutcomeJob job) => Set(job, DateTimeOffset.MaxValue, "sent");
public Task RetryAtAsync(OutcomeJob job, DateTimeOffset at) => Set(job with { Attempts = job.Attempts + 1 }, at, "due");
public Task ParkAsync(OutcomeJob job, string reason) => Set(job, DateTimeOffset.MaxValue, "parked");
Task Set(OutcomeJob job, DateTimeOffset next, string status) {
lock (_gate) _rows[job.Id] = (job, next, status);
return Task.CompletedTask;
}
}
record PspResult(string Outcome, DateTimeOffset At, string Id, long AmountMinor, string Currency);
// STAND-IN for your gateway client. Send idempotencyKey as the PSP's idempotency key, so a
// retried charge returns the first result instead of charging twice, and look charges up by it.
class Psp {
readonly ConcurrentDictionary<string, PspResult> _charges = new();
public Task<PspResult> Charge(Order o, string idempotencyKey) =>
Task.FromResult(_charges.GetOrAdd(idempotencyKey,
_ => new PspResult("approved", DateTimeOffset.UtcNow, "psp_" + Guid.NewGuid().ToString("N"),
o.AmountMinor, o.Currency)));
public Task<PspResult?> Lookup(string idempotencyKey) =>
Task.FromResult(_charges.TryGetValue(idempotencyKey, out var r) ? r : null);
}Node.js (Express)
A server-rendered checkout on the Quickstart's Node module. shop.mjs is yours: your order store, the payment attempts table (see Read the verdict), your PSP client, and the page from The SDK & assess() with the tag left out when there's no scriptUrl.
- Render creates the order's session on every request, stores the
sid, and sends the pageno-store. A failed create stores nosid. - Pay reads the verdict for the stored
sid, logs the reason, and charges only on an allow, once per session. - Outcomes go into your outbox with the PSP result; a worker sends them with
reportOutcome, as the ASP.NET Core guide'sOutcomeSenderdoes.
// server.mjs — an Express checkout on the Quickstart module (cardvera.mjs).
import express from "express"; // npm i express
import { createSession, getVerdict } from "./cardvera.mjs";
import { orders, attempts, charge, checkoutPage } from "./shop.mjs"; // yours: database, PSP, page
const app = express();
// Every render of the payment page: this order's Cardvera session.
app.get("/checkout/:orderId", async (req, res) => {
const order = await orders.get(req.params.orderId);
if (!order) return res.sendStatus(404);
if (await attempts.unresolved(order.id)) return res.redirect(303, `/orders/${order.id}`);
let scriptUrl = null;
try {
const s = await createSession({ orderId: order.id, amount: order.amountMinor, currency: order.currency });
await orders.setCardveraSid(order.id, s.sid); // overwrite: the latest session pays
scriptUrl = s.scriptUrl;
} catch (err) {
await orders.setCardveraSid(order.id, null); // no session: the pay step declines
console.warn("cardvera session failed", order.id, err.message);
}
res.set("Cache-Control", "no-store").send(checkoutPage(order, scriptUrl)); // no tag without a session
});
// The form posts here after assess(). The sid comes from your record, never the request.
app.post("/checkout/:orderId/pay", async (req, res) => {
const order = await orders.get(req.params.orderId);
const declined = `/checkout/${req.params.orderId}?declined=1`;
if (!order?.cardveraSid) return res.redirect(303, declined);
const v = await getVerdict(order.cardveraSid);
console.info("cardvera", { orderId: order.id, sid: order.cardveraSid, result: v.allow ? "allow" : v.reason });
if (!v.allow) return res.redirect(303, declined);
if (await attempts.unresolved(order.id)) return res.redirect(303, `/orders/${order.id}`);
const attempt = await attempts.create(order.id, order.cardveraSid); // UNIQUE (cardvera_sid)
if (!attempt) return res.redirect(303, `/orders/${order.id}`); // a duplicate submit
let psp;
try {
psp = await charge(order, { idempotencyKey: attempt.id });
} catch (err) {
await attempts.markUnknown(attempt.id); // reconcile with the PSP before any new charge
return res.redirect(303, `/orders/${order.id}`);
}
await attempts.record(attempt.id, psp); // the result and its outcome-outbox row, one transaction
res.redirect(303, psp.outcome === "approved" ? "/thanks" : declined);
});
app.listen(3000);Python (Flask)
The same checkout in Flask, on the Quickstart's Python module. shop is yours, as in the Node.js guide. The module uses only the standard library; with an async framework, call it from a worker thread or port _call to your HTTP client, keeping the same timeouts.
- Render creates the order's session, stores the
sid, and sends the pageno-store. A failed create (CardveraError, orOSErrorfor a network error or timeout) stores nosid. - Pay reads the verdict for the stored
sid, logs the reason, and charges only on an allow, once per session.
# app.py - a Flask checkout on the Quickstart module (cardvera.py).
from flask import Flask, abort, make_response, redirect # pip install flask
import cardvera
from shop import orders, attempts, charge, checkout_page # yours: database, PSP, page
app = Flask(__name__)
@app.get("/checkout/<order_id>")
def checkout(order_id):
"""Every render of the payment page: this order's Cardvera session."""
order = orders.get(order_id) or abort(404)
if attempts.unresolved(order.id):
return redirect(f"/orders/{order.id}", 303)
script_url = None
try:
s = cardvera.create_session(order.id, order.amount_minor, order.currency)
orders.set_cardvera_sid(order.id, s["sid"]) # overwrite: the latest session pays
script_url = s["scriptUrl"]
except (cardvera.CardveraError, OSError) as e:
orders.set_cardvera_sid(order.id, None) # no session: the pay step declines
app.logger.warning("cardvera session failed order=%s: %s", order.id, e)
resp = make_response(checkout_page(order, script_url)) # no tag without a session
resp.headers["Cache-Control"] = "no-store"
return resp
@app.post("/checkout/<order_id>/pay")
def pay(order_id):
"""The form posts here after assess(). The sid comes from your record, never the request."""
declined = redirect(f"/checkout/{order_id}?declined=1", 303)
order = orders.get(order_id)
if not order or not order.cardvera_sid:
return declined
allow, reason, _ = cardvera.get_verdict(order.cardvera_sid)
app.logger.info("cardvera order=%s sid=%s result=%s", order.id, order.cardvera_sid,
"allow" if allow else reason)
if not allow:
return declined
if attempts.unresolved(order.id):
return redirect(f"/orders/{order.id}", 303)
attempt = attempts.create(order.id, order.cardvera_sid) # UNIQUE (cardvera_sid); None = duplicate
if attempt is None:
return redirect(f"/orders/{order.id}", 303)
try:
psp = charge(order, idempotency_key=attempt.id)
except Exception:
attempts.mark_unknown(attempt.id) # reconcile with the PSP before any new charge
return redirect(f"/orders/{order.id}", 303)
attempts.record(attempt.id, psp) # the result and its outcome-outbox row, one transaction
return redirect("/thanks", 303) if psp.outcome == "approved" else declinedPHP
Two plain PHP pages on the Quickstart's PHP module. shop.php is yours: order lookups, the payment attempts table and your PSP client. Frameworks such as Laravel or Symfony follow the same two steps in a controller.
checkout.phpcreates the order's session, stores thesid, sendsno-store, and prints the tag only when there's ascriptUrl. Add the submit handler from The SDK & assess().pay.phpreads the verdict for the storedsid, logs the reason, and charges only on an allow, once per session.
<?php // checkout.php — the payment page, with this order's Cardvera session.
require 'cardvera.php'; // the Quickstart module
require 'shop.php'; // yours: orders, attempts, charge()
$order = order_find($_GET['order'] ?? '');
if (!$order) { http_response_code(404); exit; }
if (attempt_unresolved($order['id'])) { header('Location: order.php?order=' . urlencode($order['id']), true, 303); exit; }
$scriptUrl = null;
try {
$s = cv_create_session($order['id'], $order['amount_minor'], $order['currency']);
order_set_cardvera_sid($order['id'], $s['sid']); // overwrite: the latest session pays
$scriptUrl = $s['scriptUrl'];
} catch (CvError $e) {
order_set_cardvera_sid($order['id'], null); // no session: the pay step declines
error_log("cardvera session failed order={$order['id']}: " . $e->getMessage());
}
header('Cache-Control: no-store'); // the page carries this order's session
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<?php if ($scriptUrl): ?>
<script src="<?= htmlspecialchars($scriptUrl) ?>" async crossorigin="anonymous"></script>
<?php endif; ?>
</head>
<body>
<form id="checkout" method="post" action="pay.php?order=<?= urlencode($order['id']) ?>">
<button type="submit">Pay</button>
</form>
<script>/* the submit handler from "The SDK & assess()" */</script>
</body>
</html><?php // pay.php — the form posts here after assess(): read the verdict, then charge or decline.
require 'cardvera.php';
require 'shop.php';
function go(string $to): never { header("Location: $to", true, 303); exit; }
$id = $_GET['order'] ?? '';
$order = order_find($id);
$sid = $order['cardvera_sid'] ?? null; // from YOUR record, never the request
if (!$sid) go('checkout.php?declined=1&order=' . urlencode($id));
[$allow, $reason] = cv_get_verdict($sid);
error_log("cardvera order=$id sid=$sid result=" . ($allow ? 'allow' : $reason));
if (!$allow) go('checkout.php?declined=1&order=' . urlencode($id));
if (attempt_unresolved($id)) go('order.php?order=' . urlencode($id));
$attempt = attempt_create($id, $sid); // UNIQUE (cardvera_sid); null = a duplicate submit
if (!$attempt) go('order.php?order=' . urlencode($id));
try {
$psp = charge($order, $attempt['id']); // the attempt id is the PSP idempotency key
} catch (\Throwable $e) {
attempt_mark_unknown($attempt['id']); // reconcile with the PSP before any new charge
go('order.php?order=' . urlencode($id));
}
attempt_record($attempt['id'], $psp); // the result and its outcome-outbox row, one transaction
go($psp['outcome'] === 'approved' ? 'thanks.php' : 'checkout.php?declined=1&order=' . urlencode($id));Blocked checkouts
A block means Cardvera judged the attempt to be card testing or automation. Decline it before it reaches your PSP: that's what keeps the attempt off your gateway bill and out of your decline ratios.
- Message. Show the same neutral message as any other failure (see Failure handling). Don't mention fraud screening, Cardvera or the reason.
- Retry. Let the shopper reload and try again. Each attempt is a fresh session, assessed on its own evidence. Rate-limit retries per cart or account with your own rules if you want.
- Other payment methods. Your choice. Where a method starts its payment on your page, such as a wallet button, gate it with the same verdict.
- Nothing to report. A blocked attempt never reached your PSP, so it has no outcome.
- Log for support: the order id,
sid, the verdict'sreason,stepUp,scoreanddecidedAt,agentif present, your customer id and the time. Never card data.
When a real customer is blocked
- Find the attempt in your logs by order or customer, and note its
sidand time. - Check it was a Cardvera block: a
200verdict withactionblock. Apending,never_assessed, key error or timeout is an integration or availability problem; see Failure handling. - Check the context you sent: the right
flowfor the page, andidentityandsubjectfor signed-in customers. A wrongflowis the most common cause of false positives (see Session context). - Send the
sidand time to Cardvera support so we can review the session.
Production checklist
- API keys server-side only. In your secret store, never in client code, an app, a log or the repo. One key per service, with only the scopes it calls.
- Allowlist set deliberately. Your production egress IPs or ranges, or
anyif you chose it knowingly. Check that a call from production isn't refused with403; if it is, the key's Last denied in the Portal shows the IP it came from. - Create a session on every render of the payment page and store the
sidfrom every response on the order. - The payment page is
no-storeand never cached by a CDN or service worker. See Cached & headless pages. - Charge only on
allow, read fromGET /api/verdict/{sid}with thesidfrom your record. No path charges on anything the browser sends. - One charge per session. A payment attempt unique on the
sid, and the attempt id as the PSP idempotency key. - Fail closed. A pending verdict after your retries, a
410, a404, a key error or a timeout all decline, unless your emergency switch is on. - Time-box everything. 3 seconds for each API call, about 10 to load the SDK and 10 to assess, one
assess()per page load, and a full reload to try again. - Wire
/api/outcomethrough a queue. Report every auth result, and chargebacks and refunds when they land, retrying with backoff. Send the amount and currency charged, the PSP's id asoutcomeIdand its event time asoccurredAt. Map faults todeclined_technical, notdeclined_other. - Test every branch. Run your verdict handling against canned answers in CI, and work through Test your integration in staging.
- Plan for failure. Alerts on verdict results, key errors and outcome delivery, and an emergency switch in your runbook. See Failure handling.
- CSP and script inventory. Allow
https://edge.cardvera.devand listcv.js. See Security & PCI FAQ. - Send
subjectfor signed-in customers, derived with a dedicated key: it enables account-level protection that survives IP and device rotation. - Know how to replace a key: create, deploy, revoke the old one. See Revoking and replacing a key.
Security & PCI FAQ
What Cardvera does to protect the script and your data, and what stays your responsibility. Your QSA decides how these controls map to your own assessment.
What does the SDK collect?
Interaction timing and counts (pointer movement, keystroke timing, focus, dwell, paste and autofill), tagged with each field's id or name. Browser and device characteristics. Network details, including the IP address. It never reads field values: no card data or checkout-field contents. It sends data only to the domain it was loaded from.
What does my server send?
The order context in POST /api/sessions (order id, amount, currency, flow, identity, and optionally a pseudonymous subject and the shopper's IP) and PSP outcomes. No cardholder data. The browser never carries the context or a verdict.
Where does the data go, and who can see it?
Signals, verdicts and transaction data stay in your account. When Cardvera sees an attack on one merchant, the block rules derived from it protect every merchant. Those rules describe the attacker, never merchant or customer data. A data processing agreement (DPA) is available on request.
Does Cardvera need access to my gateway?
No. Cardvera needs no gateway settings, credentials or merchant-account access. Outcomes come from your server through /api/outcome and carry no cardholder data.
How do I list cv.js for PCI DSS 4.0 requirement 6.4.3?
In your payment-page script inventory, list cv.js from https://edge.cardvera.dev, with its purpose (fraud screening) and your own approval. For integrity, record the controls below rather than an SRI hash; The SDK & assess() explains why a hash can't work for this script.
- It's served only over HTTPS, only from Cardvera's edge network at
edge.cardvera.dev. - It's served only for a session your server created with its API key.
- Your CSP restricts it to that domain, for both
script-srcandconnect-src.
Those controls limit where the script comes from and who can load it. They don't prove what it contains. If your assessment needs more, raise it with Cardvera during onboarding.
What about requirement 11.6.1 (change and tamper detection)?
cv.js differs on every load by design, and Cardvera updates it without any change to your tag, so a monitor that hashes script contents will flag it every time. Monitor it by source instead: alert when the payment page loads a script from anywhere but your approved hosts, and when the Cardvera tag or its CSP entries change.
How are changes managed?
Cardvera ships SDK updates behind the same /v1 URL, without any change to your tag. The interface this reference documents (the tag, assess() and its events, and the three API endpoints) changes only in ways that keep existing integrations working: new fields and new codes may appear, so ignore ones you don't know.
Who is responsible for what?
| Cardvera | You |
|---|---|
| Serving the SDK over HTTPS from its edge network, only for sessions your server created | Keeping your API keys server-side, scoped and IP-restricted, and revoking any that may have leaked |
| Keeping verdicts off the browser and answering them only to your keys | Reading the verdict for your stored sid before you charge |
| Publishing platform status at status.cardvera.io | Your CSP, script inventory and payment-page monitoring |
| Handling vulnerability reports at security@cardvera.io | Telling shoppers about fraud screening in your privacy notice |
Incidents
- Cardvera is down or degraded: check status.cardvera.io, then follow your failure plan.
- An API key may have leaked: revoke it in the Portal (it stops working within 5 minutes), then create a new one. See Revoking and replacing a key.
- You've found a vulnerability: email security@cardvera.io.