Creating a Facebook Page Newsletter Signup Form

Advertisements

Recently, I started subscribing my blog visitors to a newsletter. Also, signup below and thank you. Anyway, I started using MailChimp which is a good service and offers a Facebook Page app for free. Alas, I went ahead and integrated MailChimp into my Facebook Page. However, I found that there was limited customization to the form. For example, I couldn’t reorder or disable the fields. This left the form appearing very odd like asking for a date of birth. Don’t get me wrong, in some cases, that can be necessary but not mine. I wanted just a simple form with First Name, Last Name and Email. As a result, I scoured the interwebs and came across this post which was exactly what I was looking for creating a newsletter signup for a Facebook page. Unfortunately, and as with many blog tutorials, they only take you so far and the rest you need to figure out on your own. That is like all of life overall, really. Anyhow, after reading through the post I found a few items I needed.

  1. I wanted to store my code publicly in GitHub and I don’t want to store my super-secret MailChimp API keys in code. This is just bad practice and never do it.
  2. After a form completes successfully, it should clear the fields. That’s just good user experience and always do it.
  3. I wanted to host this on Microsoft Azure because they have a free websites tier which includes SSL for the azurewebsite.net domain. Which is perfect for a simple Facebook App.

All right that about sums it up, let’s start creating a newsletter signup for a Facebook page using MailChimp, PHP and jQuery.

What ls Needed

  1. A Facebook Page
  2. A MailChimp Account
  3. A Microsoft Azure Account

Don’t have these? I recommend going to Facebook, MailChimp and Azure to create an account. I will not bore anyone with those details.

Software I am Using

  • Visual Studio Code
  • FileZilla
  • Firefox Developer Edition

Overview of Steps

  1. Gather MailChimp API Key and List Id
  2. Create Azure Website
    1. Add Api Key and List Id to Azure Website Application Settings
  3. Create Facebook App
    1. Add Facebook App to Facebook Page
  4. Clone this GitHub Repository
  5. Create validator.js File
  6. Customize index.php File
  7. Customize subscribe.php File
  8. Add web.config File
  9. Deploy to Azure
  10. Test on Facebook Page

Gather MailChimp API Key and List Id

Getting an Api Key

Navigate to your account

mailchimp account link

Select API Keys under Extras

mailchimp api keys link

Select create key

mailchimp creat api key button

Copy the provided API Key and store it somewhere safe.

Getting your List Id

Navigate to your lists

mailchimp account lists link

Select your list

mailchimp list link

Choose List Name and Defaults from the settings drop down

mailchimp lists name and defaults link

In the top right column is your List ID section

mailchimp list id

Grab that and store it in a safe place, preferably, the same place as the API Key

Create an Azure Web App in the free tier

Select the large plus sign at the top left

azure new resource link

Search Web App

azure resource search ui

Enter the required information.

Two things:

  1. Turn on app insights it is an amazing resource for debugging, views and availability.
  2. Make sure to create an App Service Plan in the free tier.

azure create app service form

Add Api Key and List Id to Website Settings

Select resource groups from the top left of the navigation bar

azure resource group navigation button

Select your new resource group

azure resource group link

Select Application Settings

azure web app application settings link

Scroll down to the App settings section and enter the following

azure app settings form

Delete the Additional Default Documents

Keep the index.php but remove the rest.

azure web app default document list

Save your changes

azure app settings save button

Create Facebook App

This is straight forward. Head over to developers.facebook.com, setup your account and select add a new app.

facebook add a new app drop down

Add your display name and email.

facebook create a new app id form

Here it will land on the select product page, don’t bother with this. Just go to Settings.

facebook app settingsd navigation button

Select + Add Platform and choose Page Tab

facebook add platform ui

On the App and Page Tab section enter your app domain, Secure Page Tab URL and Page Tab Name

facebook page tab and app id settings

Save Your Changes.

Adding the App to your Page

Simply, sign in, edit the below URL with the app id and secure page tab URL, navigate to it via web browser and select the desired page.

http://www.facebook.com/dialog/pagetab?app_id=FB_APP_ID&next=FBAPP_SECURE_URL

Clone GitHub Repository

Navigate to your repos folder

command prompt to navigate to development folder

