【问题标题】:POSTing JSON with GuzzleHttp\Client: returning 401 Unauthorized error使用 GuzzleHttp\Client 发布 JSON:返回 401 Unauthorized 错误
【发布时间】:2016-03-10 15:10:39
【问题描述】:

我正在尝试为支付网关 API 创建一个包装器。我选择使用GuzzleHttp。这是我目前拥有的基本代码。由于网关希望输入是通过 HTTP POST 发送的 JSON 格式,我尝试了两种可能的方法:

  1. 使用json 选项并为其分配一个基于键的数组。
  2. content-type 显式设置为application/json 并通过body 发送一个json 格式的字符串。

代码:

$client = new Client([
          'base_uri' => 'https://sandbox.gateway.com',
]);

$input = [
        'merchant_id' => '12345-33445',
        'security_key' => '**********',
        'operation' => 'ping',
    ];


$clientHandler = $client->getConfig('handler');
$tapMiddleware = Middleware::tap(function ($request) {
    foreach($request->getHeaders() as $h=>$v){
        echo $h . ': ' . print_r($v) . PHP_EOL;
    }
});

try {
    $response = $client->post(
        '/pg/auth',
        [
            'timeout' => 30,
            'headers' => [
                'Content-Type' => 'application/json',
                'Cache-Control' =>  'no-cache',
            ],
            'body' => json_encode($input),
            'debug' => true,
            'handler' => $tapMiddleware($clientHandler)
        ]
    );

    print_r($response);
} catch(Exeption $e){
    print_r($e);
}

不幸的是,尽管凭据正确,网关还是返回了 401 错误。我怀疑发送请求的方式有问题。我得出了这个结论,因为从tap 函数中打印的标题都是arrays(尤其是content-type)而不是字符串。不像这里描述的http://guzzle.readthedocs.org/en/latest/request-options.html?highlight=request#json

Array
(
    [0] => GuzzleHttp/6.1.1 curl/7.43.0 PHP/5.5.29
)
User-Agent: 1
Array
(
    [0] => sandbox.gateway.com
)
Host: 1
Array
(
    [0] => application/json
)
Content-Type: 1

【问题讨论】:

    标签: php json guzzle6


    【解决方案1】:

    按照建议发送请求怎么样?

    $client = new Client([
        'base_uri' => 'https://sandbox.gateway.com',
    ]);
    
    $client->request('POST', '/pg/auth', [
        'timeout' => 30,
        'debug' => true,
        'json' => [
            'merchant_id' => '12345-33445',
            'security_key' => '**********',
            'operation' => 'ping',
        ],
    ]);
    

    有关参考,请参阅http://docs.guzzlephp.org/en/latest/request-options.html#json

    【讨论】:

    • 也试过了。一样。看起来这正是标头的发送方式,现在我想知道为什么文档没有涵盖它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-03
    • 1970-01-01
    相关资源
    最近更新 更多