Skip to main content

KYC SDK for PHP: Start a Session and Read the Decision

Didit's server SDK for PHP (didit-protocol/sdk-php, PHP 8.1+) starts a hosted KYC flow with one server call and returns the result through a signed webhook or the decision endpoint. A full ID check costs $0.33.

KYC SDK for PHP: Start a Session and Read the Decision

Contents

In this guide

Jump to the part you need.

This guide is for PHP developers who need a KYC check inside an app that already exists. The route we recommend is Didit's hosted verification flow, started by one server call from PHP, with the result read from a signed webhook or the decision endpoint. A full ID check costs $0.33. The caveat: the PHP SDK is a server SDK, so your API key stays on the server and never reaches the browser.

Last updated: November 26, 2026. Prices checked against the live Didit price feed on November 26, 2026.

KYC integration for PHP at a glance
ItemWhat to use
OutcomeYour PHP app creates a verification session, the user completes ID, liveness and face match in the hosted flow, your backend stores the decision
Official packagedidit-protocol/sdk-php on Packagist, plus guzzlehttp/guzzle
Minimum runtimePHP 8.1
Installcomposer require didit-protocol/sdk-php guzzlehttp/guzzle
Authenticationx-api-key header against https://verification.didit.me
Start a checkPOST /v3/session/ with a workflow id
Read the resultstatus.updated webhook, or GET /v3/session/{session_id}/decision/
PriceFull ID check (KYC) $0.33, AML screening $0.20 per check, SDK and Workflow Orchestrator free
TestingSandbox is free and unlimited on every plan, $10 of monthly credit for eligible work-email sign-ups

Start free in the sandbox at business.didit.me, no sales call. If you drive the build from an AI assistant, connect the Didit MCP server at didit.me/developers/mcp. The KYC product page is Free KYC by Didit and every unit price is on didit.me/pricing.

What you build, and why the hosted flow is the method

The Didit PHP SDK is one of the official server SDKs. It calls the server endpoints of the API reference with typed requests and responses, verifies the webhooks Didit sends you, and checks the tokens of Didit Authentication. Use it wherever your code holds an API key: creating verification sessions, reading decisions, calling the standalone APIs, managing users, businesses, workflows and cases, screening transactions and wallets, and the Travel Rule.

What it does not do is show the camera to your user. In the browser or a mobile app you use the web and native SDKs, which present the verification flow and never hold your API key. In a PHP integration the pattern is therefore three parts: a server call that creates the session, a redirect to the hosted verification link, and a webhook or decision fetch that brings the result back into your database. Your PHP code talks to verification.didit.me; the user talks to the hosted flow.

Keep the decision. GET /v3/session/{session_id}/decision/ returns the same decision object the webhook carries, with per-feature results in plural arrays and the warnings attached to them. Your PHP code stores that object against vendor_data, so you can re-read what a check returned later without asking the user to repeat the flow.

Walkthrough of the steps a user sees in a Didit verification: intro, document capture, face capture and result
What your user sees after you redirect to the session link: document capture, biometrics, then the result screen.

Prerequisites

  • PHP 8.1 or newer, and Composer. The official SDK needs PHP 8.1.
  • A Didit organization and application. Sign up at business.didit.me; the sandbox is free and unlimited.
  • A published KYC workflow and its workflow_id. Workflows live in the console sidebar; a simple workflow runs its steps in fixed order, a node-based workflow branches on results.
  • An API key from Developers then API keys. Sandbox keys start with sk_test_, live keys with sk_live_, both followed by 43 URL-safe characters.
  • An HTTPS endpoint that can receive a POST, if you want webhooks. Recommended.
  • The PHP cURL extension, if you call the REST endpoint directly instead of the SDK.