command prompt to clone git repo

Create the validator.js File

Below is the validator.js file. Just move the original code into this file and reference in the index.php file.

validator.js file snapshot

There is really no change compared to the original post. Furthermore, there was a comment on the post to clear the form upon successful submission. The writer said to just use the submit handler with some added code to the post function. However, this would clear the form each time and the end user would need to re-enter their information. Not a good user experience. I moved the functionality to the subscribe.php document on a failed submission as noted below.

Customize index.php

At this point, anyone can go and download my GitHub repo, deploy it to Azure and have an app up and running but I want to discuss the changes I made to index.php. Below is the code:

index.php file snapshot

First, I moved the jQuery script into an external file source appropriately named validator.js. Having JS in your HTML is untidy. Second, I moved the references to JavaScript files below the content in the body. This gives a perceived faster page load time.

Customize the subscribe.php File

I improved the subscribe file with 2 changes.

Code for the first section.

subscribe.php file snapshot 1

The added section removes the Api Key and List Id hard coded variables. In addition, I search the folder for a debug.ini file to read debug settings if developing locally which I provide a detailed walkthrough here on a Windows machine. If the file is missing, I then do a switch case on the key/value pairs of server variables which includes the application settings we manually set in the Add Api Key and List Id to Website Settings section. This enables scalability and simple change configuration management.

Code for the second section.

subscribe.php file snapshot 2

In the second change, I echo out a script to clear out the form on success. If the MailChimp Api fails, I only output a dummy message. Before, it was reading out a verbose message which I do not want end users reading or even thinking about.

Add Custom Web.config File

The final file that I added is optional and only needed for hosting on Azure or IIS. The infamous web.config file. Below is the code.

web.config file snapshot

I created rules to force SSL redirect and rewrite all requests to index.php. This is because Facebook forces all apps to use SSL and Azure web apps provides a free SSL with the azurewebsites.net domain. In addition, I don’t want people hijacking requests using different default documents which is why I removed them in the Create Azure Web App step. I personally don’t think forcing SSL is a terrible thing. Every website should do it.

Deploy to Azure

In the web app on Azure, navigate to your web app

azure web app link

Select get publish profile and save it in a safe place

azure web app get resource publish profile button

The publish settings file is just xml with a different file extension. In the publish settings file, search for FTP and grab the Host, Username and Password and enter them in your favorite FTP client.

filezilla ftp client site manager

Copy your files over to the wwwroot folder in Azure and voila! App deployed.

Conclusion

Navigate to the Facebook page and there it is.

newsletter signup form on facebook page

Now, go forth and style the form as desired. In fact, I plan to add the MailChimp icon so that end users are more comfortable providing their first name, last name and email.

For the record, I am aware that I could’ve just deployed the original post’s GitHub repo with my super-secret keys in the code and it would work just fine. But I am a stickler for best practice and simplicity. Knowingly, it seems simpler to just put the repo out there but if I take extra care to deploy and configure the app properly, in the long-run, it is simpler. Trust me. Lastly, my GitHub repository is here. Please feel free to reach out if you have any questions. Happy dev’ing.

Advertisements

Migrating a WordPress DB from MySQL in-app to MySQL on Azure

Advertisements

Let me tell you a secret. I have been running my blog on the MySQL in App instance provided with each Azure App Service web application for the last few months. Yes, I know that is not a best practice. However, I didn’t want to have to do the ClearDb or host a Linux VM options and I knew Azure would have a MySQL service someday. Today, 5/10/2017, Microsoft announced a new service available in-preview on Azure. They are offering a Database-as-a-Service (DBaaS) for MySQL and PostgresSQL in addition to the SQL Server service. Get excited! You can read all about the service, pricing and documentation here. This post is about migrating a WordPress db from the MySQL in App instance to this new service. You can read more about the in-app instance here, but the goal of the in-app feature was only for development. Hence, the need to migrate, asap.

Overview

Software Tools

  1. Any web browser
  2. Visual Studio Code
  3. MySQL Workbench
  4. Any ftp client
  5. Optionally, phpMyAdmin

Steps

  1. Assumptions and Preparations
  2. Create an Azure Database for MySQL
  3. Export and Importing the Existing Database
  4. Deploy WordPress to Staging Environment
  5. Swap Production and Staging Environments

