-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSubscribeToMailchimp.module
249 lines (244 loc) · 11.6 KB
/
SubscribeToMailchimp.module
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
<?php
class SubscribeToMailchimp extends WireData implements Module, ConfigurableModule {
static function getModuleInfo() {
return [
'title' => 'Subscribe to Mailchimp',
'summary' => 'Subscribe, update, unsubscribe or delete a user in your Mailchimp mailing list.',
'version' => '0.0.3',
'author' => 'danielstieber',
'href' => 'https://github.com/danielstieber/SubscribeToMailchimp',
'icon' => 'address-card',
'autoload'=> false,
'singular'=> false
];
}
const WARNING_VALIDATION = "A user managed to send a form without an email address. Please check your form validation! A server-sided validation (e.g. via Valitron) is strongly recommended.";
static public function getDefaults() {
return array(
"double_opt_in" => "checked",
);
}
private function getApiBase($list = null, $param = null) {
$dc = explode('-',$this->api_key)[1];
$return = "https://".$dc.".api.mailchimp.com/3.0/";
if(!is_null($list)) $return .= "lists/".$list."/"; // trailing slash to make further parameters possible
if(!is_null($param)) $return .= $param; // no trailing slash since not necessary
return $return;
}
public function subscribe($email, array $merge_fields = [], $list = NULL, array $param = []) {
$list = is_null($list) ? $this->default_list : $list; // use default list from module settings, if no list is provided
if(isset($email)) {
$api = $this->getApiBase($list, 'members');
$param['email_address'] = $email;
foreach ($merge_fields as $k => $v) {
if(!empty(trim($v))) { // avoid to override data of existing leads with empty field values
$param['merge_fields'][$k] = $v;
}
}
$http = new WireHttp();
$http->setHeaders([
'Content-Type' => 'application/json',
'Authorization' => 'Basic '.base64_encode('user:'.$this->api_key),
]);
$status = $this->getStatus($email, $list); // get the current subscription status of the user
if($status !== false) {
if($this->double_opt_in)
if ($status == 'unsubscribed') {
if($this->double_opt_in)
$param['status'] = 'pending';
else
$param['status'] = 'subscribed';
}
$response = $http->send($api . '/' . md5($email), json_encode($param), 'PATCH');
} else {
if($this->double_opt_in)
$param['status'] = 'pending';
else
$param['status'] = 'subscribed';
$response = $http->send($api, json_encode($param), 'POST');
}
if($response !== false) {
return true;
} else {
$this->warning("Mailchimp request subscribe() not successful: " . $http->getError(), Notice::log); // Log warning in Processwire backend
return false;
}
} else {
$this->warning(self::WARNING_VALIDATION); // Log warning, if a user is able to send a form without email.
return false;
}
}
public function unsubscribe($email, $list = NULL) {
$param = [];
$list = is_null($list) ? $this->default_list : $list; // use default list from module settings, if no list is provided
if(isset($email)) {
$api = $this->getApiBase($list, 'members/' . md5($email));
$http = new WireHttp();
$http->setHeaders([
'Content-Type' => 'application/json',
'Authorization' => 'Basic '.base64_encode('user:'.$this->api_key),
]);
$param['status'] = 'unsubscribed';
$response = $http->send($api, json_encode($param), 'PATCH'); // update listentry with param 'unsubscribed'
if($response !== false) {
return true;
} else {
$this->warning("Mailchimp request unsubscribe() not successful: " . $http->getError(), Notice::log); // Log warning in Processwire backend
return false;
}
return true;
} else {
$this->warning(self::WARNING_VALIDATION); // Log warning, if a user is able to send a form without email.
return false;
}
}
public function delete($email, $list = NULL) {
$list = is_null($list) ? $this->default_list : $list; // use default list from module settings, if no list is provided
if(isset($email)) {
$api = $this->getApiBase($list, 'members/' . md5($email));
$http = new WireHttp();
$http->setHeaders([
'Content-Type' => 'application/json',
'Authorization' => 'Basic '.base64_encode('user:'.$this->api_key),
]);
$response = $http->send($api, [], 'DELETE'); // delete entry
if($response !== false) {
return true;
} else {
$this->warning("Mailchimp request delete() not successful: " . $http->getError(), Notice::log); // Log warning in Processwire backend
return false;
}
return true;
} else {
$this->warning(self::WARNING_VALIDATION); // Log warning, if a user is able to send a form without email.
return false;
}
}
public function getStatus($email, $list = NULL) {
$list = is_null($list) ? $this->default_list : $list; // use default list from module settings, if no list is provided
if(isset($email)) {
$api = $this->getApiBase($list, 'members/'.md5($email)); // get the api path
$http = new WireHttp();
$http->setHeaders([
'Authorization' => 'Basic '.base64_encode('user:'.$this->api_key)
]);
$response = $http->get($api); // get the entry of the given mail adress on the list
if($response !== false) {
return json_decode($response)->status; // return the subscription status
} else {
$this->warning("Mailchimp request getStatus() not successful: " . $http->getError(), Notice::log); // Log warning in Processwire backend
return false;
}
return true;
} else {
$this->warning(self::WARNING_VALIDATION); // Log warning, if a user is able to send a form without email.
return false;
}
}
public static function getModuleConfigInputfields(array $data) {
$defaults = self::getDefaults();
$data = array_merge($defaults, $data);
$wrap = new InputfieldWrapper();
$form = wire('modules')->get('InputfieldFieldset');
$form->label = __('Mailchimp Configuration');
$form->notes = __('Check out the README, if you have troubles to find the data for the fields above.');
$form->collapsed = wire('session')->mailchimp_test_settings ? Inputfield::collapsedNo : Inputfield::collapsedPopulated;
$inputfields = [
'api_key' => __('API Key'),
'default_list' => __('Default list (can be overwritten by every form)'),
];
$checkboxfields = [
'double_opt_in' => __('Use double opt in. (Recommended)'),
];
foreach($inputfields as $name => $label) {
$f = wire('modules')->get('InputfieldText');
$f->attr('name', $name);
$f->label = $label;
$f->required = true;
$f->columnWidth = 50;
if(isset($data[$name]))
$f->attr('value', $data[$name]);
$form->add($f);
}
foreach($checkboxfields as $name => $label) {
$f = wire('modules')->get("InputfieldCheckbox");
$f->name = $name;
$f->label = $label;
$f->attr('checked', empty($data[$name]) ? '' : 'checked');
$f->columnWidth = 100;
$form->add($f);
}
// TEST SETTINGS ||>>>
$f = wire('modules')->get('InputfieldCheckbox');
$f->attr('name', '_mailchimp_test_settings');
$f->label = __('Test your current settings!');
$f->description = __('Check this box and press save, to test the API Key and default list settings!');
$f->attr('value', 1);
$f->attr('checked', '');
$f->icon = 'heartbeat';
$f->columnWidth = wire('session')->mailchimp_test_settings ? 40 : 100;
$form->add($f);
if(wire('session')->mailchimp_test_settings) {
wire('session')->remove('mailchimp_test_settings');
$response = self::testSettings();
$f = wire('modules')->get('InputfieldMarkup');
$f->attr('name', '_test_response');
$f->label = __('Test Response: ');
$f->columnWidth = 60;
$f->attr('value', $response);
$form->add($f);
} else if(wire('input')->post->_mailchimp_test_settings) {
wire('session')->set('mailchimp_test_settings', 1);
}
// <<<|| TEST SETTINGS
$wrap->add($form);
return $wrap;
}
// static, so it can get called from static function getModuleConfigInputfields, but also from within your template files: $response = SubscribeToMailchimp::testSettings($listID);
public static function testSettings($list = null) {
$mc = wire('modules')->get('SubscribeToMailchimp');
$list = is_null($list) ? $mc->default_list : $list;
$dc = explode('-',$mc->api_key)[1]; // get the datacenter code from the api key, to use it in the api url
$api = $mc->getApiBase($list);
$errors = [];
try {
$http = new WireHttp();
$http->setHeaders([
'Authorization' => 'Basic '.base64_encode('user:'.$mc->api_key)
]);
$response = $http->send($api, '', 'GET');
if($response === false) {
$err = $http->getError();
if('401' == substr($err, 0, 3)) {
$response = "<h3 style='color: red;'>401 Unauthorized</h3>";
$response .= "<p style='color: red;'><strong>Check your API Key</strong></p>";
} else if('404' == substr($err, 0, 3)) {
$response = "<h3 style='color: red;'>404 Not Found</h3>";
$response .= "<p style='color: red;'><strong>Check your List-ID</strong></p>";
} else {
$response = '';
}
$response .= "<p style='color: red;'>".__('Mailchimp request not successful:')." {$err}</p>";
} else {
$res = json_decode($response);
$response = '';
if(isset($res->name)) $response .= "<p>List-Name: <strong>{$res->name}</strong></p>";
if(isset($res->id)) $response .= "<p>List-ID: <strong>{$res->id}</strong></p>";
$response .= "<p>";
foreach(['company', 'address1', 'address2', 'city', 'state', 'zip', 'country', 'phone'] as $param) {
if(isset($res->contact->$param) && !empty($res->contact->$param)) $response .= "{$param}: <strong>{$res->contact->$param}</strong><br />";
}
$response .= "</p>";
}
} catch(Exception $e) {
$errors[] = $e->getMessage();
}
if(count($errors)) {
$response = '';
foreach($errors as $error) {
$response .= "<p style='color: red;'>{$error}</p>";
}
}
return $response;
}
}