php function to add subscriber to mailchimp api 3 0

Solutions on MaxInterview for php function to add subscriber to mailchimp api 3 0 by the best coders in the world

showing results for - "php function to add subscriber to mailchimp api 3 0"
Ben
24 Jan 2016
1<?php
2$data = [
3  'email'     => $email,
4  'status'    => 'subscribed',
5  'firstname' => $fname,
6  'lastname'  => $lname
7];
8
9function syncMailchimp($data) {
10  $apiKey = 'XXX';
11  $listId = 'XXX';
12
13  $memberId = md5(strtolower($data['email']));
14  $dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
15  $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
16
17  $json = json_encode([
18      'email_address' => $data['email'],
19      'status'        => $data['status'], // "subscribed","unsubscribed","cleaned","pending"
20      'merge_fields'  => [
21          'FNAME'     => $data['firstname'],
22          'LNAME'     => $data['lastname']
23      ]
24  ]);
25
26  $ch = curl_init($url);
27
28  curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
29  curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
30  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
31  curl_setopt($ch, CURLOPT_TIMEOUT, 10);
32  curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
33  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
34  curl_setopt($ch, CURLOPT_POSTFIELDS, $json);                                                                                                                 
35
36  $result = curl_exec($ch);
37  $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
38  curl_close($ch);
39
40  return $httpCode;
41}
42
43syncMailchimp($data);
44
45?>