Step by step: a KYC session from PHP

  1. Create the organization and application. The application is the workspace that owns your workflows, keys and verification activity. Keys are scoped to it, so keep one application per project or environment.
  2. Build the workflow. Open Workflows, click New workflow, choose Verifying users, then describe what you need, start from a template, or start empty. Publish it and copy the workflow id.
  3. Copy the API key. Developers then API keys. The primary key is the application's own secret; create a separate scoped key for a service or partner. Store it as an environment variable, never in a repository.
  4. Install the SDK. Run the documented install command.
    composer require didit-protocol/sdk-php guzzlehttp/guzzle
  5. Set the environment. Every Didit SDK reads the same variables, so a client created with no options is ready to use. DIDIT_API_KEY covers every API key call, DIDIT_ORGANIZATION_ID and DIDIT_APPLICATION_ID cover the organization and application scoped routes, and DIDIT_LOG=debug logs method, path, status, duration and request id of every request (never bodies or headers). Create one client per process and share it; it keeps a connection pool and is safe across threads.
  6. Create the session from PHP. The documented request is POST https://verification.didit.me/v3/session/ with the x-api-key header. Through the SDK the same call is the sessions.create method on the client you configured, with the same fields, and the fallback read is sessions.retrieve_decision. The PHP SDK invocation for this endpoint sits on its server endpoint page of the API reference, next to the cURL request. The script below is the REST fallback, the version you can run without the SDK, and it sends the same fields.
    <?php
    // create-session.php   run with: php create-session.php
    $apiKey     = getenv('DIDIT_API_KEY');
    $workflowId = getenv('DIDIT_WORKFLOW_ID');
    
    $body = [
        'workflow_id' => $workflowId,
        'vendor_data' => 'user-42',
        'callback'    => 'https://myapp.com/kyc/return',
    ];
    
    $ch = curl_init('https://verification.didit.me/v3/session/');
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER     => [
            'x-api-key: ' . $apiKey,
            'Content-Type: application/json',
        ],
        CURLOPT_POSTFIELDS     => json_encode($body),
    ]);
    
    $raw    = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($status < 200 || $status >= 300) {
        throw new RuntimeException('Didit returned ' . $status . ': ' . $raw);
    }
    
    $session = json_decode($raw, true);
    // store $session['session_id'] against your user, then send the browser to the flow
    header('Location: ' . $session['url']);
    exit;
  7. Send the user to the flow. The create response carries session_id, url and session_token. Redirect the browser to url, or open it in the SDK or an iframe. Use vendor_data so the session binds to your own user id; it is also what duplicate detection uses across sessions.
  8. Register the webhook destination and verify what arrives. Create it with POST https://verification.didit.me/v3/webhook/destinations/, sending a label, a url and the events you want, for example status.updated and data.updated. Save the returned secret_shared_key as DIDIT_WEBHOOK_SECRET. Read the raw body before you parse JSON, check the timestamp, compare signatures with a constant-time function, answer 2xx within 5 seconds, and de-duplicate on event_id.
    <?php
    // webhook.php   POST target registered as a Didit webhook destination
    $secret = getenv('DIDIT_WEBHOOK_SECRET');
    $raw    = file_get_contents('php://input');
    $ts     = (int) ($_SERVER['HTTP_X_TIMESTAMP'] ?? 0);
    
    if (abs(time() - $ts) > 300) {
        http_response_code(400);
        exit;
    }
    
    // X-Signature-V2 is HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON
    function canonicalize($value) {
        if (!is_array($value)) {
            return $value;
        }
        if (array_keys($value) !== range(0, count($value) - 1)) {
            ksort($value, SORT_STRING);
        }
        foreach ($value as $key => $item) {
            $value[$key] = canonicalize($item);
        }
        return $value;
    }
    
    $body = json_decode($raw, true);
    $expected = hash_hmac(
        'sha256',
        json_encode(canonicalize($body), JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES),
        $secret
    );
    
    // accept the current header, and for 24 hours after a secret rotation its -Previous twin
    $candidates = array_filter([
        $_SERVER['HTTP_X_SIGNATURE_V2'] ?? '',
        $_SERVER['HTTP_X_SIGNATURE_V2_PREVIOUS'] ?? '',
    ]);
    
    $verified = false;
    foreach ($candidates as $sig) {
        if (hash_equals($expected, $sig)) {
            $verified = true;
        }
    }
    
    if (!$verified) {
        http_response_code(401);
        exit;
    }
    
    $event = $body;
    // $event['session_id'], $event['status'], $event['vendor_data']
    // $event['decision'] is present for Approved, Declined, In Review and Abandoned
    http_response_code(200);

    X-Signature-V2 is the recommended header: it is HMAC-SHA256 over the sorted, Unicode-preserved canonical JSON, so it keeps verifying when your framework re-encodes the body before your handler sees it. X-Signature over the exact raw bytes is the alternative and only works when the body reaches you unchanged. When a destination's signing secret is rotated, Didit also sends X-Signature-V2-Previous for 24 hours, made with the replaced secret; accepting a match on either header keeps verification working while you deploy the new secret.

  9. Keep a fallback. GET https://verification.didit.me/v3/session/{session_id}/decision/ returns the same decision the webhook carries. Use it when a delivery is dropped, or when a webhook verified with the deprecated X-Signature-Simple header, which authenticates the envelope but not the decision body.

