Wednesday 5 February 2014

MailChimp API - Subscribe User Email Through PHP

So MailChimp let your users to susbscribe and you can send them newsletters in bulk and manage your subscriber's lists. Although MailChimp provide forms and lot of APIs and functions but for that you need to google and search, it takes time.

Here I'll show you how you can simply write some code in to your site while keeping your users on site without going to MailChimp.

Things which are required before you start code.


Sign Up on MailChimp


After successfull account creation and activation, Generate your API keys and List ID.

  1. Go to your Account Settings -> Extras -> API Keys
  2. Click on Create a Key button and you will have you API  key ready.
  3. After that go to Lists section, Create List, Visit your created lists under Settings -> List name & defaults you will find List ID.


Now you need to download API files 


Download MailChimp API


I am using version2.0 API.

PHP CODE


MailChimp API send request through CURL so make sure you have enabled CURL in your PHP.

Create a php file subscribe.php

Place this inside subscribe.php file.


HTML


Create a index.html, place following code




JAVASCRIPT

Add jquery <script src="jquery.min.js" type="text/javascript"></script>



So here you go all done with basic code setup, make changes as you need with code.

Note: 

MailChimp does not show subscribers in your created list unless user activated their email. When user subscribes MailChimp send activation URL so only valid emails can subscribe.

