首页 > 解决方案 > 如何从 POST 请求中正确输出特定的 cURL 响应

问题描述

我正在运行一个 cURL 发布请求,该请求似乎命中了 url 并返回了响应。但是,我被引导相信我没有正确处理请求输出并且它抛出了一个我不理解的错误。我对 cURL 非常陌生,如果有人能指出我正确的方向,我将不胜感激。

$curl = curl_init();

$headers = array(
    'Content-Type: application/json',
    'X-Requested-With: XMLHttpRequest',
);

curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'XXX',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => [
        client_id => 'XXX',
        client_secret => 'XXX',
        member_id => 'XXX'
    ],
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);

$resp = curl_exec($curl);

curl_close($curl);

var_dump(json_decode($resp, true));

这会导致以下错误:

{"errors":{"":["Input string '--------------------------cec6101ba64bcb7f' is not a valid number. Path '', line 1, position 42."]},"title":"One or more validation errors occurred.","status":400,"traceId":"80031695-0002-ef00-b63f-84710c7967bb"}

标签: phpcurl

解决方案


$curl = curl_init();

$headers = array(
    'Content-Type: application/json',
    'X-Requested-With: XMLHttpRequest',
);
//////
 Adding this and using json_encode allowed for the request to be properly sent with the required id's and secret tokens.
//////
$data = array(
    "ClientId" => "$api_clientId" ,
    "ClientSecret" => "$api_clientSecret",
    "MemberId" => "$api_memberId"
);
$data_string = json_encode($data);

curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_URL => 'https://cors-anywhere.herokuapp.com/https://staging.micromerchantsystems.com/authenticationservice/api/GateKeeper/createtoken',
    CURLOPT_POST => 1,
    CURLOPT_POSTFIELDS => $data_string,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_HTTPAUTH => CURLAUTH_BASIC
]);

$resp = curl_exec($curl);

curl_close($curl);

var_dump(json_decode($resp, true));

推荐阅读