Skip to content

Instantly share code, notes, and snippets.

@gthayer
Last active July 1, 2017 13:51
Show Gist options
  • Save gthayer/4fb53c1d30f8ec33c7cffb659d5a7814 to your computer and use it in GitHub Desktop.
Save gthayer/4fb53c1d30f8ec33c7cffb659d5a7814 to your computer and use it in GitHub Desktop.
/*
* Mailchimp API Calls
* V. 3.0
*/
//Push users to mailchimp on GF form completion
function mailchimp_newsletter_push_form_8($entry, $form) {
$list_id = '';
$email = $entry[3];
$subscriber = mailchimp_get_subscriber( $list_id, $email );
// If subscriber does not exist, create one.
if ( ! isset( $subscriber['id'] ) ) {
$subscriber = array();
$subscriber['status'] = "subscribed";
$subscriber['email_address'] = $email;
$subscriber['list_id'] = $list_id;
} else {
$subscriber['status'] = "subscribed";
}
$response = mailchimp_update_subscriber( $list_id, $email, $subscriber );
}
add_action( 'gform_after_submission_8', 'mailchimp_newsletter_push_form_8', 10, 2 );
function mailchimp_get_lists() {
mailchimp_api_call( $data, "/lists", 'GET' );
}
function mailchimp_get_subscriber( $list_id, $email ) {
$emailhash = md5( strtolower( $email) );
$url = "/lists/" . $list_id . "/members/" . $emailhash;
$response = mailchimp_api_call( $data, $url, 'GET' );
return $response;
}
function mailchimp_update_subscriber( $list_id, $email, $subscriber ) {
$emailhash = md5( strtolower( $email) );
$url = "/lists/" . $list_id . "/members/" . $emailhash;
$response = mailchimp_api_call( $subscriber, $url, 'PUT' );
return $response;
}
function mailchimp_api_call( $data, $json_url, $request = 'GET' ) {
$domain = "https://usx.api.mailchimp.com/3.0";
$username = "username";
$key = "key-usx";
$json_body = json_encode($data, JSON_FORCE_OBJECT | JSON_PRETTY_PRINT);
$header[] = "Content-type: application/json";
$connection = curl_init("$domain/$json_url");
curl_setopt($connection, CURLOPT_RETURNTRANSFER, true);
curl_setopt($connection, CURLOPT_HTTPHEADER, $header);
curl_setopt($connection, CURLOPT_HEADER, false);
curl_setopt($connection, CURLOPT_USERPWD, $username . ':' . $key);
curl_setopt($connection, CURLOPT_POST, true);
curl_setopt($connection, CURLOPT_POSTFIELDS, $json_body);
curl_setopt($connection, CURLOPT_CUSTOMREQUEST, $request);
curl_setopt($connection, CURLOPT_VERBOSE, 1);
$response = json_decode(curl_exec($connection), true);
return $response;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment