Ian
Ian

Reputation: 7558

Use the Mailchimp API

I'd like to use the Mailchimp Node.js API in my Parse Cloud Hosting app to subscribe a user to a mailing list. Parse doesn't support NPM but, given that the Mailchimp API has no dependencies, I thought I'd be able to copy the code into my project. However, the Mailchimp API uses the "https" module which Parse doesn't support.

Does anyone know of a way around this?

Upvotes: 6

Views: 6514

Answers (3)

KBog
KBog

Reputation: 4650

Here's how I got it to work using the MailChimp API v3.0, the method below supports adding/updating a subscriber, as well as adding/removing him to/from a Group!

Prerequisite: You need to get an MD5 hash method to convert the user's email into a hash.

    var jsmd5 = require('cloud/md5js.js');

    // here replace that with your own data center (by looking at your API key).
    var datacenter = "us13";
    var MAILCHIMP_URL = "https://<any_string>:<apikey>@" + datacenter + ".api.mailchimp.com/3.0/";
    var MAILCHIMP_LIST_NEWSLETTER_ID = <yourlistId>;

    Parse.Cloud.define("SubscribeUserToMailingList", function(request, response) {

      if (!request.params ||
            !request.params.email){
        response.error("Must supply email address, firstname and lastname to Mailchimp signup");
        return;
      }

      var email = request.params.email;
      var firstName = request.params.firstname;
      var lastName = request.params.lastname;

      // this converts the email string into an MD5 hash.
      // this is Required if you want to use a "PUT" which allows add/update of an entry, compared to the POST that allows only adding a new subscriber.
      var emailHash = jsmd5.MD5(email);

      var mailchimpData = {
        'email_address': email,
        'status': "subscribed",
        'merge_fields': {
          'FNAME': firstName,
          'LNAME': lastName
        },
        'interests': {
          "<groupID>": true  // optional, if you want to add the user to a "Group".
        }
      };

      var url = MAILCHIMP_URL + "lists/" + MAILCHIMP_LIST_NEWSLETTER_ID + "/members/" + emailHash;

      // using a "PUT" allows you to add/update an entry.
      Parse.Cloud.httpRequest({
        method: 'PUT',
        url: url,
        body: JSON.stringify(mailchimpData),
        success: function(httpResponse) {
          console.log(httpResponse.text);

          response.success("Successfully subscribed");
        },
        error: function(httpResponse) {
          console.error('Request failed with response code ' + httpResponse.status);
          console.error(httpResponse.text);

          response.error('Mailchimp subscribe failed with response code ' + httpResponse.status);
        }
      });
    });

Upvotes: 2

Akshaya Moorthy
Akshaya Moorthy

Reputation: 307

  1. Install mailchimp in your project

    npm install mailchimp-api
    
  2. From client controller call the server-controller with required data
    Don't forget to add $http to the top of controller

    $http({
        method : 'POST',
        url : '/mailchimp-users/subscribe',
        data : {user:this.name}}).
            success(function(response) {
        console.log("hai this is basic test" + response);
        $scope.send = response.message;
    }).error(function(response) {
        $scope.error = response.message;
    });
    
  3. In server controller Add this to the beginning of page

    var MailchimpUser = mongoose.model('MailchimpUser'),
    _ = require('lodash'),
    mcapi = require('mailchimp-api');
    var apiKey = '4bf6fb8820c333da4179216c3c2ef8fb-us10';
    // Change this to your Key
    var listID = 'ebbf193760';
    var mc = new mcapi.Mailchimp(apiKey, {version: '2.0'});
    

    Add this function

    exports.subscribe = function(req, res) {
        var entry = req.body.user;
        var mcReq = {
            apikey: '4bf6fb8820c333da4179216c3c2ef8fb-us10',
            id: 'ebbf193760',
            email: {email: entry + '@gmail.com'},
            merge_vars: {
                FNAME: 'subscriber-first-name',
                LNAME: 'subscriber-last-name'
            },
            'double_optin': false,
            'send_welcome': true
        }
        // submit subscription request to mail chimp
        mc.lists.subscribe(mcReq, function(data) {
            console.log(data);
        }, function(error) {
            console.log(error);
        });
    };
    
  4. Add this route your route file

    app.route('/mailchimp-users/subscribe')
       .post(mailchimpUsers.subscribe);
    

Upvotes: 5

Ian
Ian

Reputation: 7558

I've been unable to use the Mailchimp API directly but the REST API is pretty easy to use.

In main.js, create a Cloud Function. Enter your API key and update the REST URL to point at the correct Mailchimp data center (http://apidocs.mailchimp.com/api/2.0/)

var mailchimpApiKey = "<<REPLACE_WITH_YOUR_KEY>>";

Parse.Cloud.define("SubscribeUserToMailingList", function(request, response) {

  if (!request.params ||
        !request.params.email){
    response.error("Must supply email address, firstname and lastname to Mailchimp signup");
    return;
  }

  var mailchimpData = {
    apikey  : mailchimpApiKey,
    id      : request.params.listid,
    email   : {
      email : request.params.email
    },
    merge_vars : request.params.mergevars
  }

  var url = "https://<<REPLACE_WITH_DATA_CENTRE>>.api.mailchimp.com/2.0/lists/subscribe.json";

  Parse.Cloud.httpRequest({
    method: 'POST',
    url: url,
    body: JSON.stringify(mailchimpData),
    success: function(httpResponse) {
      console.log(httpResponse.text);

      response.success("Successfully subscribed");
    },
    error: function(httpResponse) {
      console.error('Request failed with response code ' + httpResponse.status);
      console.error(httpResponse.text);

      response.error('Mailchimp subscribe failed with response code ' + httpResponse.status);
    }
  });

});

Then, in the code which calls this function... (replace your list ID)

Parse.Cloud.run("SubscribeUserToMailingList", {
    listid      : "<<REPLACE_WITH_LIST_ID>>",
    email       : email,
    mergevars   : {
        FNAME   : firstName,
        LNAME   : lastName
    }
})
.then(function(success){
    console.log("Successfully subscribed");
    // ...
},
function(error){
    console.log("Unable to subscribe");
    // ...
});

Upvotes: 9

Related Questions