> ## Documentation Index
> Fetch the complete documentation index at: https://usefoil.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Checkout & payment

> Use Foil at checkout to decline automated payments, give your fraud review device and network context, and keep session records for chargeback disputes.

This guide shows you how to add Foil to a checkout flow. Foil helps at checkout in three ways. It identifies automated sessions so that you can decline them before they reach your payment processor, it gives your fraud rules and review team device and network context for orders that people place, and it keeps a record of each payment's session that you can use when a customer disputes a charge.

When you finish, your checkout endpoint verifies a Foil token with every payment request, declines automated sessions and blocked devices, and stores the Foil session and device with each order. Your order review can read the session's device and network details, and your team can use the stored session when it responds to a dispute.

## Before you begin

* Load the browser SDK on your checkout page. See [Browser SDK](https://usefoil.com/docs/browser-sdk.md).
* Install a server SDK and set `FOIL_SECRET_KEY` on the server that handles checkout. See [Server verification](https://usefoil.com/docs/server-verification.md).
* Confirm that your server makes the request that creates or confirms the payment. If your checkout confirms payments from the browser, verify the Foil token in the server request that creates the payment instead.

## How Foil helps at checkout

### Automated checkout

Scripts and automated browsers carry out several kinds of checkout abuse. In card testing, an attacker with a list of stolen card numbers submits small payments to find out which cards are still active, and each attempt can cost you an authorization fee and raise your decline rate with your processor. Scalping bots buy limited-stock items at release faster than people can, and other bots guess gift card numbers to find ones with a balance. Foil returns a `bot` verdict for these sessions, so you can decline them before the payment reaches your processor. The same device also tends to appear across many attempts even when the attacker rotates IP addresses, which lets you limit attempts per device.

Foil also returns `bot` for AI agents that operate a browser. If you want to accept purchases that customers make through an agent, fetch the session from the [Sessions API](https://usefoil.com/docs/api-reference/sessions.md) before you decline it, and check `attribution.labels` for a label whose `kind` is `actor` and whose `value` is `ai-agent`.

### Fraud that leads to chargebacks

Many fraud chargebacks come from purchases that a person makes with a stolen card in an ordinary browser, often from a device and network chosen to hide who they are. Foil returns `human` for these sessions, because a person is making the purchase, so the verdict alone doesn't catch them. Instead, Foil gives your fraud rules and review team context that is hard to get from the payment details:

* The visitor fingerprint identifies the device across sessions, including after the browser's cookies are cleared. You can count how many customer accounts, cards, and shipping addresses have been used from one device, and you can block a device after a confirmed fraud chargeback.
* The session's network details report whether the connection came through a VPN, a proxy, a residential proxy, or Tor, and where the IP address is located, which you can compare with the billing and shipping addresses.
* The session's runtime integrity details report whether the browser is misrepresenting its identity, which is common in tools that make one computer look like many different devices.

Your processor's fraud checks and 3-D Secure remain the primary controls for card fraud, and Foil's signals work best as inputs to them. If an attacker reaches checkout through a compromised account, stop them at sign-in instead. See [Login & credential stuffing](https://usefoil.com/docs/use-cases/login.md).

### Disputes

Some disputes are filed by cardholders for purchases they made themselves. When a customer disputes a charge, the Foil session stored with the order shows the device, network, and location used for the purchase. If the same device placed earlier orders on the customer's account that weren't disputed, that history can support your response to the dispute.

## How the integration works

**1. Start Foil when the checkout page loads**

The browser SDK collects signals while the customer enters their payment details.

**2. Request a session handoff when the customer submits payment**

`getSession()` returns a `sessionId` and a `sealedToken`, which the page sends to your server with the payment request.

**3. Verify the token before you call your processor**

Your server verifies the token locally with your secret key and checks that it was issued recently.

**4. Apply your checkout policy**

Decline `bot` sessions and blocked devices, ask for 3-D Secure when the verdict is `inconclusive`, and send everything else to your processor.

**5. Record the session with the order**

Store the Foil session ID and device ID with the order, and attach your customer ID to the Foil session.

**6. Review orders before you fulfill them**

For orders that need a closer look, fetch the session's device and network details and pass them to your fraud rules or review queue.

**7. Act on chargebacks**

When a fraud chargeback arrives, block the order's device. When you respond to a dispute, use the stored session as part of your evidence.

## Token fields used at checkout

After verification, your server reads the following fields from the token.

| Field | Description | How checkout uses it |
| - | - | - |
| `session_id` | The Foil session that produced the token. | Store it with the order. Use this value rather than the `sessionId` that the browser sent. |
| `decision.verdict` | `human`, `inconclusive`, or `bot`. | Decline the payment when the verdict is `bot`, and require 3-D Secure when it's `inconclusive`. |
| `decision.risk_score` | An integer from `0` to `100`. | Pass it to your processor or rules engine as payment metadata. |
| `decision.evaluated_at` | The time that Foil produced the decision, as an ISO 8601 timestamp. | Reject tokens that are more than a few minutes old. |
| `visitor_fingerprint.id` | A stable identifier for the device. | Check it against your device blocklist, count payment attempts per device, and store it with the order. |

For the full token shape, see [Server verification](https://usefoil.com/docs/server-verification.md).

## Add Foil to the checkout page

Start Foil when the checkout page loads, and call `getSession()` when the customer submits payment. `getSession()` waits for fingerprinting to finish before it returns a handoff, so you don't need to call `waitForFingerprint()` first. Fingerprinting usually finishes within a few hundred milliseconds of page load, well before the customer has entered their payment details.

```html theme={"dark"}
<script type="module">
  const foilPromise = import("https://cdn.usefoil.com/t.js").then((Foil) =>
    Foil.start({ publishableKey: "pk_live_your_publishable_key" }),
  );

  async function getFoilHandoff() {
    try {
      const foil = await foilPromise;
      return await foil.getSession();
    } catch (err) {
      // Send the payment without a handoff. The server decides how to treat it.
      return null;
    }
  }

  async function submitPayment(payment) {
    const foil = await getFoilHandoff();

    return fetch("/api/checkout", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ ...payment, foil }),
    });
  }
</script>
```

If the script fails to load or `getSession()` fails, the page sends the payment without a handoff. This keeps a network problem or a blocked script from stopping a real customer at checkout. The next section describes how the server handles a payment that arrives without a valid token.

## Verify the token on your server

Verify the token before you call your payment processor, so that payments from automated sessions never reach it. The example below does the following:

1. Verifies the sealed token and treats it as missing if verification fails or if the token is more than five minutes old.
2. Declines the payment if the verdict is `bot` or the device is on your blocklist. The [Block devices after a fraud chargeback](#block-devices-after-a-fraud-chargeback) section describes how devices get there.
3. Passes the payment to your existing checkout with the Foil session ID, device ID, verdict, and risk score attached as metadata. If the verdict is `inconclusive` or the token is missing, it asks the processor to require 3-D Secure.

`chargePayment` stands in for your existing checkout, including how it creates orders, handles 3-D Secure, and responds to the page. `isBlockedDevice` stands in for your blocklist lookup. The `DECLINED` response should match what your checkout already returns for a card decline. Card-testing tools read the response to decide whether a card works, and if Foil declines look different from processor declines, the tool can recognize them and retry those cards later from a different setup.

```javascript Node.js theme={"dark"}
const { safeVerifyFoilToken } = require("@abxy/foil-server");

const MAX_TOKEN_AGE_MS = 5 * 60 * 1000;
const DECLINED = { error: "Your payment could not be processed." };

function verifyFoil(handoff) {
  if (!handoff?.sealedToken) return null;

  const result = safeVerifyFoilToken(handoff.sealedToken, process.env.FOIL_SECRET_KEY);
  if (!result.ok) return null;

  const age = Date.now() - Date.parse(result.data.decision.evaluated_at);
  if (age > MAX_TOKEN_AGE_MS) return null;

  return result.data;
}

app.post("/api/checkout", async (req, res) => {
  const foil = verifyFoil(req.body.foil);
  const deviceId = foil?.visitor_fingerprint?.id ?? null;

  if (foil?.decision.verdict === "bot" || (deviceId && (await isBlockedDevice(deviceId)))) {
    return res.status(402).json(DECLINED);
  }

  return chargePayment(req, res, {
    requireAuthentication: !foil || foil.decision.verdict === "inconclusive",
    metadata: {
      foil_session_id: foil?.session_id ?? "none",
      foil_device_id: deviceId ?? "none",
      foil_verdict: foil?.decision.verdict ?? "none",
      foil_risk_score: foil ? String(foil.decision.risk_score) : "none",
    },
  });
});
```

```python Python theme={"dark"}
import os
from datetime import datetime, timezone

from foil_server import safe_verify_foil_token

MAX_TOKEN_AGE_SECONDS = 5 * 60
DECLINED = {"error": "Your payment could not be processed."}


def verify_foil(handoff):
    if not handoff or not handoff.get("sealedToken"):
        return None

    result = safe_verify_foil_token(handoff["sealedToken"], os.environ["FOIL_SECRET_KEY"])
    if not result.ok:
        return None

    evaluated_at = datetime.fromisoformat(
        result.data.decision.evaluated_at.replace("Z", "+00:00")
    )
    if (datetime.now(timezone.utc) - evaluated_at).total_seconds() > MAX_TOKEN_AGE_SECONDS:
        return None

    return result.data


@app.post("/api/checkout")
def checkout(request):
    foil = verify_foil(request.json.get("foil"))
    device_id = foil.visitor_fingerprint.id if foil and foil.visitor_fingerprint else None

    if (foil and foil.decision.verdict == "bot") or (device_id and is_blocked_device(device_id)):
        return DECLINED, 402

    return charge_payment(
        request,
        require_authentication=foil is None or foil.decision.verdict == "inconclusive",
        metadata={
            "foil_session_id": foil.session_id if foil else "none",
            "foil_device_id": device_id or "none",
            "foil_verdict": foil.decision.verdict if foil else "none",
            "foil_risk_score": str(foil.decision.risk_score) if foil else "none",
        },
    )
```

```go Go theme={"dark"}
import (
    "encoding/json"
    "net/http"
    "os"
    "strconv"
    "time"

    foil "github.com/abxy-labs/foil-server-go"
)

const maxTokenAge = 5 * time.Minute

type checkoutRequest struct {
    // ...your existing checkout fields
    Foil *struct {
        SealedToken string `json:"sealedToken"`
    } `json:"foil"`
}

func verifyFoil(body checkoutRequest) *foil.VerifiedFoilToken {
    if body.Foil == nil || body.Foil.SealedToken == "" {
        return nil
    }

    result := foil.SafeVerifyFoilToken(body.Foil.SealedToken, os.Getenv("FOIL_SECRET_KEY"))
    if !result.OK {
        return nil
    }

    evaluatedAt, err := time.Parse(time.RFC3339, result.Data.Decision.EvaluatedAt)
    if err != nil || time.Since(evaluatedAt) > maxTokenAge {
        return nil
    }

    return result.Data
}

func checkoutHandler(w http.ResponseWriter, r *http.Request) {
    var body checkoutRequest
    if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
        http.Error(w, "Bad request", http.StatusBadRequest)
        return
    }
    token := verifyFoil(body)

    deviceID := ""
    if token != nil && token.VisitorFingerprint != nil {
        deviceID = token.VisitorFingerprint.ID
    }
    if (token != nil && token.Decision.Verdict == "bot") || (deviceID != "" && isBlockedDevice(deviceID)) {
        w.Header().Set("Content-Type", "application/json")
        w.WriteHeader(http.StatusPaymentRequired)
        json.NewEncoder(w).Encode(map[string]string{"error": "Your payment could not be processed."})
        return
    }

    metadata := map[string]string{
        "foil_session_id": "none",
        "foil_device_id":  "none",
        "foil_verdict":    "none",
        "foil_risk_score": "none",
    }
    if token != nil {
        metadata["foil_session_id"] = token.SessionID
        metadata["foil_verdict"] = token.Decision.Verdict
        metadata["foil_risk_score"] = strconv.Itoa(token.Decision.RiskScore)
    }
    if deviceID != "" {
        metadata["foil_device_id"] = deviceID
    }

    chargePayment(w, r, body, ChargeOptions{
        RequireAuthentication: token == nil || token.Decision.Verdict == "inconclusive",
        Metadata:              metadata,
    })
}
```

```ruby Ruby theme={"dark"}
require "foil/server"
require "time"

MAX_TOKEN_AGE_SECONDS = 5 * 60
DECLINED = { error: "Your payment could not be processed." }.to_json

def verify_foil(handoff)
  return nil unless handoff && handoff["sealedToken"]

  result = Foil::Server::SealedToken.safe_verify_foil_token(
    handoff["sealedToken"],
    ENV.fetch("FOIL_SECRET_KEY"),
  )
  return nil unless result[:ok]

  token = result[:data]
  return nil if Time.now - Time.iso8601(token[:decision][:evaluated_at]) > MAX_TOKEN_AGE_SECONDS

  token
end

post "/api/checkout" do
  body = JSON.parse(request.body.read)
  foil = verify_foil(body["foil"])
  device_id = foil&.dig(:visitor_fingerprint, :id)

  halt 402, DECLINED if foil&.dig(:decision, :verdict) == "bot"
  halt 402, DECLINED if device_id && blocked_device?(device_id)

  charge_payment(
    body,
    require_authentication: foil.nil? || foil[:decision][:verdict] == "inconclusive",
    metadata: {
      foil_session_id: foil ? foil[:session_id] : "none",
      foil_device_id: device_id || "none",
      foil_verdict: foil ? foil[:decision][:verdict] : "none",
      foil_risk_score: foil ? foil[:decision][:risk_score].to_s : "none",
    },
  )
end
```

```php PHP theme={"dark"}
use Foil\Server\SealedToken;

const MAX_TOKEN_AGE_SECONDS = 5 * 60;

function verifyFoil(?array $handoff): ?array
{
    if (empty($handoff["sealedToken"])) {
        return null;
    }

    $result = SealedToken::safeVerify($handoff["sealedToken"], getenv("FOIL_SECRET_KEY"));
    if (!$result->ok) {
        return null;
    }

    $token = $result->data->toArray();
    if (time() - strtotime($token["decision"]["evaluated_at"]) > MAX_TOKEN_AGE_SECONDS) {
        return null;
    }

    return $token;
}

$body = json_decode(file_get_contents("php://input"), true);
$foil = verifyFoil($body["foil"] ?? null);
$deviceId = $foil["visitor_fingerprint"]["id"] ?? null;

if (($foil["decision"]["verdict"] ?? null) === "bot" || ($deviceId !== null && isBlockedDevice($deviceId))) {
    http_response_code(402);
    echo json_encode(["error" => "Your payment could not be processed."]);
    exit;
}

chargePayment(
    $body,
    requireAuthentication: $foil === null || $foil["decision"]["verdict"] === "inconclusive",
    metadata: [
        "foil_session_id" => $foil["session_id"] ?? "none",
        "foil_device_id" => $deviceId ?? "none",
        "foil_verdict" => $foil["decision"]["verdict"] ?? "none",
        "foil_risk_score" => $foil ? (string) $foil["decision"]["risk_score"] : "none",
    ],
);
```

### Limit attempts per device

Card testers submit many cards from the same device, so a limit on payment attempts per device adds a second layer. The example above doesn't include this limit, so add it yourself, right before the call to your checkout. Keep a counter per `visitor_fingerprint.id` that expires after an hour, increment it before you call the processor, and decline when it passes a small number, such as three attempts that weren't approved. Use an atomic increment, such as Redis `INCR`, so that parallel requests can't all pass the check. When there is no valid token, count by IP address instead.

The limit also covers replayed tokens. The server SDKs don't check a token's age, which is why the example rejects tokens older than five minutes. Within that window, a token captured from a real browser session still carries the same device ID every time it's reused, so an attempt limit stops it after a few tries.

## Record the session with the order

Store the Foil session ID and device ID with the order in your own database, and pass them to your processor as payment metadata as the example does. Most processors show metadata in their dashboard, which lets your team see the Foil session next to the processor's own risk information. Use the `session_id` and `visitor_fingerprint.id` from the verified token rather than values that the browser sent.

After you create the order, attach your customer ID to the Foil session. This links the session to the customer's account in the Foil dashboard and in the Sessions API.

```javascript Node.js theme={"dark"}
const { Foil } = require("@abxy/foil-server");

const client = new Foil({ secretKey: process.env.FOIL_SECRET_KEY });

await client.sessions.attachClientUser(order.foilSessionId, customer.id);
```

```python Python theme={"dark"}
from foil_server import Foil

client = Foil(secret_key=os.environ["FOIL_SECRET_KEY"])

client.sessions.attach_client_user(order.foil_session_id, customer.id)
```

```go Go theme={"dark"}
client, err := foil.NewClient(foil.WithSecretKey(os.Getenv("FOIL_SECRET_KEY")))
if err != nil {
    log.Fatal(err)
}

_, err = client.Sessions.AttachClientUser(ctx, order.FoilSessionID, customer.ID)
```

```ruby Ruby theme={"dark"}
client = Foil::Server::Client.new(secret_key: ENV.fetch("FOIL_SECRET_KEY"))

client.sessions.attach_client_user(order.foil_session_id, customer.id)
```

```php PHP theme={"dark"}
use Foil\Server\Client;

$client = new Client(secretKey: getenv("FOIL_SECRET_KEY"));

$client->sessions()->attachClientUser($order->foilSessionId, $customer->id);
```

```bash cURL theme={"dark"}
curl -X PATCH https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..." \
  -H "Content-Type: application/json" \
  -d '{"client_user_id":"customer_123"}'
```

If your platform takes orders on behalf of other businesses, you can also set `client_application_id` to the ID of the business the order belongs to. Set it with the SDKs' `attachClientApplication` helper (`attach_client_application` in Python and Ruby), or send it in the same `PATCH` request as `client_user_id`. See the [Sessions API](https://usefoil.com/docs/api-reference/sessions.md).

## Review orders before you fulfill them

The token gives you enough to decline automated sessions at checkout. For fraud that a person commits, the more useful information is in the session's device and network details, which you fetch from the Sessions API. The lookup is a network call to Foil, so run it after the payment is authorized rather than in the checkout request, for example in the job that decides whether to capture the payment or release the order for shipping. You can fetch details for every order, or only for orders that meet your review criteria, such as high-value orders, orders from new customer accounts, or orders with an `inconclusive` verdict.

The following fields are the most useful for order review.

| Field | Description |
| - | - |
| `visitor_fingerprint.lifecycle` | When Foil first and last saw the device, and how many sessions it has had. |
| `network.anonymity` | Whether the connection came through a VPN, a proxy, a residential proxy, Tor, or a hosting provider. Each is a boolean field. |
| `network.location.country_code` | The country of the IP address, which you can compare with the billing and shipping addresses. |
| `runtime_integrity.identity_spoofing` | Whether the browser is misrepresenting its identity: `clean`, `notice`, `elevated`, or `high_risk`. |
| `highlights` | Up to five plain-language findings that explain the session's decision, written for a person reviewing the order. |

The example below fetches the session for an order and returns the fields that a rules engine or review queue needs.

```javascript Node.js theme={"dark"}
async function foilReviewContext(order) {
  const session = await client.sessions.get(order.foilSessionId);
  const anonymity = session.network.anonymity;

  return {
    riskScore: session.decision.risk_score,
    deviceId: session.visitor_fingerprint?.id ?? null,
    deviceFirstSeenAt: session.visitor_fingerprint?.lifecycle.first_seen_at ?? null,
    anonymizedNetwork:
      anonymity.vpn || anonymity.proxy || anonymity.residential_proxy || anonymity.tor,
    ipCountry: session.network.location?.country_code ?? null,
    identitySpoofing: session.runtime_integrity.identity_spoofing,
    findings: session.highlights.map((highlight) => highlight.summary),
  };
}
```

```python Python theme={"dark"}
def foil_review_context(order):
    session = client.sessions.get(order.foil_session_id)
    fingerprint = session.visitor_fingerprint or {}
    anonymity = session.network["anonymity"]
    location = session.network.get("location") or {}

    return {
        "risk_score": session.decision.risk_score,
        "device_id": fingerprint.get("id"),
        "device_first_seen_at": fingerprint.get("lifecycle", {}).get("first_seen_at"),
        "anonymized_network": any(
            anonymity[key] for key in ("vpn", "proxy", "residential_proxy", "tor")
        ),
        "ip_country": location.get("country_code"),
        "identity_spoofing": session.runtime_integrity["identity_spoofing"],
        "findings": [highlight["summary"] for highlight in session.highlights],
    }
```

```go Go theme={"dark"}
type ReviewContext struct {
    RiskScore         int
    DeviceID          string
    DeviceFirstSeenAt *string
    AnonymizedNetwork bool
    IPCountry         *string
    IdentitySpoofing  string
    Findings          []string
}

func foilReviewContext(ctx context.Context, client *foil.Client, order Order) (ReviewContext, error) {
    session, err := client.Sessions.Get(ctx, order.FoilSessionID)
    if err != nil {
        return ReviewContext{}, err
    }

    anonymity := session.Network.Anonymity
    review := ReviewContext{
        RiskScore:         session.Decision.RiskScore,
        AnonymizedNetwork: anonymity.VPN || anonymity.Proxy || anonymity.ResidentialProxy || anonymity.Tor,
        IdentitySpoofing:  session.RuntimeIntegrity.IdentitySpoofing,
    }
    if fingerprint := session.VisitorFingerprint; fingerprint != nil {
        review.DeviceID = fingerprint.ID
        review.DeviceFirstSeenAt = fingerprint.Lifecycle.FirstSeenAt
    }
    if location := session.Network.Location; location != nil {
        review.IPCountry = location.CountryCode
    }
    for _, highlight := range session.Highlights {
        review.Findings = append(review.Findings, highlight.Summary)
    }

    return review, nil
}
```

```ruby Ruby theme={"dark"}
def foil_review_context(order)
  session = client.sessions.get(order.foil_session_id)
  anonymity = session[:network][:anonymity]

  {
    risk_score: session[:decision][:risk_score],
    device_id: session.dig(:visitor_fingerprint, :id),
    device_first_seen_at: session.dig(:visitor_fingerprint, :lifecycle, :first_seen_at),
    anonymized_network: anonymity.values_at(:vpn, :proxy, :residential_proxy, :tor).any?,
    ip_country: session.dig(:network, :location, :country_code),
    identity_spoofing: session[:runtime_integrity][:identity_spoofing],
    findings: session[:highlights].map { |highlight| highlight[:summary] },
  }
end
```

```php PHP theme={"dark"}
function foilReviewContext(Client $client, Order $order): array
{
    $session = $client->sessions()->get($order->foilSessionId);
    $anonymity = $session->network["anonymity"];

    return [
        "risk_score" => $session->decision["risk_score"],
        "device_id" => $session->visitor_fingerprint["id"] ?? null,
        "device_first_seen_at" => $session->visitor_fingerprint["lifecycle"]["first_seen_at"] ?? null,
        "anonymized_network" => $anonymity["vpn"] || $anonymity["proxy"]
            || $anonymity["residential_proxy"] || $anonymity["tor"],
        "ip_country" => $session->network["location"]["country_code"] ?? null,
        "identity_spoofing" => $session->runtime_integrity["identity_spoofing"],
        "findings" => array_column($session->highlights, "summary"),
    ];
}
```

```bash cURL theme={"dark"}
curl https://api.usefoil.com/v1/sessions/sid_... \
  -H "Authorization: Bearer sk_live_..."
```

The Sessions API uses different names for some decision fields. For example, the token's `verdict` is returned as `decision.automation_status`. For the full mapping, see [Verdicts & scoring](https://usefoil.com/docs/verdicts-and-scoring.md#using-verdicts-in-your-api).

Combine these fields with your own order data. Because you store the device ID with each order, you can also count how many customer accounts, cards, and shipping addresses have been used from the same device. The following are examples of rules that you can build:

* Hold the order for review if the device has placed orders under several customer accounts or with several different cards in the last 30 days.
* Hold the order for review if the IP address is in a different country from both the billing and shipping addresses and the connection went through a VPN or proxy.
* Hold the order for review if `identity_spoofing` is `elevated` or `high_risk`.
* Show the `highlights` summaries to the person reviewing the order.

Many legitimate customers use a VPN or shop while traveling, so treat network details as reasons to look more closely rather than as reasons to decline.

## Block devices after a fraud chargeback

When you receive a chargeback for fraud, or your team confirms that an order was fraudulent, add the order's device ID to your blocklist. The checkout example declines payments from blocked devices, so a person who returns with a new account and a different card is declined if they use the same device. The visitor fingerprint stays the same when the browser's cookies are cleared or it opens a private window, which makes it harder to evade than a cookie or an account.

A device can be shared by the people in a household, so a block can affect someone other than the person who committed the fraud. If this is a concern for your business, send payments from blocked devices to manual review instead of declining them.

The blocklist only applies to payments that carry a valid token, because a request without one has no device ID to check. A blocked person could avoid the check by calling your checkout endpoint without a token. The example sends those payments through 3-D Secure, and an attempt limit, if you add one, counts them by IP address. If that isn't enough for your risk level, decline payments that arrive without a valid token instead, and watch the share of those requests as described in [Roll out the policy](#roll-out-the-policy).

## Respond to disputes

When a customer disputes a charge, look up the Foil session stored with the order. The session shows the device, IP address, location, and network used for the purchase. If the same device ID or IP address appears on earlier orders from the same customer account that weren't disputed, include that history in your response.

Some card networks accept this kind of match as evidence against a fraud dispute. For example, Visa's Compelling Evidence 3.0 rules for card-not-present fraud disputes consider a device ID or IP address that matches earlier undisputed transactions on the same account. Your processor can tell you which evidence it accepts and how to submit it.

## Roll out the policy

Declines at checkout have a direct cost in lost sales, so run the policy in log-only mode before you enforce it. For about a week, verify tokens and record what the policy would have done without declining any payments, then compare the payments that it would have declined with your processor's outcomes and your dispute data.

During this period, also track the share of payment requests that arrive without a valid token. This share should stay small and steady. A sudden increase usually means that someone is calling your checkout endpoint directly without loading the page.

When the results look right, turn on the `bot` decline first, then the blocklist and any attempt limit. Add devices to the blocklist only for confirmed fraud, and start your review rules by holding orders rather than declining them. For a general rollout plan, see [Going to production](https://usefoil.com/docs/going-to-production.md).

## Common mistakes

* Calling the processor before you verify the token. The attempt then costs you an authorization fee and counts toward your decline rate, even if you cancel the order afterward.
* Treating a missing token as a `human` verdict. Scripts that call your checkout endpoint directly don't send a token, so a payment without a valid token needs its own handling.
* Skipping the token age check. Verification succeeds for a token of any age, so the age check is what prevents an attacker from reusing one captured token across many attempts.
* Returning a different response when Foil declines a payment. A distinct error tells a card-testing tool which attempts Foil stopped.
* Declining `inconclusive` sessions. Real customers sometimes receive an `inconclusive` verdict, so require 3-D Secure or another step-up check instead.
* Treating a `human` verdict as proof that a payment is legitimate. The verdict means that a person made the purchase, not that the card belongs to them, so keep your other fraud checks in place.
* Declining orders because of a VPN or proxy alone. Use network details to decide which orders to review.

## What's next

> [card] [Login protection](https://usefoil.com/docs/use-cases/login.md)
>
> Stop account takeover before an attacker reaches checkout.

> [card] [Promo abuse](https://usefoil.com/docs/use-cases/promo-abuse.md)
>
> Limit discount and referral abuse by device.

> [card] [Verdicts & scoring](https://usefoil.com/docs/verdicts-and-scoring.md)
>
> How verdicts and risk scores are assigned.

> [card] [Going to production](https://usefoil.com/docs/going-to-production.md)
>
> Move from log-only mode to enforcement.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.