使用GuzzleHttp \ Client发布JSON:返回401 Unauthorized错误

时间:2015-12-05 18:46:58

标签: php json guzzle6

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

  1. 使用json选项并为其分配基于密钥的数组。
  2. 明确将content-type设置为application/json并通过body发送json格式的字符串。
  3. 代码:

    $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
    

0 个答案:

没有答案
相关问题