Issue
I'm working with a vendors API and the documentation is a little sparse.
They are looking for a post formatted like this.
{"import":{"members":[{"organization_customer_identifier":"XXXXXX","program_customer_identifier":"XXXXXX","member_customer_identifier":"XXX-XXX-XXXX","first_name":"Mister","last_name":"Tester","email_address":[email protected],"member_status":"OOOO","record_identifier":"XXX"}]}}'
My code is submitting it like this:
{"members":{"organization_customer_identifier":"XXXXXX","program_customer_identifier":"XXXXXX","member_status":"OOOO","member_customer_identifier":"XXX-XXX-XXXX","first_name":"Mister","last_name":"Tester","email_address":"[email protected]","record_identifier":"XXX"}}
I'm not that versed in using PHP to submit to an API with json/curl... as I understand it "import" is object and "members" is the array, I am missing the object. their examples have only shown expected results. their example results show multiple entries in the members array, I will only be submitting one member as they register. So I have no need to roll through an array of members.
Here is my PHP.
$url = 'https://api-domain.com/import';
$ch = curl_init($url);
$data = array(
'organization_customer_identifier' => 'XXXXX',
'program_customer_identifier' => 'XXXXXX',
'member_status' => 'OOOO',
'member_customer_identifier' => 'PPPPPPPPPP',
'first_name' => 'Mister',
'last_name' => 'Tester',
'email_address' => '[email protected]',
'record_identifier' => 'XXX'
);
$payload = json_encode(array("import" => $data));
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json', 'Access-Token: xxxxxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
Solution
you're missing the members
array.
$data = ['members' => [[
'organization_customer_identifier' => 'XXXXX',
'program_customer_identifier' => 'XXXXXX',
'member_status' => 'OOOO',
'member_customer_identifier' => 'PPPPPPPPPP',
'first_name' => 'Mister',
'last_name' => 'Tester',
'email_address' => '[email protected]',
'record_identifier' => 'XXX'
]]];
$payload = json_encode(["import" => $data]);
To get the correspondence between JSON and PHP arrays, each []
or {}
in the JSON corresponds to a PHP array, which is in []
in either case. {}
corresponds to associative arrays; the keys are the same, but PHP uses =>
instead of :
.
So when you see "members":[{
in the JSON, that corresponds to "members" => [[
in PHP.
Answered By - Barmar Answer Checked By - Candace Johnson (WPSolving Volunteer)