Skip to content

Instantly share code, notes, and snippets.

@butlerblog
Last active November 24, 2021 18:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save butlerblog/b372301e671ead8a291f32a43ee50a11 to your computer and use it in GitHub Desktop.
Save butlerblog/b372301e671ead8a291f32a43ee50a11 to your computer and use it in GitHub Desktop.
#Mailchimp list subscribe "put" request
<?php
/**
* Utility function to subscribe a user to a MailChimp
* list using the MC API 3.0
*
* @param array $args {
* Array of settings.
*
* @type string $api_key Your MailChimp API key.
* @type string $list_id Your MailChimp List ID.
* @type string $email The email you are subscribing to the list.
* @type string $status The status you are setting the user as (subscribed|unsubscribed|cleaned|pending).
* @type array $merge_fields {
* Merge field values.
*
* @type string $FNAME MC default for user first name.
* @type string $LNAME MC default for user last name.
* }
* }
*/
function sync_to_mailchimp( $args ) {
$member_id = md5( strtolower( $args['email'] ) );
$data_center = substr( $args['api_key'], strpos( $args['api_key'], '-' ) +1);
$url = 'https://' . $data_center . '.api.mailchimp.com/3.0/lists/' . $args['list_id'] . '/members/' . $member_id;
$json = json_encode([
'email_address' => $args['email'],
'status' => $args['status'], // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => $args['merge_fields']
]);
$ch = curl_init( $url );
curl_setopt( $ch, CURLOPT_USERPWD, 'user:' . $args['api_key'] );
curl_setopt( $ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json'] );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_TIMEOUT, 10 );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, 'PUT' );
curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $json );
$result = curl_exec( $ch );
$http_code = curl_getinfo( $ch, CURLINFO_HTTP_CODE );
curl_close( $ch );
return $http_code;
}
<?php
// Example of how to use the sync_to_mailchimp() function.
$args = array(
'api_key' => 'your api key',
'list_id' => 'your list id',
'email' => 'johndoe@example.com',
'status' => 'subscribed', // "subscribed","unsubscribed","cleaned","pending"
'merge_fields' => array(
'FNAME' => 'first_name',
'LNAME' => 'last_name',
)
);
$result = sync_to_mailchimp( $args );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment