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

PHP调用Dutchie GraphQL API遇Mutation类未找到问题的解决方法

问题解决步骤

1. 修复「Class 'Mutation' not found」错误

你的代码里用了Mutation类但没引入对应命名空间,需要添加:

use GraphQL\Mutation;

另外注意:你提到的webonyx/graphql-php主要用来搭建GraphQL服务端,不是做客户端发请求的工具。你代码里的GraphQL\Client「GraphQL\Mutation其实来自graphql/client这个独立包,得先确保用Composer装了它:

composer require graphql/client

2. 确认Ping的操作类型:Query还是Mutation?

Ping一般是**查询(Query)**而非突变(Mutation),如果Postman里发的是查询请求,得把代码改成用Query类:

use GraphQL\Query;

// 创建GraphQL查询(替换原来的Mutation)
$gql = (new Query('ping'))
    ->setSelectionSet([
        'id',
        'time',
    ]);

3. 修正Authorization头格式

你的Authorization头里多了空格:"public- eyJhbGciOiJIUzI1NiJ9.",得和Postman里的格式完全一致,去掉多余空格:

$client = new Client(
    'https://plus.dutchie.com/plus/2021-07/graphql',
    ["Authorization" => "public-eyJhbGciOiJIUzI1NiJ9."]
);

4. 修正结果获取逻辑

你代码里尝试获取$results->getData()->pokemon,但你的查询是ping,所以要对应ping字段:

// 正确获取ping的返回结果
var_dump($results->getData()->ping);

完整修正后的代码

<?php
include("library/graphQL/vendor/autoload.php");

use GraphQL\Client;
use GraphQL\Exception\QueryError;
use GraphQL\Query; // 引入Query类(如果是查询操作)

$client = new Client(
    'https://plus.dutchie.com/plus/2021-07/graphql',
    ["Authorization" => "public-eyJhbGciOiJIUzI1NiJ9."] // 修正空格问题
);

// 创建GraphQL查询(Ping是查询而非Mutation)
$gql = (new Query('ping'))
    ->setSelectionSet([
        'id',
        'time',
    ]);

try {
    $results = $client->runQuery($gql);
} catch (QueryError $exception) {
    print_r($exception->getErrorDetails());
    exit;
}

// 显示原始响应
var_dump($results->getResponseObject());

// 获取ping的结果
var_dump($results->getData()->ping);

// 转为数组格式
$results->reformatResults(true);
print_r($results->getData()['data']['ping']);

额外说明

  • 如果Postman里确实是发Mutation请求,再改用Mutation类并添加use GraphQL\Mutation;
  • 确保你的API密钥和Postman里用的完全一致,别打错
  • 要是只想用webonyx/graphql-php,得自己用Guzzle这类HTTP库发POST请求,手动构造GraphQL请求体,示例如下:
use GuzzleHttp\Client as GuzzleClient;
use GraphQL\Language\Parser;
use GraphQL\Language\Printer;

$guzzle = new GuzzleClient();
$query = Printer::doPrint(Parser::parse('{ ping { id time } }'));

$response = $guzzle->post('https://plus.dutchie.com/plus/2021-07/graphql', [
    'headers' => [
        'Authorization' => 'public-eyJhbGciOiJIUzI1NiJ9.',
        'Content-Type' => 'application/json',
    ],
    'json' => [
        'query' => $query,
    ],
]);

$result = json_decode($response->getBody(), true);
print_r($result);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:40:22