---
title: "sdk/php"
description: "PHP 8.1+ 服务端 SDK，提供 networkless JWT 验证、PSR-7 请求认证和 webhook 签名校验。"
locale: "zh-Hans"
---

> Documentation Index
> Fetch the locale documentation index at: https://xid.dev/zh-hans/llms.txt
> Use this file to discover all available pages before exploring further.

# sdk/php

## 状态

已在本地实现并验证。针对真实 XID 实例的 IdP 往返验证（JWKS 获取、token 签名/验证）尚未执行，生产使用前必须完成。

## 安装

需要 PHP 8.1+。核心依赖由 Composer 自动拉取。

```shell
composer require xid/xid
```

## 快速开始

```php
use Xid\XidClient;
use Xid\Exception\TokenException;
use Xid\Exception\JwksException;

$xid = new XidClient([
'issuer'   => 'https://xid.dev',
'audience' => 'your-client-id',
'cache'    => $psrSimpleCacheImpl, // PSR-16; null disables JWKS cache
]);

try {
$claims = $xid->verifyToken($jwtString);
echo $claims->sub();    // user ID
echo $claims->scope();  // "openid profile email"
echo implode(',', $claims->amr()); // "phr" / "otp"
} catch (TokenException $e) {
http_response_code(401);
} catch (JwksException $e) {
http_response_code(503);
}
```

## 认证 PSR-7 请求

```php
$result = $xid->authenticateRequest($psrRequest);

if ($result->isAuthenticated()) {
$userId = $result->claims()->sub();
} else {
// $result->reason() for server-side logs only
http_response_code(401);
}
```

## 验证 webhook

```php
use Xid\Exception\WebhookException;

try {
$payload = $xid->verifyWebhook($psrRequest, 'whsec_...');
$type = $payload->type();  // "user.created"
$data = $payload->data();
} catch (WebhookException $e) {
http_response_code(400);
}
```

## XidClient 选项

| 密钥 | 默认 | 描述 |
| --- | --- | --- |
| `issuer` | 必填 | XID 签发方 URI |
| `audience` | `null` | 期望的受众；null 跳过验证 |
| `cache` | `null` | 用于 JWKS 缓存的 PSR-16 CacheInterface |
| `jwks_ttl` | `3600` | JWKS 缓存 TTL（秒） |
| `clock_leeway` | `0` | JWT 时钟偏差容忍度（秒） |
| `cookie_name` | `__xid_session` | 提取 token 的会话 cookie key |

## XidClient 方法

| 方式 | 返回值 | 描述 |
| --- | --- | --- |
| `verifyToken(string $token)` | `Claims` | 验证 JWT 字符串；失败时抛出异常 |
| `authenticateRequest(ServerRequestInterface $request)` | `AuthResult` | 认证 PSR-7 请求；不抛出异常 |
| `verifyWebhook(ServerRequestInterface $request, string $secret)` | `WebhookPayload` | 校验 webhook 签名；失败时抛出异常 |
| `refreshJwks()` | `void` | 强制刷新 JWKS 缓存 |

## 平台注意事项

- 使用 `firebase/php-jwt` 进行 ES256/RS256 验证。HS256 和 `none` 算法会被拒绝。
- `authenticateRequest` 和 `verifyWebhook` 需要 PSR-7 请求对象。如需请使用 PSR-7 bridge 转换框架原生请求。
- 异常层级：`XidException` -&gt; `TokenException`、`JwksException`、`WebhookException`。

Source: https://xid.dev/zh-hans/sdks/php/index.mdx