Expected output

The create call returns the session id, the hosted link and a session token, with the session in Not Started until the user opens the link. Store the id, redirect to the link, and wait. The webhook envelope is the documented shape, trimmed here to the fields you will actually read:

{
  "event_id": "uuid",
  "session_id": "uuid",
  "status": "Approved",
  "webhook_type": "status.updated",
  "created_at": 1627680000,
  "timestamp": 1627680000,
  "application_id": "uuid",
  "environment": "live",
  "sandbox_scenario": null,
  "workflow_id": "uuid",
  "workflow_version": 1,
  "vendor_data": "user-42",
  "metadata": { "user_type": "premium" },
  "decision": { }
}

Status values are exact, case-sensitive strings. Note that Kyc Expired uses a single capital K. The decision mirrors the decision endpoint: per-feature results are in plural arrays such as id_verifications[], liveness_checks[], face_matches[] and aml_screenings[], because one workflow can hold several instances of the same check. Never assume the singular V2 fields.

A verification session overview in the Didit Business Console showing its status and warnings
The same session in the console: status, warnings and the checks that ran. This is what your webhook payload describes.

What each status means in your PHP code

Session statuses and the action your code takes
StatusWhat happenedWhat your code does
Not StartedSession created, link not openedWait, or send a reminder
In ProgressUser is working through the stepsNothing, show a waiting state
ApprovedAll checks passedGrant access, store the decision
DeclinedOne or more checks failed, warnings explain whyNotify the user; a reviewer may request a resubmission
In ReviewWarnings need a human decisionKeep it pending, do not auto-approve
ResubmittedUser asked to redo specific stepsWait for the next status
ExpiredLink timed out before it was openedCreate a new session
AbandonedStarted but not finished in timeCreate a new session or re-engage
Kyc ExpiredAn approved document passed its expiry dateAsk for a fresh verification

When verification fails: failure cases and recovery

Two different things get reported as a failed verification. The first is an HTTP or API error on the request itself: the session was never created, or the read was refused. The second is a session that ended as Declined, or that sits in In Review waiting on a person. Handle them differently.

Failure cases, cause and recovery
What you seeCauseRecovery
401 from verification.didit.mex-api-key missing, malformed, revoked or expiredRe-fetch the key with the login and organizations endpoints, or issue a new one in Developers then API keys
403 with "You do not have permission to perform this action."No key header, a scoped key without access to this resource, or a key called from an address outside its IP listUse a key whose scope covers the call; check the IP list
403 with application_deletedThe key's application was deletedDo not retry, the keys no longer exist; use a key of an existing application
400 on session createInvalid workflow_id, or a callback outside the application's allowed domainsCheck the published workflow id, and put the callback on an allowed origin or use an app deep link
404 on a session routeThe session sits outside the scoped key's workflows or statusesUse a key whose limits include that session
429Rate limitBack off for the seconds in the wait field, then retry
Webhook never arrivesHandler slower than 5 seconds, or it answered 5xx or 404Didit retries twice, after about 1 and 4 minutes, then drops the delivery. Resend it from the destination's delivery log, or fetch the decision
User says verification failedSession is Declined, or In Review and waiting on a personRead the warnings in the decision. If the issue is fixable, a reviewer requests a resubmission; otherwise create a new session after the fix
Liveness check results for one verification session in the Didit Business Console
A failed biometric check, read from the same decision your PHP code stores. The warning text is what you surface to support.

Inputs and outputs

Inputs: fields on POST /v3/session/
FieldRequiredWhat it does
workflow_idYesUUID of the published workflow. A KYC workflow creates a user verification session; a KYB workflow creates a business session on the same endpoint
vendor_dataRecommendedYour stable identifier for the user; binds the session and drives duplicate detection
callbackNoWhere the hosted flow sends the browser when it finishes. Must be on an allowed domain, or a custom app scheme
callback_methodNoinitiator, completer or both, when the callback sometimes fails to fire
metadataNoArbitrary JSON echoed in responses and webhooks, never shown to the user
languageNoISO 639-1 code for the verification UI; defaults to browser detection
contact_detailsNoPre-fills email and phone steps, optionally sends notification emails
expected_detailsNoExpected name, date of birth, nationality, document country. Mismatches surface as decision warnings
session_expiration_timeNoSeconds the link stays valid, 3600 to 2419200, overriding the workflow setting for this session
tagsNoUp to 10 tags, 50 characters each, for filtering in the console
Outputs: what comes back to PHP
OutputSourceWhat to do with it
session_idCreate responseStore it against the user; it is the key for the decision endpoint
urlCreate responseRedirect the browser, or open it in an iframe
session_tokenCreate responsePass to the front end if you drive the flow from there
statusWebhook or decisionMatch the exact string, case-sensitive, spaces included
decisionWebhook, or GET /v3/session/{session_id}/decision/Store the plural arrays: id_verifications[], liveness_checks[], face_matches[], aml_screenings[], poa_verifications[], phone_verifications[], ip_analyses[]
event_idWebhookDe-duplicate deliveries on this value

