php - 如何从 guzzle 获取 json 响应
问题描述
我正在获取 API 响应,但我发现很难获得 Json 响应,
这是代码库
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);
}
}
然后,当我尝试解码消息时,它会给出 null 作为响应:
catch(RequestException $ex){
$message = $ex;
dd(json_decode($ex->getMessage()));
}
解决方案
您需要使用标头发送 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']
}
}