使用PHP OAuth Library调用API报400错误,求问题排查
The root cause of your error is double JSON encoding. Here's what's happening behind the scenes:
- You manually convert your
$fieldsarray to a JSON string usingjson_encode($fields). - Then you pass that string to
CallAPI, which (since you setRequestContentTypetoapplication/json) automatically encodes the input again into JSON.
The result is that your API receives a quoted string of your original JSON (like "{"lastName":"Smith"...}") instead of the actual JSON object it expects. That's why you get the error about converting a string to the required data type.
Corrected Code
Remove the manual json_encode step and pass the raw $fields array directly to CallAPI:
$params = array( 'x-api-key' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', 'Content-Type' => 'application/json', 'Accept' => 'application/json' ); $fields = array( "lastName" => $entries[$tmp_id]["2.6"], "firstName" => $entries[$tmp_id]["2.3"], "webAddresses" => array([ "value" => $entries[$tmp_id]["4"] ]), "phoneNumbers" => array([ "value" => $entries[$tmp_id]["5"] ]) ); // Remove the json_encode line here $success = $client->CallAPI( 'https://myurl.com/v2/api', 'POST', $fields, // Pass the array directly instead of $json array( 'FailOnAccessError'=>true, 'RequestHeaders' => $params, 'RequestContentType' => 'application/json', 'FollowRedirection' => true, ), $user );
Additional Check: Structure of webAddresses and phoneNumbers
Looking at the error message, the API is receiving webAddresses as a single object ({"value":"john@smith.com"}), but your code is sending it as an array of objects ([{"value":"john@smith.com"}]).
If the API expects a single address object (not an array), adjust those lines to remove the extra array layer:
"webAddresses" => array("value" => $entries[$tmp_id]["4"]), "phoneNumbers" => array("value" => $entries[$tmp_id]["5"])
Or using shorter PHP array syntax:
"webAddresses" => ["value" => $entries[$tmp_id]["4"]], "phoneNumbers" => ["value" => $entries[$tmp_id]["5"]]
This should resolve the 400 error by sending a properly formatted JSON object to your API.
内容的提问来源于stack exchange,提问作者troxxx

