How to create Mailchimp form in AMP

Mailchimp form in AMP. Introduction.

If you are migrating your non-AMP pages to AMP then making Mailchimp subscription forms works smoothly can be a headache. The reason is, AMP uses the amp-form extension to create forms that work on XHR (XMLHttpRequest or well known as Ajax). Also, you can not use the “action” attribute in forms for HTTP Post requests in AMP( embed form code provided by Mailchimp).

I found how to work with amp-form on the official AMP page here, but it’s more like a generic tutorial. There are other resources on the internet also but they are either incomplete, simply don’t work, obsolete which don’t work with new AMP versions, and of course, paid ones. So I decided to do it myself and I am posting my work on how to create MailChimp form in AMP in a crisp and consumable way here. It’s valid for migrating non-AMP to AMP also. If you want to set up an Email subscription in non-AMP pages, please refer to my post on Email subscription for WordPress Site.

Approach

Since the amp-form uses Ajax whose response headers are not what MailChimp expects so one thing is sure, we can’t use amp-forms to directly interact with Mailchimp. To have Mailchimp forms in AMP, we will write an intermediate endpoint in our server which glues amp-form based forms and Mailchimp. I am using WordPress so the endpoint is in PHP but the same approach can be extended to non-WordPress hosted sites in ASP, JSP, etc also. To keep things neat, simple, and scalable we will use Mailchimp APIs instead of direct action URLs. The benefit of using API is that you can extend the solution to any other content marketing provider which offers APIs. Let’s do it step by step.

Step 1. Get Mailchimp API token

To use Mailchimp API you need an API key and Audience ID, which you can easily get from your Mailchimp account. Login to Mailchimp and select “Accounts” from the drop-down menu at the top right corner. In the new window go to “Extras->API key“:-

Mailchmp Menu

Scroll down and go to the “Your API Keys” section. Here you can see the API key and if not click on the button “Create a Key“:-

Mailchimp API key

Copy the API key and keep it safe for further reference. Don’t disclose it to anybody. Next thing we need is Audience ID which is like a reference to which list of audience we want the new user details to be added. If you are setting up Mailchimp for first time then first create an Audience List( which can be empty). Select “Audience->Audience dashboard” from the top menu :-

Audience Dashboard

Click “View Reports” and in the newly opened window select “Settings->Audience name and defaults” to get your audience id as below:-

Audience Id

Copy the Audience ID and keep it safe for further reference.

Step 2. Create an intermediate server endpoint

Here comes the most interesting part. Let’s write the server endpoint which receives XHR request from the amp-form, pushes it to Mailchimp using the API and returns the response(success/failure) back to amp-form. I have already written the code for this, so just copy below code and paste it in your favourite editor :-

<?php if (!empty($_POST)) { $msg = ''; $email = isset($_POST['email']) ? $_POST['email'] : ''; if (!empty($email) && !filter_var($email, FILTER_VALIDATE_EMAIL) === false) { // MailChimp API credentials $apiKey = ''; $audienceID = ''; // MailChimp API URL $memberID = md5(strtolower($email)); $dataCenter = substr($apiKey, strpos($apiKey, '-') + 1); $url = 'https://' . $dataCenter . '.api.mailchimp.com/3.0/lists/' . $audienceID . '/members/' . $memberID; // member information $json = json_encode(['email_address' => $email, 'status' => 'subscribed', ]); // send a HTTP POST request with curl $ch = curl_init($url); curl_setopt($ch, CURLOPT_USERPWD, 'user:' . $apiKey); curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_TIMEOUT, 10); curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_POSTFIELDS, $json); $result = curl_exec($ch); $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch); if ($httpCode == 200) { $msg = 'You have successfully subscribed to DigitalBetel'; } else { switch ($httpCode) { case 214: $msg = 'You are already subscribed.'; break; default: $msg = 'Some problem occurred, please try again.'; break; } } } else { $msg = 'Please enter valid email address.'; } } header("access-control-allow-credentials:true"); header("access-control-allow-headers:Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token"); header("access-control-allow-methods:POST, GET, OPTIONS"); header("access-control-allow-origin:" . $_SERVER['HTTP_ORIGIN']); header("access-control-expose-headers:AMP-Access-Control-Allow-Source-Origin"); // If your site uses HTTP. Change it to HTTP here. header("amp-access-control-allow-source-origin:https://" . $_SERVER['HTTP_HOST']); header("Content-Type: application/json"); $output = ['msg' => $msg]; header("Content-Type: application/json"); echo json_encode($output); ?>
Code language: PHP (php)

In-Line 9 and 10 above, put your API key and Audience ID found in step1 respectively. Name the file to “mailchimp.php” and save it. Now open an FTP connection to your server and go to the “public_html” folder and upload “mailchimp.php” there (it’s with respect to WordPress. For any other site, you can put it at any location from where it can be hosted). Our endpoint is ready now.

Step 3. Client side AMP form

Now we need to create a client-side AMP-compatible form that users can use to subscribe. Import the amp-form javascript extension and amp-mustache for the client-side rendering of response. Open the “header.php” file of your theme in the theme editor and copy-paste below two lines in between <head> and </head> tags and save it:-

<script async custom-element="amp-form" src="https://cdn.ampproject.org/v0/amp-form-0.1.js"></script> <script async custom-template="amp-mustache" src="https://cdn.ampproject.org/v0/amp-mustache-0.2.js"></script>
Code language: JavaScript (javascript)

Further create a form which uses AMP’s “action-xhr” attribute instead of “action” in forms with method as post and redirecting to “mailchimp.php” as follow :-

<form name="submit" method="post" action-xhr="https://<your-domain.com>/mailchimp.php" target="_blank"> <input type="email" name="email" placeholder="email@domain.com" required> <input type="submit" value="Subscribe!" name="subscribe" id="mc-embedded-subscribe" class="button"> <div submit-success> <template type="amp-mustache"> Great.{{msg}} </template> </div> <div submit-error> <template type="amp-mustache"> Sorry! {{msg}} </template> </div> </form>
Code language: HTML, XML (xml)

Replace “your-domain.com” in Line 1 with your real domain. Paste this code wherever you want to display the subscription form. WordPress users can even put it in the “custom-HTML” widget also. publish the changes and your Mailchimp form in AMP is ready for use.

Let’s verify

Open the form’s page and enter email id as a user and click subscribe. On successful form submission, you will see:-

Succesfull subscription

If you find the post helpfull, you can thank me by commenting or sharing the post.

Click here to view posts you may like.

Leave a Reply

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