What costs money, and where a person steps in

Sandbox checks are mocked and free on every plan, so the loop of create, redirect and read costs nothing while you build. Live, you pay per completed check from prepaid credit. A full ID check bills as the sum of ID document verification $0.15, passive liveness $0.10, face match 1:1 $0.05 and device and IP analysis $0.03, which is $0.33. AML screening adds $0.20 per check, ongoing AML monitoring $0.07 per person a year, proof of address $0.20, and phone codes bill the carrier price plus Didit's $0.02 fee with Free plan credit not applying to them. The docs pricing page lists which no-match database lookups and retries are billable. SDKs, the Workflow Orchestrator and the MCP server are listed as free.

Review boundaries matter more than the price. Automated checks drive most status moves; a person steps in when a session reaches In Review, and a reviewer approves, declines or requests a resubmission in the console. Your PHP code should treat In Review as pending and let the reviewer's decision arrive as another status.updated event. An approved session moves to Kyc Expired when the verified document passes its expiry date, unless the expiration mode for that country and document type is set to allow expired documents, so plan a re-verification path before you ship.

Worked cost example

Academy lesson explaining Didit credits, auto-recharge and volume discounts
How billing works: per completed check, from prepaid credit, with plan credit added each month.

Say 10,000 users a month complete a full ID check, and every one of them also gets an AML screen. The figures below use published unit prices and ignore plan credit, so you can see the unit arithmetic.

  • Full ID checks: 10,000 x $0.33 = $3,300.00
  • AML screens: 10,000 x $0.20 = $2,000.00
  • List total: $3,300.00 + $2,000.00 = $5,300.00 for the month
  • Free plan credit: $10.00 / $0.33 = 30 full ID checks a month, $9.90 spent, $0.10 left unspent
  • Growth, 4% off each unit: $0.33 x 0.96 = $0.3168, 10,000 x $0.3168 = $3,168.00; $0.20 x 0.96 = $0.192, 10,000 x $0.192 = $1,920.00; plus the $99.00 monthly fee = $5,187.00
  • Scale, 10% off each unit: $0.33 x 0.90 = $0.297, 10,000 x $0.297 = $2,970.00; $0.20 x 0.90 = $0.18, 10,000 x $0.18 = $1,800.00; plus the $299.00 monthly fee = $5,069.00

Growth also carries $115 of credit a month and Scale $350, which offset that usage before top-ups are touched. Plan credit does not roll over; top-ups last 12 months. If you are moving an existing PHP integration from another provider, didit.me/switch shows what maps across, and 4,000+ companies are active Didit customers.

Sources

Your next step: create a free application in the Didit sandbox at business.didit.me, publish a KYC workflow, and run the create-session script above against your sk_test_ key. No sales call, and sandbox checks do not bill.

Try it

Try this in the sandbox

Run the check this guide describes, free.

ID Verification

The product this post is about, taken from its topic. Run it free in the sandbox.

$0.15 per checkStart free

Author

Alejandro Rosas

Co-founder and CTO

Alejandro Rosas

Alejandro Rosas

Co-founder and CTO

About Didit

Questions

Frequently asked questions

Is there an official Didit SDK for PHP?

Yes. The package is didit-protocol/sdk-php on Packagist, installed with composer require didit-protocol/sdk-php guzzlehttp/guzzle, and it needs PHP 8.1 or newer. It is a server SDK: it holds your API key and calls the server endpoints, while the browser flow is presented by the web or native SDKs. The current 1.0.1 release does not include the two Google Wallet endpoints; every other server endpoint is there.

How much does one KYC check cost from a PHP app?

A full ID check costs $0.33 per completed check, made up of ID document verification $0.15, passive liveness $0.10, face match 1:1 $0.05 and device and IP analysis $0.03. AML screening is $0.20 per check, so a KYC plus AML bundle is $0.53. Sandbox checks are mocked and free, and eligible work-email sign-ups get $10 of credit a month.

