-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMailchimp.php
More file actions
56 lines (48 loc) · 1.96 KB
/
Mailchimp.php
File metadata and controls
56 lines (48 loc) · 1.96 KB
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
<?php
class Mailchimp
{
/**
* Access the mailchimp lists API and subscribe user
* @author Versha dhiman
* for more info check "https://apidocs.mailchimp.com/api/2.0/lists/subscribe.php"
*/
public static function addEmailToList($email)
{
$apiKey = 'YOUR_API_KEY_COMES_HERE'; // API key for mailchimp
$listID = 'YOUR_LIST_ID_COMES_HERE'; //Id of newsletter list
// MailChimp API URL
$memberID = md5(strtolower($email));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listID . '/members/' . $memberID;
// member information
$json = json_encode([
'email_address' => $email,
'status' => 'subscribed',
]);
// send a HTTP POST request with curl
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
// store the status message based on response code
if ($httpCode == 200) {
echo $msg = '<p style="color:green;"> have successfully subscribed</p>';
} else {
switch ($httpCode) {
case 214:
echo $msg = '<p style="color:orange;"> are already subscribed.</p>';
//break;
default:
echo $msg = '<p style="color:red;">Some problem occurred, please try again.</p>';
//break;
}
}
}
}