php 8.6实现json-rpc 2.0接口,关键是保留json对象与数组的区别,并区分有id的请求和没有id的通知。通知不返回结果,批量请求只返回需要响应的项;空批次则是invalid request。下面给出只提供ping方法的http示例。

官方文档:4 Request object
按协议建立响应函数
将下面内容保存为public/rpc.php。这里使用stdClass识别JSON对象,限制请求体大小和批次数量;业务方法用固定分发表,不把method当作任意PHP函数执行。
<?php
function errorResult(int $code, string $message, mixed $id = null): array {
return ['jsonrpc'=>'2.0','error'=>['code'=>$code,'message'=>$message],'id'=>$id];
}
function dispatch(mixed $r): ?array {
if (!$r instanceof stdClass) return errorResult(-32600, 'Invalid Request');
$hasId = property_exists($r, 'id');
$id = $hasId ? $r->id : null;
if (($r->jsonrpc ?? null) !== '2.0' || !is_string($r->method ?? null)
|| ($hasId && !is_int($id) && !is_string($id) && $id !== null)
|| (property_exists($r, 'params') && !is_array($r->params) && !$r->params instanceof stdClass)) {
return errorResult(-32600, 'Invalid Request');
}
$reply = match ($r->method) {
'ping' => property_exists($r,'params') && (array)$r->params !== []
? errorResult(-32602,'Invalid params',$id)
: ['jsonrpc'=>'2.0','result'=>'pong','id'=>$id],
default => errorResult(-32601,'Method not found',$id)
};
return $hasId ? $reply : null;
}
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405); header('Allow: POST'); exit;
}
$raw = file_get_contents('php://input', false, null, 0, 1048577);
if ($raw === false || strlen($raw)>1048576) { http_response_code(413); exit; }
try {
$input = json_decode($raw, false, 64, JSON_THROW_ON_ERROR);
} catch (JsonException $e) {
echo json_encode(errorResult(-32700,'Parse error')); exit;
}
if (is_array($input)) {
if ($input === []) $output = errorResult(-32600,'Invalid Request');
elseif (count($input)>100) { http_response_code(413); exit; }
else {
$output = [];
foreach ($input as $request) {
$response = dispatch($request);
if ($response !== null) $output[] = $response;
}
if ($output === []) { http_response_code(204); exit; }
}
} else $output = dispatch($input);
if ($output === null) { http_response_code(204); exit; }
echo json_encode($output, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE);
官方文档:6 Batch
分别验证请求、通知与批量调用
启动本地开发服务器后,依次提交以下请求体。第一项返回id为1的pong;第二项没有id,返回HTTP 204;混合批次只返回带id的那一项。
{"jsonrpc":"2.0","method":"ping","id":1}
{"jsonrpc":"2.0","method":"ping"}
[{"jsonrpc":"2.0","method":"ping"},{"jsonrpc":"2.0","method":"ping","id":"a"}]不要把无效对象当成通知
缺少id的有效请求是通知,但缺少jsonrpc或method类型错误的对象仍是Invalid Request。id:null虽然允许,规范并不推荐使用;不要用empty(id)判断是否有响应,否则0和空字符串会被误判。批次返回顺序也不应被客户端当成关联依据,应按id匹配。
exa-js 是 Exa 官方 JavaScript 软件开发工具包,Exa 是一个为 AI 工作流构建的网络搜索 API。它为代理提供了一种具体的方式来搜索网络、检索页面内容,并从代码中生成有来源的答案,而不是手动拼接原始 HTTP 调用。
增加业务方法时保留错误边界
实际方法应逐个校验命名参数或位置参数,并将可预期的参数错误映射为-32602,未预期异常映射为-32603且不返回堆栈。身份验证、限流和写操作幂等性属于应用层,不能因为采用JSON-RPC就省略。
立即学习“PHP免费学习笔记(深入)”;


















