· 6 years ago · Jan 12, 2020, 06:32 AM
1<?php
2// Your Account API & List ID
3$api_key = "8e46b3994b45e3463cff4c46ef4404a9-us4"; // YOUR-API-KEY-HERE
4$list_id = "feee58f221"; // YOUR-LIST-ID-HERE
5
6// Check $recipient
7if($recipient === '' || $list_id === '' ) {
8 returnAndExitAjaxResponse(
9 constructAjaxResponseArray(
10 FALSE,
11 'APIDATA_IS_NOT_SET',
12 array('error_message'=> 'API KEY / LIST ID is not set. Please configure the script.')
13 )
14 );
15}
16
17// make sure that $_POST['fname'] is not blank
18$_fname = (empty($_POST['fname'])) ? 'No name specified' : $_POST['fname'];
19
20/**
21 * see https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php
22 * When using a wrapper or XML-RPC, this is generally the parameter order.
23 * When building JSON objects or serialized HTTP requests parameter order does not matter
24 */
25// var_dump($thememountain_mailchimp_form_settings,$email,$fname,$api_key,$list_id);
26try {
27 include_once('MailChimp/MailChimp.php');
28 $MailChimp = new \DrewM\MailChimp\MailChimp($api_key);
29 $result = $MailChimp->post("lists/$list_id/members", array(
30 'email_address' => $_POST['email'],
31 'status' => 'subscribed',
32 'merge_fields' => array(
33 'FNAME' => $_fname,
34 'LNAME' => ''
35 )
36 )
37 );
38
39 if($result['status'] == 'subscribed') {
40 returnAndExitAjaxResponse(
41 constructAjaxResponseArray(TRUE,'')
42 );
43 } else {
44 returnAndExitAjaxResponse(
45 constructAjaxResponseArray(FALSE,'',array('error_message'=>$result['title']) )
46 );
47 }
48} catch (Exception $_e) {
49 returnAndExitAjaxResponse(
50 constructAjaxResponseArray(FALSE,'ERROR_AT_MAILCHIMP',$_e->getMessage(),$list_id)
51 );
52}
53
54/*
55 Construct ajax response array
56 Input: Result (bool), Message (optional), Data to be sent back in array
57*/
58function constructAjaxResponseArray ($_response, $_message = '', $_json = null) {
59 $_responseArray = array();
60 $_response = ( $_response === TRUE ) ? TRUE : FALSE;
61 $_responseArray['response'] = $_response;
62 if(isset($_message)) $_responseArray['message'] = $_message;
63 if(isset($_json)) $_responseArray['json'] = $_json;
64
65 return $_responseArray;
66}
67/*
68 Returns in the Gframe ajax format.
69 Input: data array processed by constructAjaxResponseArray ()
70 Outputs as a html stream then exits.
71*/
72function returnAndExitAjaxResponse ($_ajaxResponse) {
73 if(!$_ajaxResponse){
74 $_ajaxResponse = array('response'=>false,'message'=>'Unknown error occurred.');
75 }
76 header("Content-Type: application/json; charset=utf-8");
77 echo json_encode($_ajaxResponse);
78 die();
79}