mailchimp.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. <?php
  2. /**
  3. * Super-simple, minimum abstraction MailChimp API v3 wrapper
  4. * MailChimp API v3: http://developer.mailchimp.com
  5. * This wrapper: https://github.com/drewm/mailchimp-api
  6. *
  7. * @author Drew McLellan <drew.mclellan@gmail.com>
  8. * @version 2.4
  9. */
  10. class MailChimp
  11. {
  12. private $api_key;
  13. private $api_endpoint = 'https://<dc>.api.mailchimp.com/3.0';
  14. const TIMEOUT = 10;
  15. /* SSL Verification
  16. Read before disabling:
  17. http://snippets.webaware.com.au/howto/stop-turning-off-curlopt_ssl_verifypeer-and-fix-your-php-config/
  18. */
  19. public $verify_ssl = true;
  20. private $request_successful = false;
  21. private $last_error = '';
  22. private $last_response = array();
  23. private $last_request = array();
  24. /**
  25. * Create a new instance
  26. * @param string $api_key Your MailChimp API key
  27. * @param string $api_endpoint Optional custom API endpoint
  28. * @throws \Exception
  29. */
  30. public function __construct($api_key, $api_endpoint = null)
  31. {
  32. $this->api_key = $api_key;
  33. if ($api_endpoint === null) {
  34. if (strpos($this->api_key, '-') === false) {
  35. throw new Exception("Invalid MailChimp API key `{$api_key}` supplied.");
  36. }
  37. list(, $data_center) = explode('-', $this->api_key);
  38. $this->api_endpoint = str_replace('<dc>', $data_center, $this->api_endpoint);
  39. } else {
  40. $this->api_endpoint = $api_endpoint;
  41. }
  42. $this->last_response = array('headers' => null, 'body' => null);
  43. }
  44. /**
  45. * Create a new instance of a Batch request. Optionally with the ID of an existing batch.
  46. * @param string $batch_id Optional ID of an existing batch, if you need to check its status for example.
  47. * @return Batch New Batch object.
  48. */
  49. public function new_batch($batch_id = null)
  50. {
  51. return new Batch($this, $batch_id);
  52. }
  53. /**
  54. * @return string The url to the API endpoint
  55. */
  56. public function getApiEndpoint()
  57. {
  58. return $this->api_endpoint;
  59. }
  60. /**
  61. * Convert an email address into a 'subscriber hash' for identifying the subscriber in a method URL
  62. * @param string $email The subscriber's email address
  63. * @return string Hashed version of the input
  64. */
  65. public function subscriberHash($email)
  66. {
  67. return md5(strtolower($email));
  68. }
  69. /**
  70. * Was the last request successful?
  71. * @return bool True for success, false for failure
  72. */
  73. public function success()
  74. {
  75. return $this->request_successful;
  76. }
  77. /**
  78. * Get the last error returned by either the network transport, or by the API.
  79. * If something didn't work, this should contain the string describing the problem.
  80. * @return string|false describing the error
  81. */
  82. public function getLastError()
  83. {
  84. return $this->last_error ?: false;
  85. }
  86. /**
  87. * Get an array containing the HTTP headers and the body of the API response.
  88. * @return array Assoc array with keys 'headers' and 'body'
  89. */
  90. public function getLastResponse()
  91. {
  92. return $this->last_response;
  93. }
  94. /**
  95. * Get an array containing the HTTP headers and the body of the API request.
  96. * @return array Assoc array
  97. */
  98. public function getLastRequest()
  99. {
  100. return $this->last_request;
  101. }
  102. /**
  103. * Make an HTTP DELETE request - for deleting data
  104. * @param string $method URL of the API request method
  105. * @param array $args Assoc array of arguments (if any)
  106. * @param int $timeout Timeout limit for request in seconds
  107. * @return array|false Assoc array of API response, decoded from JSON
  108. */
  109. public function delete($method, $args = array(), $timeout = self::TIMEOUT)
  110. {
  111. return $this->makeRequest('delete', $method, $args, $timeout);
  112. }
  113. /**
  114. * Make an HTTP GET request - for retrieving data
  115. * @param string $method URL of the API request method
  116. * @param array $args Assoc array of arguments (usually your data)
  117. * @param int $timeout Timeout limit for request in seconds
  118. * @return array|false Assoc array of API response, decoded from JSON
  119. */
  120. public function get($method, $args = array(), $timeout = self::TIMEOUT)
  121. {
  122. return $this->makeRequest('get', $method, $args, $timeout);
  123. }
  124. /**
  125. * Make an HTTP PATCH request - for performing partial updates
  126. * @param string $method URL of the API request method
  127. * @param array $args Assoc array of arguments (usually your data)
  128. * @param int $timeout Timeout limit for request in seconds
  129. * @return array|false Assoc array of API response, decoded from JSON
  130. */
  131. public function patch($method, $args = array(), $timeout = self::TIMEOUT)
  132. {
  133. return $this->makeRequest('patch', $method, $args, $timeout);
  134. }
  135. /**
  136. * Make an HTTP POST request - for creating and updating items
  137. * @param string $method URL of the API request method
  138. * @param array $args Assoc array of arguments (usually your data)
  139. * @param int $timeout Timeout limit for request in seconds
  140. * @return array|false Assoc array of API response, decoded from JSON
  141. */
  142. public function post($method, $args = array(), $timeout = self::TIMEOUT)
  143. {
  144. return $this->makeRequest('post', $method, $args, $timeout);
  145. }
  146. /**
  147. * Make an HTTP PUT request - for creating new items
  148. * @param string $method URL of the API request method
  149. * @param array $args Assoc array of arguments (usually your data)
  150. * @param int $timeout Timeout limit for request in seconds
  151. * @return array|false Assoc array of API response, decoded from JSON
  152. */
  153. public function put($method, $args = array(), $timeout = self::TIMEOUT)
  154. {
  155. return $this->makeRequest('put', $method, $args, $timeout);
  156. }
  157. /**
  158. * Performs the underlying HTTP request. Not very exciting.
  159. * @param string $http_verb The HTTP verb to use: get, post, put, patch, delete
  160. * @param string $method The API method to be called
  161. * @param array $args Assoc array of parameters to be passed
  162. * @param int $timeout
  163. * @return array|false Assoc array of decoded result
  164. * @throws \Exception
  165. */
  166. private function makeRequest($http_verb, $method, $args = array(), $timeout = self::TIMEOUT)
  167. {
  168. if (!function_exists('curl_init') || !function_exists('curl_setopt')) {
  169. throw new Exception("cURL support is required, but can't be found.");
  170. }
  171. $url = $this->api_endpoint . '/' . $method;
  172. $response = $this->prepareStateForRequest($http_verb, $method, $url, $timeout);
  173. $ch = curl_init();
  174. curl_setopt($ch, CURLOPT_URL, $url);
  175. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  176. 'Accept: application/vnd.api+json',
  177. 'Content-Type: application/vnd.api+json',
  178. 'Authorization: apikey ' . $this->api_key
  179. ));
  180. curl_setopt($ch, CURLOPT_USERAGENT, 'DrewM/MailChimp-API/3.0 (github.com/drewm/mailchimp-api)');
  181. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  182. curl_setopt($ch, CURLOPT_VERBOSE, true);
  183. curl_setopt($ch, CURLOPT_HEADER, true);
  184. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  185. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->verify_ssl);
  186. curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  187. curl_setopt($ch, CURLOPT_ENCODING, '');
  188. curl_setopt($ch, CURLINFO_HEADER_OUT, true);
  189. switch ($http_verb) {
  190. case 'post':
  191. curl_setopt($ch, CURLOPT_POST, true);
  192. $this->attachRequestPayload($ch, $args);
  193. break;
  194. case 'get':
  195. $query = http_build_query($args, '', '&');
  196. curl_setopt($ch, CURLOPT_URL, $url . '?' . $query);
  197. break;
  198. case 'delete':
  199. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  200. break;
  201. case 'patch':
  202. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PATCH');
  203. $this->attachRequestPayload($ch, $args);
  204. break;
  205. case 'put':
  206. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  207. $this->attachRequestPayload($ch, $args);
  208. break;
  209. }
  210. $responseContent = curl_exec($ch);
  211. $response['headers'] = curl_getinfo($ch);
  212. $response = $this->setResponseState($response, $responseContent, $ch);
  213. $formattedResponse = $this->formatResponse($response);
  214. curl_close($ch);
  215. $this->determineSuccess($response, $formattedResponse, $timeout);
  216. return $formattedResponse;
  217. }
  218. /**
  219. * @param string $http_verb
  220. * @param string $method
  221. * @param string $url
  222. * @param integer $timeout
  223. */
  224. private function prepareStateForRequest($http_verb, $method, $url, $timeout)
  225. {
  226. $this->last_error = '';
  227. $this->request_successful = false;
  228. $this->last_response = array(
  229. 'headers' => null, // array of details from curl_getinfo()
  230. 'httpHeaders' => null, // array of HTTP headers
  231. 'body' => null // content of the response
  232. );
  233. $this->last_request = array(
  234. 'method' => $http_verb,
  235. 'path' => $method,
  236. 'url' => $url,
  237. 'body' => '',
  238. 'timeout' => $timeout,
  239. );
  240. return $this->last_response;
  241. }
  242. /**
  243. * Get the HTTP headers as an array of header-name => header-value pairs.
  244. *
  245. * The "Link" header is parsed into an associative array based on the
  246. * rel names it contains. The original value is available under
  247. * the "_raw" key.
  248. *
  249. * @param string $headersAsString
  250. * @return array
  251. */
  252. private function getHeadersAsArray($headersAsString)
  253. {
  254. $headers = array();
  255. foreach (explode("\r\n", $headersAsString) as $i => $line) {
  256. if ($i === 0) { // HTTP code
  257. continue;
  258. }
  259. $line = trim($line);
  260. if (empty($line)) {
  261. continue;
  262. }
  263. list($key, $value) = explode(': ', $line);
  264. if ($key == 'Link') {
  265. $value = array_merge(
  266. array('_raw' => $value),
  267. $this->getLinkHeaderAsArray($value)
  268. );
  269. }
  270. $headers[$key] = $value;
  271. }
  272. return $headers;
  273. }
  274. /**
  275. * Extract all rel => URL pairs from the provided Link header value
  276. *
  277. * Mailchimp only implements the URI reference and relation type from
  278. * RFC 5988, so the value of the header is something like this:
  279. *
  280. * 'https://us13.api.mailchimp.com/schema/3.0/Lists/Instance.json; rel="describedBy", <https://us13.admin.mailchimp.com/lists/members/?id=XXXX>; rel="dashboard"'
  281. *
  282. * @param string $linkHeaderAsString
  283. * @return array
  284. */
  285. private function getLinkHeaderAsArray($linkHeaderAsString)
  286. {
  287. $urls = array();
  288. if (preg_match_all('/<(.*?)>\s*;\s*rel="(.*?)"\s*/', $linkHeaderAsString, $matches)) {
  289. foreach ($matches[2] as $i => $relName) {
  290. $urls[$relName] = $matches[1][$i];
  291. }
  292. }
  293. return $urls;
  294. }
  295. /**
  296. * Encode the data and attach it to the request
  297. * @param resource $ch cURL session handle, used by reference
  298. * @param array $data Assoc array of data to attach
  299. */
  300. private function attachRequestPayload(&$ch, $data)
  301. {
  302. $encoded = json_encode($data);
  303. $this->last_request['body'] = $encoded;
  304. curl_setopt($ch, CURLOPT_POSTFIELDS, $encoded);
  305. }
  306. /**
  307. * Decode the response and format any error messages for debugging
  308. * @param array $response The response from the curl request
  309. * @return array|false The JSON decoded into an array
  310. */
  311. private function formatResponse($response)
  312. {
  313. $this->last_response = $response;
  314. if (!empty($response['body'])) {
  315. return json_decode($response['body'], true);
  316. }
  317. return false;
  318. }
  319. /**
  320. * Do post-request formatting and setting state from the response
  321. * @param array $response The response from the curl request
  322. * @param string $responseContent The body of the response from the curl request
  323. * * @return array The modified response
  324. */
  325. private function setResponseState($response, $responseContent, $ch)
  326. {
  327. if ($responseContent === false) {
  328. $this->last_error = curl_error($ch);
  329. } else {
  330. $headerSize = $response['headers']['header_size'];
  331. $response['httpHeaders'] = $this->getHeadersAsArray(substr($responseContent, 0, $headerSize));
  332. $response['body'] = substr($responseContent, $headerSize);
  333. if (isset($response['headers']['request_header'])) {
  334. $this->last_request['headers'] = $response['headers']['request_header'];
  335. }
  336. }
  337. return $response;
  338. }
  339. /**
  340. * Check if the response was successful or a failure. If it failed, store the error.
  341. * @param array $response The response from the curl request
  342. * @param array|false $formattedResponse The response body payload from the curl request
  343. * @param int $timeout The timeout supplied to the curl request.
  344. * @return bool If the request was successful
  345. */
  346. private function determineSuccess($response, $formattedResponse, $timeout)
  347. {
  348. $status = $this->findHTTPStatus($response, $formattedResponse);
  349. if ($status >= 200 && $status <= 299) {
  350. $this->request_successful = true;
  351. return true;
  352. }
  353. if (isset($formattedResponse['detail'])) {
  354. $this->last_error = sprintf('%d: %s', $formattedResponse['status'], $formattedResponse['detail']);
  355. return false;
  356. }
  357. if( $timeout > 0 && $response['headers'] && $response['headers']['total_time'] >= $timeout ) {
  358. $this->last_error = sprintf('Request timed out after %f seconds.', $response['headers']['total_time'] );
  359. return false;
  360. }
  361. $this->last_error = 'Unknown error, call getLastResponse() to find out what happened.';
  362. return false;
  363. }
  364. /**
  365. * Find the HTTP status code from the headers or API response body
  366. * @param array $response The response from the curl request
  367. * @param array|false $formattedResponse The response body payload from the curl request
  368. * @return int HTTP status code
  369. */
  370. private function findHTTPStatus($response, $formattedResponse)
  371. {
  372. if (!empty($response['headers']) && isset($response['headers']['http_code'])) {
  373. return (int) $response['headers']['http_code'];
  374. }
  375. if (!empty($response['body']) && isset($formattedResponse['status'])) {
  376. return (int) $formattedResponse['status'];
  377. }
  378. return 418;
  379. }
  380. /**
  381. * Get all the mailing list. Takes care of the request limit (50 records) from the MC API.
  382. * @param array $args Assoc array of arguments
  383. * @return array of all the lists with the MC account.
  384. */
  385. public function getLists( $args = array() ){
  386. $defaults = array(
  387. 'count' => 50,
  388. 'offset' => 0,
  389. 'sort_field' => 'date_created',
  390. 'sort_dir' => 'ASC',
  391. 'fields' => 'lists.name,lists.id,total_items'
  392. );
  393. $r = array_merge( $defaults, $args );
  394. $result = $this->get( 'lists', $r );
  395. $lists = array();
  396. if ( isset( $result[ 'lists' ] ) ) {
  397. $lists = $result[ 'lists' ];
  398. if ( count( $lists ) < $result[ 'total_items' ] ) {
  399. for ( $offset = 50; $offset < $result[ 'total_items' ]; $offset += 50 ) {
  400. $r[ 'offset' ] = $offset;
  401. $new_result = $this->get( 'lists', $r );
  402. $lists = array_merge( $lists, $new_result[ 'lists' ] );
  403. }
  404. }
  405. }
  406. return $lists;
  407. }
  408. /**
  409. * Get the list of interest groupings for a given list, including the label, form information, and included groups for each
  410. * @param string $list_id
  411. * @return array of structs of the interest groupings for the list
  412. */
  413. public function interestGroupings( $list_id ) {
  414. if ( ! $list_id ) {
  415. return;
  416. }
  417. $groups = array();
  418. $results = $this->get(
  419. 'lists/' . $list_id . '/interest-categories',
  420. array(
  421. 'fields' => 'categories.id,categories.title,total_items'
  422. )
  423. );
  424. if ( $results[ 'total_items' ] > 0 ) {
  425. foreach ( $results[ 'categories' ] as $category ) {
  426. $subgroups = $this->get(
  427. 'lists/' . $list_id . '/interest-categories/' . $category[ 'id' ] . '/interests',
  428. array(
  429. 'fields' => 'interests.id,interests.name,total_items'
  430. )
  431. );
  432. if ( $subgroups[ 'total_items' ] > 0 ) {
  433. $category[ 'groups' ] = $subgroups[ 'interests' ];
  434. }
  435. $groups[] = $category;
  436. }
  437. }
  438. return $groups;
  439. }
  440. /**
  441. * Subscribe a member to a list. It will automatically update member if exists.
  442. * @param string $list_id
  443. * @param array $data
  444. * @return array
  445. */
  446. public function subscribe( $list_id, $data ){
  447. if ( ! isset( $list_id ) || ! isset( $data[ 'email' ] ) ) {
  448. return;
  449. }
  450. $member = $this->get_member( $list_id, $data[ 'email' ] );
  451. if ( ! $this->getLastError() && 'unsubscribed' == $member[ 'status' ] ) {
  452. // Re-subscribe member if their status is `unsubscribed`.
  453. $data[ 'status' ] = 'pending';
  454. }
  455. $args = array(
  456. 'email_address' => $data[ 'email' ],
  457. 'status_if_new' => $data[ 'double_optin' ] ? 'pending' : 'subscribed',
  458. 'status' => isset( $data[ 'status' ] ) ? $data[ 'status' ] : 'subscribed',
  459. 'email_type' => 'html',
  460. 'merge_fields' => array(
  461. 'FNAME' => ! empty( $data[ 'FNAME' ] ) ? $data[ 'FNAME' ] : '',
  462. 'LNAME' => ! empty( $data[ 'LNAME' ] ) ? $data[ 'LNAME' ] : ''
  463. ),
  464. );
  465. if ( isset( $data[ 'groups' ] ) ) {
  466. $args[ 'interests' ] = (object) $data[ 'groups' ];
  467. }
  468. $email_hash = $this->subscriberHash( $data[ 'email' ] );
  469. $results = $this->put( 'lists/' . $list_id . '/members/' . $email_hash, $args );
  470. return $results;
  471. }
  472. /**
  473. * Get information about a specific list member.
  474. * @param string $list_id
  475. * @param string $email
  476. * @return array
  477. */
  478. public function get_member( $list_id, $email ){
  479. if ( ! $email ) {
  480. return;
  481. }
  482. $email_hash = $this->subscriberHash( $email );
  483. $result = $this->get( 'lists/' . $list_id . '/members/' . $email_hash );
  484. return $result;
  485. }
  486. }