Created
March 11, 2018 01:31
-
-
Save seanbehan/1e8bde5597cb2a0e12d53621e9f8a652 to your computer and use it in GitHub Desktop.
Send Users to a Mailchimp List w/ Custom Fields in Pure PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$API_KEY = '[Mailchimp API Key Goes Here]'; | |
$LIST_ID = "[Mailchimp List ID Here]"; | |
$AUTH_HEADER = "Authorization: Basic ".base64_encode("anystring:".$API_KEY)."\r\nContent-type: application/x-www-form-urlencoded\r\n"; | |
// Prob. fetched from db.. | |
$list_of_users = [ | |
(object)["first" => "John", "last" => "Smith", "email" => "[email protected]", "color" => "red"], | |
(object)["first" => "Jane", "last" => "Doe", "email" => "[email protected]", "color" => "blue"] | |
]; | |
foreach($list_of_users as $user){ | |
$email = $user->email; | |
$email_hash = md5($email); | |
$merge_fields = [ | |
'FNAME' => $user->first, | |
'LNAME' => $user->last, | |
'COLOR' => $user->color // Custom fields have to be added in list settings first | |
]; | |
try { | |
// If the $url exists then we'll send a PATCH request to update | |
$url = "https://us2.api.mailchimp.com/3.0/lists/{$LIST_ID}/members/{$email_hash}"; | |
$context = stream_context_create([ 'http' => [ | |
'header' => $AUTH_HEADER, | |
'method' => "GET" | |
] | |
]); | |
if(@file_get_contents($url, true, $context)) { | |
$subscriber_info = json_encode([ | |
'email_address' => $email, | |
'status' => "subscribed", | |
'merge_fields' => $merge_fields | |
]); | |
$context = stream_context_create([ 'http' => [ | |
'header' => $AUTH_HEADER, | |
'method' => "PATCH", | |
'content' => $subscriber_info | |
] | |
]); | |
$resp = @file_get_contents($url, true, $context); | |
} else { | |
throw new Exception; | |
} | |
} catch (Exception $error){ | |
// They didn't exist so we can create a new subscriber member | |
$url = "https://us2.api.mailchimp.com/3.0/lists/{$LIST_ID}/members/"; | |
$subscriber_info = json_encode([ | |
'email_address' => $email, | |
'status' => "subscribed", | |
'merge_fields' => $merge_fields | |
]); | |
$context = stream_context_create([ 'http' => [ | |
'header' => $AUTH_HEADER, | |
'method' => "POST", | |
'content' => $subscriber_info | |
] | |
]); | |
$resp = @file_get_contents($url, true, $context); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment