如何从枪口中获取JSON响应

时间:2018-09-22 11:07:58

标签: php laravel guzzle

我正在获取API响应,但发现很难得到Json响应,

以下是异常消息: enter image description here

这是代码库

 try{
            $client = new Client([
                "base_uri"=> $this->base_uri,
                'connect_timeout' => 10
            ]);

        $response = $client->request(
                        "POST",
                       "https://creditswitch.net/api/v1/". $this->airtimeURI, 
                        ['json'=>[
                            'loginId'=>$this->loginId, 
                            'key'=>$this->publicKey,
                            'checksum'=>$airtimeChecksum,
                            "serviceId"=>$this->airtimeServiceId[$data["network"]],
                            "requestId"=>Paystack::genTranxRef(),
                            "date"=> Carbon::now()->toDateTimeString(),
                            "recipient"=>$data["mobile_number"],
                            "amount"=>$data["amount"],
                            ]
                        ]);
        $response->statusCode();
    }

    catch(RequestException $ex){
        $message = $ex;
        dd($ex);

    }
}

然后我尝试解码消息时,它给出一个空值作为响应:

    catch(RequestException $ex){
        $message = $ex;
        dd(json_decode($ex->getMessage()));

    }

2 个答案:

答案 0 :(得分:1)

您需要使用标头发送API密钥或用户名密码

try{

            $client = new Client([
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                    'Authorization' => 'Basic base64_encode('api_key'))
                 ],
                "base_uri"=> $this->base_uri,
                'connect_timeout' => 10
            ]);

        $response = $client->request(
                        "POST",
                       "https://creditswitch.net/api/v1/". $this->airtimeURI, 
                        ['json'=>[
                            'loginId'=>$this->loginId, 
                            'key'=>$this->publicKey,
                            'checksum'=>$airtimeChecksum,
                            "serviceId"=>$this->airtimeServiceId[$data["network"]],
                            "requestId"=>Paystack::genTranxRef(),
                            "date"=> Carbon::now()->toDateTimeString(),
                            "recipient"=>$data["mobile_number"],
                            "amount"=>$data["amount"],
                            ]
                        ]);
        return json_decode($response->getBody()->getContents(), true);
    }

    catch(RequestException $ex){
        $apiResponse = json_decode($response->getBody()->getContents(), true);
        return $apiResponse['message']
    }
}

答案 1 :(得分:0)

您可以通过调用POST /从异常中获取响应,然后像平常的响应一样使用它。

/foo