Labs - February 8, 2010

AS3 MailChimp Library

While building our awesome new website, we wanted to ensure that users could easily subscribe to our newsletter through the Flash version, without having to be redirected anywhere else. Convenience is king, and we wanted to deliver it!

We use MailChimp, the best email marketing platform available! And luckily, they have a great API to work with. Through Flash, we were able to add subscribers to our list and also return any results, i.e. error or success.

While searching Google I found an article by Christian Cox on MailChimp’s API and AS2, but that wasn’t enough.  We needed a nice AS3 version of the code. So Justin and I put together this nice, simple code that should work for anyone. If I had more time I would definitely make a class.. Perhaps later this month.


//api and list id keys
var _api:String = "MAIL_CHIMP_API_KEY_HERE";
var _listID:String = "LIST_ID_HERE";

//text box handler
emailAddress.text = "email address";
emailAddress.tabIndex = 1;
emailAddress.addEventListener(FocusEvent.FOCUS_IN, txtFocusIn);
emailAddress.addEventListener(FocusEvent.FOCUS_OUT, txtFocusOut);

function txtFocusIn(e:FocusEvent) {
        emailAddress.text = "";
}
function txtFocusOut(e:FocusEvent) {
        if (emailAddress.text == "") {
                emailAddress.text = "email address";
        }
}

//button setup
submitBtn.buttonMode = true;
submitBtn.addEventListener(MouseEvent.CLICK, submitForm);

function submitForm(e:Event) {

        var email:String = emailAddress.text;

        //check if valid
        if (isValidEmail(email)) {

                //set response text
                responseText.text = "sending...";

                //disable the submit button
                submitBtn.removeEventListener(MouseEvent.CLICK, submitForm);

                //setup POST
                var variables:URLVariables = new URLVariables("method=listSubscribe&output=xml&apikey=" + _api + "&id=" + _listID + "&email_address=" + email + "&merge_vars=");
                var request:URLRequest = new URLRequest();
                request.url = "http://api.mailchimp.com/1.2/?method=listSubscribe";
                request.method = URLRequestMethod.POST;
                request.data = variables;

                var loader:URLLoader = new URLLoader();
                loader.dataFormat = URLLoaderDataFormat.VARIABLES;
                loader.addEventListener(Event.COMPLETE, completeHandler);

                try {
                        trace("loading...");
                        responseText.text = "loading...";
                        loader.load(request);
                }
                catch(error:Error) {
                        trace("unable to load URL");
                        responseText.text = "Oh, that's embarassing. something went wrong, please try again. Thanks!";
                        trace(e.target.data);
                }
                function completeHandler(e:Event) {
                        var _t:String = unescape(e.target.data); //decode the uri

                        var _xml:XMLList = new XMLList(_t); //parse the xml
                        trace(_xml.@type);
                        if (_xml.@type == "array") { //check to see if there is an error
                                trace(_xml.error);
                                responseText.text = _xml.error;
                                resetForm();
                        } else if (_xml.@type == "boolean") { //check to see if successfully added
                                trace("successfully added to list");
                                responseText.text = "You have beeen successfully added to our list. Thank you!";
                                resetForm();
                        }
                }

        } else {
                trace ("email invalid");
        resetForm ();
                responseText.text = "invalid email!";
        }

}

//validate given email
function isValidEmail(_e:String):Boolean {
        var exp:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
    return exp.test(_e);
}

//reset the form elements
function resetForm(){
        submitBtn.addEventListener(MouseEvent.CLICK, submitForm);
        emailAddress.text = "email address";

}

Done and done. Pretty easy, right? You can also download the mailchimp_api.

UPDATE: A new version has been created that includes First and Last Name data collection [mailchimp_api_1.3].

  1. How Blogging Can Attract Business | kohactive | Web Design Chicago | Interactive Design Chicago | Online Marketing | Search Engine Optimization | Web Application Development on March 11th, 2010 -

    [...] to set up the situation. A few months ago I was looking for a solution to a problem with regards to Flash Web Development and MailChimp Integration and when I couldn’t find the answer I decided to develop my own. After a few [...]

  2. lia on April 19th, 2010 -

    I am attempting to use this code and the framework to setup the mail option on my flash website. I am having a very difficult time. How do I get the form on the page to begin with? I copied the frame and inserted it into a new layer, and then applied the action script to that frame, but I am continually receiving an error at line 34
    setTextBoxes(); //call the function

    //button setup
    submitBtn.buttonMode = true;
    submitBtn.addEventListener(MouseEvent.CLICK, submitForm);

    function submitForm(e:Event) {

    var email:String = emailAddress.text;
    var firstName:String = firstName.text;
    ***var lastName:String = lastName.text;**** (problem line)

    I thought this would be easier to integrate than starting a new website in HTML but it hasn’t been.

    PLEASE HELP!!!

  3. john on April 28th, 2010 -

    Hi Lia,

    I apologize for the delayed response.

    If you are going to collect first name, last name and email address then all you need is to add three text fields to the stage and name them firstName, lastName and emailAddress, respectively.

    Your submit button should be called “submitBtn” and will automatically trigger the function.

    Let me know if you have any further issues. I’m glad to help.

  4. a guy on May 18th, 2010 -

    Correct me if I’m wrong, but doesn’t the MailChimp API give dang near full access to the MailChimp account needing nothing but the API key? I’m looking through the API and it’s staggering the amount of access that is given just by having the API key to the account. Reading all your campaign and list information, deleting campaigns, even creating new campaigns. I believe that MailChimp intended their API keys to be used server side only and never visible to the client side, and by putting it freely viewable on the client side you are opening yourself to enormous breaches of security.

    I haven’t used the MailChimp API a lot, but at first glance I’m struck at the amount of control over the account is given just from having the API key and I’m hoping you have some extra information that I don’t that will show me I’m wrong about this.

  5. jorge on July 8th, 2010 -

    i keep getting this error, either testing offline or uploading the swf to my site

    Error opening URL ‘http://api.mailchimp.com/1.2/?method=listSubscribe’
    Error #2044: Unhandled ioError:. text=Error #2032: Stream Error. URL: http://api.mailchimp.com/1.2/?method=listSubscribe
    at mailchimp_api_fla::MainTimeline/submitForm()

  6. jorgeotero on July 10th, 2010 -

    fixed. just had to send name and last name with the email

  7. admin on July 10th, 2010 -

    jorge,

    Yeah the attached code does require a first and last name to be submitted. If you look at the code that is highlighted in the post above it offers a API call that does NOT require a first/last name.

    If you have any issues let me know and I’ll email you a source file without the first/last name.

    jk