14 Eylül 2012 Cuma

Mailchimp reconciliation

To contact us Click HERE

I spent much of today doing a basic implementation of the Mailchimp API into a client site. Individual actions can almost be copy/pasted from the examples but there is one more complicated wrinkle - the customers can unsubscribe from the newsletter via Mailchimp so periodically the two databases need reconciled.I suspect the proper way to do this is via a webhook for instant results but for today I just put a section in the daily cron. It worked first time which I was pretty pleased with.

[API class included at beginning of file]/** * mailchimp reconciliation * @var string $key * @var string $list * @var object $api */$key = 'your-api-key';$list = 'your-list-id'; //"Testing Activate"$api = new MCAPI($key);/** * @link http://apidocs.mailchimp.com/api/rtfm/listmembers.func.php * api listMembers($id, $status='subscribed', $since=NULL, $start=0, $limit=100) * @var array $remote_records */// 1000 records should be plenty to start with$remote_records = $api->listMembers($list, 'subscribed', NULL, 0, 1000); if($api->errorCode){ echo 'Unable to sync with Mailchimp - error '.$api->errorCode.': '.$api->errorMessage;} else{ /** * @var array $members * @var resource $local_records */ $members = array(); foreach($remote_records['data'] as $d) { //we put the data value in the key so we can easily remove it with unset() later $members[ $d['email'] ] = 1; } /* debugging print_r($remote_records); echo "\n"; print_r($members); echo "\n"; // */ $local_records = mysql_query("select user_id, email from users where newsletter = '1'"); /** * unset local newsletter flag for people who have unsubscribed * remove them from remote recordset */ if($local_records && mysql_num_rows($local_records) > 0) { while($l = mysql_fetch_assoc($local_records)) { if(!isset($members[ $l['email'] ])) { // has been removed from mailchimp mysql_query("update users set newsletter = '0' where user_id = '{$l['user_id']}'"); echo $l['email']." removed \n"; } unset($members[$l['email']]); } } /** * if there are any records remaining in remote recordset check for a matching local email and update */ foreach($members as $email => $n) { mysql_query("update users set newsletter = '1' where email = '$email'"); echo "$email added if a matching user exists \n"; }}

Hiç yorum yok:

Yorum Gönder