Add new subscriber in a Mailchimp List API

Add new subscriber in a Mailchimp List API

Mailchimp is very flexible & gives you a variety of easily customizable options. Mailchimp is an email marketing service. It is an American company founded in 2001. They investing in their platform to make the work of email marketing more integrated into other platforms like eCommerce, social media etc. They've added features that have helped make my job more of a one-system stop which has been a positive impact on my workflow. In Mailchimp contacts & audiences are two main fundamental parts of marketing. With the help of Mailchimp it is very easier to shares content with the subscribers.

In this article, I will explain you that, how we can insert a new subscriber in mailchimp list using API 3.0, for this I'm going to use CURL request. My form has only 2 fields email and status because I will created a simple html form for newsletter. You can include more fields in your form based on your requirements. It adds a new member of a list or updates the member if the email already exists on the list.

To add subscriber in a list you will need API_KEY and LIST_ID. I'm using the following code to add subscriber in mailchimp list.

<?php
$mailchimp_data = [
'email_address' => 'EMAIL ADDRESS HERE',
'status' => 'subscribed'
];

//API KEY and LIST ID here
$apiKey = 'ENTER API HERE';
$listId = 'ENTER LIST ID HERE';

$memberId = md5(strtolower($mailchimp_data['email_address']));
$dataCenter = substr($apiKey,strpos($apiKey,'-')+1);
$url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $listId . '/members/' . $memberId;
$json = json_encode($mailchimp_data);
$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);

?>

How to get API Key & List ID in Mailchimp

Get Api Key

1. Go to account after login

Mailchimp account

2. After that click on API Keys under Extras

Mailchimp under extras

3. Copy and use API key in your code

Mailchimp API key

Get List ID

1. Go to this URL https://us2.admin.mailchimp.com/lists/ after login to get your list id and then click on setting on any list

Mailchimp List Page

2. And after that, scroll down the page & you will see unique list id

Mailchimp List ID

Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Add your comment