我正在获取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);
}
}
然后我尝试解码消息时,它给出一个空值作为响应:
catch(RequestException $ex){
$message = $ex;
dd(json_decode($ex->getMessage()));
}
答案 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