PHP cURL JSON data to MailChimp Endpoint - PixelPowerLLC/NinjaForms---Addon-MailChimp-Multi-Referral GitHub Wiki
CodexWorld Reference Citation
I used this CodexWorld post as a reference.
MailChimp Members Endpoint POST JSON Data
The entire code for this solution is placed in the WordPress functions.php theme file. This solution posts data multiple times to the same endpoint therefore, the code is in a reusable function.
Posting JSON data to the members endpoint will create a new contact. This example show how to execute the cURL post passing the data payload from the WordPress Hook function.
How to Build a JSON payload with Ninja Forms Data
function postContact($payload)
{
// MailChimp URL members endpoint
// https://{sub domain from your api key}.api.mailchimp.com/3.0/lists/{list_id}/members
$url = {build your mailchimp member endpoint url from the example above}
$username = 'any text here';
$password = 'your MailChimp API key here';
// Create a new cURL resource
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
// Attach encoded JSON string to the POST fields
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
// Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
// Return response instead of outputting
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Execute the POST request
$result = curl_exec($ch);
// For testing you can use error_log which will write out to the WordPress logs folder.
// There will be a WordPress PHP errors log file.
// error_log(print_r($result, TRUE));
// Close cURL resource
curl_close($ch);
}