Misha Rudrastyh

Misha Rudrastyh

WordPress Developer

Mailchimp API 3.0 – PHP and AJAX subscription / unsubscription

Ready to use function which allows you to subscribe an email address to any of your mailchimp lists (with confirmation email or not) or unsubscribe it as well.

November 16, 2015October 12, 2016 21

Ok, if you are reading this post, you already know something about mailchimp and use default Mailchimp sign up forms maybe.

But what if you want your forms to be more customizable for your website purposes, such as:

  • original form design,
  • mailchimp subscription built-in another form (sign up checkbox in custom form — look at my comment form),
  • no confirmation emails,
  • subscribe or unsubscribe users via your website administration area etc.

First of all insert this function into your website code. If you use WordPress, it can be functions.php file.

function rudr_mailchimp_subscriber_status( $email, $status, $list_id, $api_key, $merge_fields = array('FNAME' => '','LNAME' => '') ){
	$data = array(
		'apikey'        => $api_key,
    		'email_address' => $email,
		'status'        => $status,
		'merge_fields'  => $merge_fields
	$mch_api = curl_init(); // initialize cURL connection
	curl_setopt($mch_api, CURLOPT_URL, 'https://' . substr($api_key,strpos($api_key,'-')+1) . '.api.mailchimp.com/3.0/lists/' . $list_id . '/members/' . md5(strtolower($data['email_address'])));
	curl_setopt($mch_api, CURLOPT_HTTPHEADER, array('Content-Type: application/json', 'Authorization: Basic '.base64_encode( 'user:'.$api_key )));
	curl_setopt($mch_api, CURLOPT_USERAGENT, 'PHP-MCAPI/2.0');
	curl_setopt($mch_api, CURLOPT_RETURNTRANSFER, true); // return the API response
	curl_setopt($mch_api, CURLOPT_CUSTOMREQUEST, 'PUT'); // method PUT
	curl_setopt($mch_api, CURLOPT_TIMEOUT, 10);
	curl_setopt($mch_api, CURLOPT_POST, true);
	curl_setopt($mch_api, CURLOPT_SSL_VERIFYPEER, false);
	curl_setopt($mch_api, CURLOPT_POSTFIELDS, json_encode($data) ); // send data in json
	$result = curl_exec($mch_api);
	return $result;

Ok, now let me show what each parameter means.

(string) I hope it is clear for you.
(string) Subscriber status to set:

  • subscribed
  • unsubscribed
  • cleaned
  • pending (confirmation email will be sent)
(string) Mailchimp list ID you want to add subscribers to. How to obtain it?

How to get Mailchimp list ID?

Login to Mailchimp, go to Lists then click on the list title, then in list menu Settings > List name and defaults.

Go to Lists > Settings > List name and defaults to obtain a list ID. Do not use the list ID from the screenshot - it is fake.
(string) API key is unique for every Mailchimp account. And this is how to get it:

How to get Mailchimp API keys?

1. In main Mailchimp menu click on your picture and go to Account.

Mailchimp account settings is here.

2. Then choose Extras > API keys.

Click on «API keys» link from «Extras» dropdown menu then you will be redirected to page where you can create a Mailchimp API key.

3. That’s it. Click on Create A Key and your new API key will appear.

Click on Create A Key button to  create new mailchimp API key.
(array) Subscriber fields, can be configured in a list settings. By default each mailchimp list has two merge fields (except email) — subscriber first name $merge_fields['FNAME'] and last name $merge_fields['LNAME'].

PHP Subscription example

Do not forget to copy the rudr_mailchimp_subscriber_status() function to your website code (you can find it at the beginning of the post).

$email = 'johndoe@rudrastyh.com';
$status = 'subscribed'; // "subscribed" or "unsubscribed" or "cleaned" or "pending"
$list_id = 'YOUR LIST ID HERE'; // where to get it read above
$api_key = 'YOUR MAILCHIMP API KEY HERE'; // where to get it read above
$merge_fields = array('FNAME' => 'Misha','LNAME' => 'Rudrastyh');
rudr_mailchimp_subscriber_status($email, $status, $list_id, $api_key, $merge_fields );

The very simple example. Do you think so?

AJAX Subscription example (WordPress-friendly)

Actually my blog is about WordPress, so the AJAX example will be adapted for WordPress.

Step 1. Sign Up form HTML

This form will work properly only if the JavaScript is enabled in user browser. You can also upgrade it to work both with JavaScript and without it.

<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" id="mailchimp">
	<!-- for my website the site_url() function returns https://rudrastyh.com -->
	<input type="text" name="fname" placeholder="First name" />
	<input type="text" name="lname" placeholder="Last name" />
	<input type="email" name="email" placeholder="Email *" required />
	<input type="hidden" name="action" value="mailchimpsubscribe" />
	<!-- we need action parameter to receive ajax request in WordPress -->

Step 2. jQuery code to send asynchronous request

Make sure that jQuery library is included to your website pages.

		var mailchimpform = $(this);
		return false;

Step 3. PHP code for your functions.php file. Errors Handling

function rudr_mch_subscribe(){
	$list_id = 'YOUR LIST ID HERE';
	$result = json_decode( rudr_mailchimp_subscriber_status($_POST['email'], 'subscribed', $list_id, $api_key, array('FNAME' => $_POST['fname'],'LNAME' => $_POST['lname']) ) );
	// print_r( $result ); 
	if( $resul->status == 400 ){
		foreach( $result->errors as $error ) {
			echo '<p>Error: ' . $error->message . '</p>';
	} elseif( $result->status == 'subscribed' ){
		echo 'Thank you, ' . $result->merge_fields->FNAME . '. You have subscribed successfully';
	// $result['id'] - Subscription ID
	// $result['ip_opt'] - Subscriber IP address

Only new posts about WordPress

once a week

Comments 21

  • Hii,

    I tried your code on my site but it’s not working for me.
    by the way should not this line be 3.0? curl_setopt($mch_api, CURLOPT_USERAGENT, ‘PHP-MCAPI/2.0’);

  • Hi, grate code :)
    Do you have an AJAX example not connected to WordPress?

    • Hi, thank you :)
      All you need is to change form action to a file where you would like to place mailchimp subscription code.

  • Hi, Thanks !!
    Saved lot of time

  • Thanks, this was helpful when other tutorials were not.

  • Hi ,
    i need your help. I need the disable the double optin in mailchimp for my shopify. can you please what are all the steps i need to do for disable the double optin?

    • MishaAuthorJune 14, 2016 at 05:06

      Is MailChimp functionality integrated into your shopify theme? If yes, I recommend to perform a search through your theme files for a keyword pending. And when you find it, replace to subscribed.

      • Hi,
        Thanks for your reply.

        Actually i have a newsletter sign up form in my shopify site. So after i have created the signup form in my mailchimp account, i took the form action url alone and used in the shopify.Thats all.

        so i think mailchimp functionality is integrated with shopify like you are asking. but i have checked all the files. there is no keyword pending. I have a two shopify sites which one i am using “brooklyn” theme and another one is “Launch-pad star” theme. I am using the mailchimp sign up form integrated with the two sites of nesletter sign up form. But i can’t disable the double optin in those two sites.

        Can you please provide any other solution for this??? I really need your help.

        Thanks in Advance!!!

        • MishaAuthorJune 14, 2016 at 15:06

          I think it is because you are using HTML sign-up form — it doesn’t allow to disable double optin.

          If you want to subscribe users without confirmation, you have to use MailChimp API for these purposes. All the examples are above. Or you can try to look for an extension.

  • Can you give an example of this working? I am totally lost.

    • The example is above :) How can I help you?

      • Thank you for answering. I have so many questions – like:

        Where do I put the API?

        How do I make the API add new users based on a custom form?

        • I’m sorry, Sean, but answers to your questions are very clear in the post.

          So, I do not want just to duplicate the text and code from the post here, so I recommend you to read the post once again or ask me the other questions.

  • Hi Misha,
    first of all thank you for this!

    I used your WP example and adding users to a mailchimp list with the form works fine, but after user submission of the email a the browser popup dialog opens on the frontend and after closing this the user is redirected to


    My questions:
    How can i prevent the browser popup, and redirect to another link without displaying the user information in the browser adress bar? I am using the Foundation framework and would ideally like to open up a modal dialog (http://foundation.zurb.com/sites/docs/reveal.html) upon successful subscription.

    And is it possible to just have one field on the frontend for the user’s email adress instead of first & last name + email adress?

    Thank you for your time!

    • Hi Josh,

      of course user shouldn’t be redirected to admin-ajax.php. Oh, sorry, I forgot to add return false; in my jQuery code – plese try now.

      Yes, it is possible to have just email address field on the frontend.

Leave comment

Please, enter a comment
Please, enter a name
Incorrect email
© 2016 Misha Rudrastyh
Developed on with