Let’s begin.

Assumptions and Preparations

I am assuming a couple of things about the audience for this post. First, that you have a valid Azure subscription and know what PaaS means. Second, you are familiar with administering a WordPress blog running in an Azure App Service using the Standard pricing tier.

This last bit of preparation is configuration. Let me start by saying, configuration management is difficult even for small apps. I originally deployed this app with the idea of only having a staging site and a production site. However, this was not feasible as there was some weird issues with the MySQL in-app between the 2. As a result, I just use my development environment as the testing ground before production. Additionally, I don’t install any plugins in dev they are all installed in prod, backed up and copied down to dev. Anyway, I originally configured the wp-config.php file to dynamically read the server environment variables so that I wouldn’t have to reconfigure each environment. Because that is a pain. Below is the code I used for this. Once I got this working it was nice not to have to remember configuration settings for each environment. You are welcome to use this. If you only have one deployment I don’t think you will have to but you can. Here is a gist for you.

custom wordpress config file

Create an Azure Database for MySQL

This step is simple enough. Just search for the service and follow the prompts. However, once the database completes deploying there are 2 things required.

  1. Ensure the force SSL is disabled.

    azure enable ssl settings

  1. Add a firewall rule to allow all IP’s. This was s setting I discovered by creating a Web App + MySQL test application in Azure from the Marketplace.

    azure mysql db firewall settings

Exporting the Existing Database

There are 2 options, maybe more and not even one is better than the next. I will discuss the options I tried and note the one that I went with because it’s easier.

Option 1: Using phpMyAdmin

This is the less preferred method because I am not really a fan of phpMyAdmin but it is the method provided in the WordPress codex here.

phpmyadmin export tables

Exporting this way will provide you with a SQL file that you can then run against your new database.

NOTE: This script shows creating the database. Just manually create your database in your new SQL Database for MySQL via MySQL workbench. Also, don’t use localdb. That is for demo purposes.

phpmyadmin export sql file

Option 2: Using the Azure Portal

This is the preferred method and extremely simple. It’s like the Azure devs knew that the in-app instance would need an export function. It’s as simple as just entering the security credentials to the MySQL Server and clicking a button. So, here are some pictures for reference.

Note: I initially had an issue with connecting to the SQL database for MySQL doing this. However, I disabled the force SSL and added the firewall rule and it worked seamlessly.

azure mysql in app export

azure mysql in app export form

azure mysql in app export screen

Deploy WordPress in Staging Environment

This next step you’ll want to test out your work to see if all went well. Luckily, Azure App Service has an excellent feature for that; deployment slots. It’s easy to create a deployment slot. In the production app blade select the section for deployment slots and add a slot. I cloned the source configuration so that things would be identical to test out.

azure create web app deployment slot form

azure web apps deployment slot screen

In the staging deployment turn off the MySQL in App feature.

disable azure web app mysql in app

Also in staging, delete the old application settings specific to the MySQL in App instance and add your connection string. The format of the connection string is Database={dbName};Data Source={dbHost};User Id={userName};Password={password}

delete azure web application settings

This next step requires and FTP client. I use FileZilla but whatever your preference is will work fine. Make sure to configure the ftp client to connect to production and staging. Connect to production and download the production WordPress application code.

filezilla file download

Now, connect to staging and upload the application code.

filezilla ftp file upload

In the wp-config.php file, ensure the database connection string key matches the key from the application settings. Reupload the wp-config.php file via ftp client, if necessary.

wordpress config settings file

Test the staging URL and make sure everything works. Click links, read posts, etc. If all goes well, move to the last step.

Swap Production and Staging Environments

Swap staging and production. This is easy enough, just click the swap button via the staging or production website overview blade. Below is a sample of what the swap button looks like.

azure web app deployment slot swap

Conclusion

Migrating a database is easy in MySQL and I really enjoyed using the MySQL Workbench tool. Additionally, now the site is scalable. Where before it wasn’t because each MySQL in-app instance was unique to the website instance. Meaning, if the site scaled to 100 instances there would also be 100 MySQL in app instances. This alleviates this issue. However, I doubt many users will need to do this but it is documented here. Enjoy.