Why does my PHP request return 403 or 401?

A 401 on verification.didit.me means the x-api-key header is wrong, malformed, revoked or expired. A 403 means the header is missing, the scoped key lacks access to that resource, or the key was called from an address outside its IP list. Neither is a user verification failure: fix the key, then retry.

What does a Declined status mean, and how should PHP handle it?

Declined means one or more checks failed, and the decision carries warnings explaining which. Notify the user and store the decision; do not silently retry. A reviewer can request a resubmission, which moves the session to Resubmitted and sends the user back through the steps in the workflow.

Do I need a webhook if I can fetch the decision?

The webhook is the primary route and the decision endpoint is the fallback. Register a destination with status.updated and data.updated, verify the signature, answer within 5 seconds and de-duplicate on event_id. Then use GET /v3/session/{session_id}/decision/ when a delivery is dropped or when you need to re-read a decision later.

Can I embed the verification flow inside my PHP page instead of redirecting?

Yes. The create call returns a url, and the quick start says to redirect the user to it or open it in the SDK or an iframe. What you must not do is call the API from the browser with your key: keep the create call on the server and hand the front end only what it needs to show the flow.

How long does a verification session link stay valid?

By default the workflow's session expiration setting applies. You can override it per session with session_expiration_time, in whole seconds between 3600 and 2419200, which is one hour to four weeks. A session that times out before the user opens it ends as Expired; one that is started but not finished ends as Abandoned.

Where should the API key live in a PHP application?

In a server-side environment variable such as DIDIT_API_KEY, never in front-end code, a public repository or a client bundle. New keys start with sk_test_ for a sandbox application or sk_live_ for a live one, followed by 43 URL-safe characters, and older keys without a prefix keep working, so never validate a key by its prefix.

How do I test failed verifications without real documents?

Use a sandbox application. Every check is mocked there, testing is free and unlimited, and sandbox_scenario on session create reproduces a bundled outcome from the sandbox catalog, which you list with GET /v1/sandbox/scenarios/. The field is rejected with 400 on live applications, so a scenario can never leak into production.

Does the PHP SDK verify webhook signatures for me?

Yes. The server SDK overview lists webhook verification as something every SDK does. If you call the REST API directly instead, verify the signature yourself with the destination secret, following the webhooks page: X-Signature-V2 is the recommended header, and X-Signature works when your stack preserves the raw body.

Compliance built in

Audited, certified and attested.

We hold the certifications and build each country's rules into your flows, so you can launch anywhere without worrying. Security and Compliance center

  • Regulation encoded into your flows

    Tell us what you do and where. Didit lists the rules that apply to you, with sources, and builds the checks each country needs into one workflow.

  • Ready for AMLR

    Every requirement of the new EU anti-money laundering rules, from checking customers to human review, is already covered by a Didit check.

  • Tested in Spain's Treasury sandbox

    Spain's Treasury published its supervised sandbox report on Didit's NFC plus active liveness onboarding; SEPBLAC took part and valued the added measures positively.

  • Audited, not self-declared

    iBeta Level 1 and Level 2. Liveness tested under ISO/IEC 30107-3.

Compliance assistant

Your obligations · 3 regions

EU · AMLRCustomer due diligence, human reviewCovered
Illinois, Texas, ColoradoExplicit biometric consentCovered
Germany · Youth protectionVerified adults only (JMStV)Covered
Workflow checked. Every obligation is met
  • SOC 2 Type 2
  • ISO 27001
  • iBeta Level 1 and Level 2
  • EU regulator attestation
  • FSM youth protection
  • GDPR
  • EBA remote onboarding
  • MiCA compatible
  • FIDO Alliance member
  • AMLREU AML Regulation ready

Integration · Didit MCP

Run Didit from your own AI agent

Connect Didit to Claude, Cursor, VS Code or ChatGPT and just ask in plain words. Your agent can do anything you can do in the console, with the same permissions you have.

Add to ClaudeChatGPT
Didit Academy · Lesson 04 · Use Didit with MCP
  • Build workflowsDescribe the checks you need. The agent creates and publishes the flow.
  • Run investigationsAsk why a session was declined, review cases, search people and companies.
  • Change rulesCreate payment rules, test them on past data and switch them on.
  • Pull reportsAsk for numbers, exports or the audit log.

Verify your first user today.

Start free

Free sandbox. Credit applies to work-email sign-ups.