【发布时间】:2015-11-20 21:31:17
【问题描述】:
我正在尝试使用 curl 将数据发布到 api,它必须是 JSON。 现在我有一个多维数组,我需要将它与帖子一起传递。但是我总是遇到同样的错误,我不知道为什么。
我已经尝试了所有我能想到的方法。
这是我需要发送到 API 的示例:
POST /orders/ HTTP/1.1
Authorization: Basic aHVudGVyMjo=
Content-Type: application/json
{
"currency": "EUR",
"amount": 99,
"return_url": "http://www.example.com/",
"transactions": [
{
"payment_method": "ideal",
"payment_method_details": {
"issuer_id": "INGBNL2A"
}
}
]
}
所以我的数组是这样的:
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"]["payment_method"] = "ideal";
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = "INGBNL2A";
然后我要做的就是通过以下代码将数组转换为 JSON 字符串:
$data_string = json_encode($post_fields);
到目前为止一切正常,但接下来我将使用以下代码将数据发布到 API:
$url = "https://api.kassacompleet.nl/v1/orders/";
$curl_header = array();
$curl_header[] = "Authorization: Basic ".base64_encode("$auth_code:");
$curl_header[] = "Content-type: application/json";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
这总是会导致如下所示的错误:
{ "error": { "status": 400, "type": "", "value": "{u'payment_method': u'ideal', u'payment_method_details': {u'issuer_id': u'INGBNL2A'}} is not of type u'array'" } }
谁能告诉我它来自哪里以及我做错了什么? 是数组的格式还是什么?
【问题讨论】:
-
通常你需要提供
CURLOPT_POSTFIELDS一个http查询字符串或一个php数组,它将变成一个http查询字符串。 -
@JonathanKuhn 你是想说我不需要将它作为 JSON 发送吗?