53 comments:

  1. thanks man for the tutorial, good job!

    ReplyDelete
  2. Good Tutorial ! it's working fine for me but if I want to add FirstName, LastName and group how can I do?

    ReplyDelete
    Replies
    1. Thanks,
      You can pass another array of 'merge_vars' => array('FNAME'=>'Davy', 'LNAME'=>'Jones')

      Find more info here
      https://github.com/drewm/mailchimp-api/
      http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php

      Delete
    2. Woww... it's working fine now :) super thanks

      Delete
    3. hi all i want to add a group of subscibers. How it is possible

      Delete
  3. Thank you very much sir, for this tutorial.

    ReplyDelete
  4. Thank you but I would like to know if I can add my user to the list without sending confirmation email to user email. If yes, please let me know how to do it.
    Thank you very much.

    ReplyDelete
    Replies
    1. Hey Kenric, After email in array add 'double_optin' => false.

      Delete
  5. where is this file????

    require('Mailchimp.php');

    ReplyDelete
    Replies
    1. Its in the folder you'd download from https://bitbucket.org/mailchimp/mailchimp-api-php.git. I have mentioned in blog.

      Delete
  6. Thanks for the tutorial.
    Do I need to modify anything in Mailchimp.php? I saved it as it is in the same path as subscribe.php but nothing happens when I test the form (ie. no ajax msg, no email updated in mailchimp, etc.)
    Thanks

    ReplyDelete
    Replies
    1. Did you follow all the steps mentioned above ?
      You do not need to do any thing in Mailchimp.php. You should download whole folder of it with Mailchimp.php.

      Delete
    2. Great, thanks for your quick reply, it works now!
      Just one additional question, is my syntax below correct for the double_optin False? Doesn't seem to be working (users are still receiving the confirmation email to register to the news letter). Thanks

      subscribe( $list_id, array( 'email' => htmlentities($_POST['email'] ), 'double_optin' => false ) );


      if ( ! empty( $subscriber['leid'] ) ) {
      echo "success";
      }
      else
      {
      echo "fail";
      }

      ?>

      Delete
    3. It seems correct.
      http://kb.mailchimp.com/article/can-i-shut-off-the-e-mail-that-asks-people-for-confirmation-that-they-want-/

      Delete
  7. Seems that the double_optin code is placed at the wrong place. I've just received feedback from the mailchimp team, see below (but still not sure where to place it):

    I took a peek at the form on this page (http://dev.be-pixel.com/newsletter/), and logged the call it was making to the account when I signed up. Here's what we saw:

    {
    "id": "12345",
    "email": {
    "email": "examples@mailchimp.com",
    "double_optin": false
    },
    "merge_vars": null,
    "email_type": "html",
    "double_optin": true,
    "update_existing": false,
    "replace_interests": true,
    "send_welcome": false,
    "apikey": "HIDDEN"
    }

    You may notice that there are two instances of the double_optin parameter. One is improperly placed within the "email" struct, and the other is properly placed later in the call and set to "true".

    This means you'll want to make sure to remove the first instance of the double_optin parameter from the email struct and replace the "true" value for the second instance with "false". Then folks will no longer have to confirm their subscriptions to be added to the list.

    ReplyDelete
  8. hi i need to add a batch of subscribers to mc. how could it be possible by using the list batch subscribe function

    ReplyDelete
  9. My double optin code doesnt seem to work. Could you please take a quick look?

    $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => $email, 'double_optin' => false));

    ReplyDelete
  10. How does one use the API to create a two-step signup process? Like this:

    Step 1:

    The website shows a sign up form with just an email field and a subscribe button. Once someone fills out her/his email address and hits 'Subscribe', the email address gets added to the list (single opt-in, triggering a welcome email), and then additional options show up in a modal window (name, location, interests, etc.)

    Step 2:

    At this stage the user has already been added to the mailing list. The user can now choose to fill in the additional fields in the modal window (which will then be added to her/his account), or if he doesn't, then certain default values are added, after which a thank you message is shown.

    Any help would be greatly appreciated! Thank you.

    ReplyDelete
  11. For working single opt-in just open Mailchimp/Lists.php and change this:

    public function subscribe($id, $email, $merge_vars=null, $email_type='html', $double_optin=true, $update_existing=false, $replace_interests=true, $send_welcome=false)

    to this:

    public function subscribe($id, $email, $merge_vars=null, $email_type='html', $double_optin=false, $update_existing=false, $replace_interests=true, $send_welcome=false)

    Just tested this. Good luck

    ReplyDelete
    Replies
    1. We can call like this: $subscriber = $Mailchimp_Lists->subscribe($list_id, array('email' => $email), null, 'html', false);

      Delete
  12. I just followed your instruction, but i got the error
    {"status":"error","code":-100,"name":"ValidationError","error":"The email parameter should include an email, euid, or leid key"}

    ReplyDelete
  13. Hi, I read your new stuff daily. Your writing style is witty, keep it up!


    My blog ... Eric D Gray

    ReplyDelete
  14. Its not working I am getting the following error.
    http://localhost:8888/dev/html/codrops/php/mailchimp2/src/subscribe.php 500 (Internal Server Error)
    jquery-1.11.0.js:4 sendjquery-1.11.0.js:4 n.extend.ajax(index):2366 (anonymous function)jquery-1.11.0.js:3 n.event.dispatchjquery-1.11.0.js:3 r.handle

    ReplyDelete
  15. It's not working for me, either. Everytime I enter a valid email address, the form spits out the email as invalid. :/

    ReplyDelete
  16. Hi, thanks for code, I wprapped last line if try => catch block to stop exception if email is already on list..

    ReplyDelete
  17. The code doesn't work. Every time I put in an email address that meets the requirements, it is rejected.

    ReplyDelete
  18. Hello, I solved the double opt-in problem editing directly the subscribe functions on Mailchimp/Lists.php

    There you'll see that the parameter double_optin set to true.
    This is the reason why it is not working the parameter that we are sending.

    Set the parameter to false and works.

    Regards.

    ReplyDelete
  19. Great Artitcle!
    It seems that a lot of people are having issues with the double opt-in. I was able to disable double opt-in by assigning a variable "$double_optin" and setting it to false. I also, created variables for the other arguments.

    Ex:
    $list_id = "abcd1234";
    $email = array('email' => htmlentities($_POST['email']));
    $merge_vars = array('FNAME' => 'John','LNAME' => 'Doe');
    $email_type = 'html';
    $double_optin = FALSE;

    $subscriber = $Mailchimp_Lists->subscribe($list_id, $email, $merge_vars, $email_type, $double_optin);

    Hope this helps!

    ReplyDelete
  20. Thank you for your tutorial. I am struggling to get this to work. As far as I know I have entered the code correctly but when I enter a valid email address and hit submit all I get is the message from the jQuery "Adding your email address..." Any advice on what to try next?

    ReplyDelete
  21. Very nice tutorial! and is going perfectly!!
    Now the next step for me is how to unsubscribe (or delete) from a list.
    My main problem is how to find the euid and the leid indicated on the api doc

    ReplyDelete
  22. How we send campaign using campaing id to mutliple user via mail using php for mailchimp

    ReplyDelete
  23. This is exactly what I was looking for. Thanks for the code examples.

    ReplyDelete
  24. I don't see this working, and it produces errors. Could be me but it is old.

    ReplyDelete
    Replies
    1. its working ,you just download mail chimp lib and integrated them

      I have tried it Now

      Thanks
      Mahendra

      Delete
  25. Hello,

    is there any way to send First Name and Last name in subscription confirmation mail

    ReplyDelete
  26. hi
    I'm Rino from Tuscany(Italy) Sorry for my english.....Your script does't work for me ...but ..Are you used the latest release of api??the v2 ..can do you make a step by step guide to realize something like that from the library's download if it's possible .I also have problems using composer to download the package
    thanks a lot
    Rino

    ReplyDelete
    Replies
    1. Did you download all files from here https://bitbucket.org/mailchimp/mailchimp-api-php ?

      Delete
  27. Hello Saba!

    Thanks for the tutorial, it´s great.

    I was using api 1.3 and getting long error logs on my server.

    But i´m facing a issue with this code, when a email is Already Subscribed,
    i´m getting a error log on server.

    Best Regard´s
    Vitor

    ReplyDelete
  28. Simple and clear, great work!
    In another way, we don't need to create a new 'Mailchimp_Lists' object. Just do :

    $api = new Mailchimp('[API_KEY]');
    try{
    $api->lists->subscribe('[LIST_ID]', array('email' => $_POST['email']));
    echo 'success';
    }catch(Mailchimp_Error $e){
    echo 'fail'; //echo $e->getMessage();

    }

    ReplyDelete
  29. Great job :)
    I'm trying to use your code but give me this error message ("Fatal error: Uncaught exception 'Mailchimp_HttpError' with message 'API call to lists/subscribe failed: couldn't connect to host'"). Anyone know why?

    ReplyDelete
  30. Hi, It's nice tutorial for using MailChimp.
    I want to use my template. How I can i use it.

    ReplyDelete
  31. cant download anything from the link provided for the API.
    And there is no email added in mailchimp

    ReplyDelete
  32. Thank you for your tutorial. I am struggling to get this to work.

    ReplyDelete
  33. Thanks for this : )

    ReplyDelete
  34. Hi, i'm trying to implement this code into my wordpress theme. I have coppied the code above top my frontpage.php where i want the signup form to be displayed and uploaded the Mailchimp.php and folder to my themes folder. The php crashes at this line
    $subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['email']) ) );

    it's the same as yours so don't know why any ideas?

    ReplyDelete
  35. Every thing is working, but how can i get the email wich subscribed ?

    ReplyDelete
  36. I have done every thing but its not working. this is always says "The email address you entered was invalid. Please make sure you enter a valid email address to subscribe".

    ReplyDelete
  37. hi, i need php code for sending mail from webpage for subscriber list in mailchimp.

    ReplyDelete
  38. It's actually a great and useful piece of information. I am glad that you
    just shared this helpful info with us. Please stay us informed like this.
    Thank you for sharing.

    ReplyDelete