我正在尝试调用REST-API,但它仅返回“ BAD_REQUEST无法处理的JSON”。
我已经尝试按照下面的示例重写输入,但是它给了我同样的错误。
这是我用于发送请求的代码:
function callAPI($method, $url, $data)
{
$curl = curl_init();
$username = 'PK10008_e8f77aebdb0a';
$password = 'rwBmthNFK8JTbIL7';
switch($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, 1);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
}
//Options
curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json'
));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
$result = curl_exec($curl);
if(!$result)
{
die("Connection Failure");
}
curl_close($curl);
return $result;
}
这是我用来创建和发送信息的代码:
$data_array = array(
'purchase_country'=> 'SE',
'purchase_currency'=> 'SEK',
'locale'=> 'sv-SE',
'order_amount'=> 10,
'order_tax_amount'=> 0,
'order_lines' => array(
'type'=> 'physical',
'reference'=> '19-402',
'name'=> 'Test',
'quantity'=> 1,
'unit_price'=> 10,
'tax_rate'=> 0,
'total_amount'=> 10,
'total_discount_amount'=> 0,
'total_tax_amount'=> 0
)
);
$make_call = callAPI('POST', 'https://api.playground.klarna.com/payments/v1/sessions', json_encode($data_array));
$response = json_decode($make_call, true);
这是示例:
POST /payments/v1/sessions
Authorization: Basic pwhcueUff0MmwLShJiBE9JHA==
Content-Type: application/json
{
"purchase_country": "SE",
"purchase_currency": "SEK",
"locale": "sv-SE",
"order_amount": 10,
"order_tax_amount": 0,
"order_lines": [{
"type": "physical",
"reference": "19-402",
"name": "Battery Power Pack",
"quantity": 1,
"unit_price": 10,
"tax_rate": 0,
"total_amount": 10,
"total_discount_amount": 0,
"total_tax_amount": 0
}]
}
我得到的结果是这样的: '错误的请求 不可处理的JSON 1734c472-c9cb-4022-b469-a8231c7abeec'
但是我应该得到这样的东西:
HTTP/1.1 200 OK
Content-Type: application/json
{
"session_id": "068df369-13a7-4d47-a564-62f8408bb760",
"client_token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjAwMDAwMDAwMDAtMDAwMDAtMDAwMC0wMDAwMDAwMC0wMDAwIiwidXJsIjoiaHR0cHM6Ly9jcmVkaXQtZXUua2xhcm5hLmNvbSJ9.A_rHWMSXQN2NRNGYTREBTkGwYwtm-sulkSDMvlJL87M",
"payment_method_categories": [{
"identifier": "pay_later"
"name" : "Pay later.",
"asset_urls" : {
"descriptive" : "https://cdn.klarna.com/1.0/shared/image/generic/badge/en_us/pay_later/descriptive/pink.svg",
"standard" : "https://cdn.klarna.com/1.0/shared/image/generic/badge/en_us/pay_later/standard/pink.svg"
}
}]
}
答案 0 :(得分:0)
我遇到的问题是json_encode如何创建编码数组。代替此:"example":[{
"ex": "ex"
}]
它是这样做的:
"example":{
"ex": "ex"
}
这反过来使json对最终API不可读