You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP中使用curl_impersonate调用GraphQL API时filters参数语法求助

解决GraphQL getSearchResults查询的filters参数Bad Request问题

既然请求在Altair中能正常执行,核心问题大概率是PHP代码中filters参数的JSON序列化格式和Altair中的结构不一致,或者请求头/POST数据的编码存在问题。以下是具体排查和解决步骤:

1. 从Altair导出正确的参数结构

打开Altair中可正常运行的getSearchResults查询,复制完整的variables部分,示例结构如下:

{
  "filters": {
    "categoryId": "123",
    "priceRange": {
      "min": 0,
      "max": 100000
    },
    "sort": "price_asc",
    "availableOnly": true
  },
  "page": 1,
  "pageSize": 20
}

确保该结构在Altair中能返回正确结果,以此作为PHP参数的基准。

2. 在PHP中正确构建并序列化参数

PHP中用关联数组构建filters时,需保证嵌套结构完整,且JSON编码格式与Altair一致。示例代码:

// 构建符合要求的variables数组
$variables = [
    'filters' => [
        'categoryId' => '123', // 替换为实际需要的分类ID
        'priceRange' => [
            'min' => 0,
            'max' => 100000
        ],
        'sort' => 'price_asc',
        'availableOnly' => true
    ],
    'page' => 1,
    'pageSize' => 20
];

// 正确序列化JSON,避免不必要的转义
$postData = json_encode([
    'query' => 'query getSearchResults($filters: SearchFiltersInput!, $page: Int!, $pageSize: Int!) { getSearchResults(filters: $filters, page: $page, pageSize: $pageSize) { items { id name price } } }',
    'variables' => $variables
], JSON_UNESCAPED_SLASHES);

3. 配合curl_impersonate的请求配置

确保curl请求头与Altair完全一致,尤其是Content-Type、模拟浏览器的User-Agent、Referer等。示例curl调用:

$ch = curl_init('https://www.xxxlutz.hu/api/graphql');

curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// 模拟Chrome浏览器UA,适配curl_impersonate
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36');
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    'Content-Type: application/json',
    'Referer: https://www.xxxlutz.hu/',
    // 可添加Altair中显示的其他请求头,如必要的Cookie
]);

$response = curl_exec($ch);
curl_close($ch);

// 查看响应结果
var_dump($response);

4. 常见错误排查

  • 检查filters字段名与GraphQL schema完全匹配(注意大小写、拼写,比如availableOnly不能写成available_only)
  • 确认参数类型:min/max是数字类型,不要加引号;availableOnly是布尔值,不能写成字符串"true"
  • 用json_last_error()检查JSON编码是否存在语法错误
  • 用抓包工具对比Altair和PHP发送的请求体,排查格式差异

内容的提问来源于stack exchange,提问作者S7_

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 02:03:21