Enabling SMS subscriptions to your MailChimp list using Plivo, Part 2

This example is an excerpt from my book, Building Phone Applications, which shows you step-by-step how to build voice and SMS applications using Plivo and some basic PHP. If you enjoy or find this useful, you should check out the book for more applications like this one.

In Part 1 I showed you how to build a really simple Plivo application to add subscribers to your MailChimp lists via SMS. This week we’re going to improve that application to be a little smarter and more interactive.  This example is taken from my book, Building Phone Applications, so if you find it interesting or useful checkout the book for more example applications like this.

Adding some smarts

Right now our application will give an error when anything other than a single email address is sent. What if our user texts us “My email is [email protected]”? Right now John will get a response with an error. That’s not very friendly.
If we want to enhance our user experience and make our application act more natural, which is why we’re using SMS in the first place, we need to add some basic intelligence.

Extracting the email address

One easy thing we can do is to run our $text string through a quick regex to extract the email address out of the nominally complex string. I’m not a regex wizard, but luckily this is a fairly common problem and I was able to find a somewhat elegant solution on StackExchange

preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i", $text, $matches);
$email = $matches[0];

This will go through the $text variable which is the content of the SMS message and place anything that looks like an email address into the $matches array. We’ll just take the first entry and assign it to the $email variable. We’re using multiple variables in this example just to keep the code logical and readable. Understand this isn’t necessarily the most efficient way to do this.
So if we add this regex statement before our email validation we can dump anything from the SMS message that doesn’t look like an email address and just save the email address.

Now our email check code looks like this…

preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i", $text, $matches);
$email = $matches[0];

if (filter_var($email, FILTER_VALIDATE_EMAIL)) { 
   ## Subscribe the caller
   $MailChimp = new MailChimp('API_KEY');
   $result = $MailChimp->call( 'lists/subscribe', 
				array('id' => 'LIST ID', 'email' => array('email'=> $email)));
        if ($result){
                 $body = "Thanks! Check your email to confirm your subscription";
                 }
}else{ //Email didn't Validate
        $body = "Sorry, that does not look like a valid email";
        }

saving the phone number

One of the other neat things we can do is save the sender’s phone number to their MailChimp profile. This can come in handy if we want to later enable SMS notifications to our subscribers, or just if we want to verify the sender later. To do this we’re going to use the Merge Variables functionality in MailChimp. These are the extra bits of profile data that can be used with your mailing lists, for example FNAME, etc.

We know that the sender’s phone number is stored in the $from variable. We’ll just add the new MERGE_VAR to the list/subscribe call we make the MailChimp.

 $result = $MailChimp->call( 'lists/subscribe', 
				array('id' => 'LIST ID', 'email' => array('email'=> $email), 'merge_vars' => array('phone' => $from)));

So now our whole script looks like this:

require_once 'lib/plivo.php';
require_once 'lib/mailchimp.php';
# Create our variables from the Plivo message
    $to = $_REQUEST['To'];
    $from = $_REQUEST['From'];
    $text = $_REQUEST['Text'];

## Get the email out of the text
preg_match("/[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})/i", $text, $matches);
$email = $matches[0];

## Validate the email address
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
   ## Subscribe the caller
   $MailChimp = new MailChimp('API_KEY');
   $result = $MailChimp->call( 'lists/subscribe', 
                                array(
                                        'id' => 'LIST_ID',
                                        'email' => array('email'=> $email),
                                        'merge_vars' => array('phone' => $from)
                                ));

## Make sure the MailChimp call worked
        if ($result){
        	$body = "Thanks! Check your email to confirm your subscription";
            }
	}else{ //Email didn't Validate
        $body = "Sorry, that does not look like a valid email";
        }

##Setup the Plivo Response      
$params = array(
            'src' => $to,
            'dst' => $from,
			);
$r = new Response(); 			//Create the Plivo response object
$r->addMessage($body,$params); 	//add the reply message to the response
header('Content-type: application/xml'); // Plivo is expecting XML
echo $r->toXML(); 	

That’s it

So now we’ve got our script to answer the SMS webhook from Plivo, pull the email address out of the text, and subscribe the sender to our MailChimp list and save their phone number. You should now be able to customize this further if you would like. If you would like to get more applications like this delivered free by email go ahead and join my mailing list or check out my book, Building Phone Applications, and as always, I hope you find this useful, if not feel free to reach out and let me know how to improve these examples.

You may also like...

2 Responses

  1. Braden Heckman says:

    The “Answer URL” is required in the Plivo Application Form. You don’t mention it here. What would be appropriate in that field?

    • Vince says:

      The Answer URL is the script that is called when you receive an incoming call, in this case it isn’t used, so it really doesn’t matter. If you wanted to round out the user experience you could point this to a script that uses to read an error or direct callers to your site.

Leave a Reply

Your email address will not be published. Required fields are marked *