How to add subscribers to Mailchimp within your Unity game

Mailing list is one of the powerful marketing tools for indie devs. You can read Chris Zukowski’s posts here and here. One of my favorite books, Perennial Seller by Ryan Holiday, also talked about why a mailing list is important to have if you’re a creator that wants to sell. There’s a story that when Kevin Hart was starting out, he had his “team” collect business cards from the audience on his gigs. That was the beginning of his now massive platform. Yeah, he called it that. His platform.

I know of some games that allows mailing list subscription. Their players can subscribe within the game itself. I thought this was clever. Mailchimp is one the most recommended mailing list management software/website out there. Thankfully, it has an API and I’m sure there’s a way to access it via C#. I’m writing this article to show you how so you don’t have to suffer like I did.

Required Software

  • Postman – It’s like a web API tester. It’s also needed to get the “listids” of your Mailchimp account. This will be discussed later. You can download it for free.
  • Unity – It’s the reason why we’re doing this. We’re subscribing players within a Unity app. The version used as of writing is Unity 2020.3.3.

Mailchimp Setup

Assuming you have created an account (go sign up for free), click on your avatar on the bottom left then select Account:

I had a hard time locating this

In the Account page, select Extras > API keys:

In API Keys page, click the Create A Key button. This will create the API key. This is required to make use of the API. It acts as your username and password so keep this key a secret. You can specify a label if you like.

Testing the API

The API documentation can be found here. The Quick Start part is generally helpful but unfortunately there’s no sample for C#. We can use Postman here. Let’s do the equivalent of hello world to Mailchimp API. Let’s do a ping:

Before we can use Postman, let’s identify the URL for the requests. It’s different depending on your API key. The URL is:

https://{data_center}.api.mailchimp.com/3.0

where data_center is the last 3 characters of the API key after the dash. For example, mine is us1. Yours could be us2 or us3. In my case, the URL would be:

https://us1.api.mailchimp.com/3.0

The specific API call is then appended to this URL. For example for ping, the API request URL would be:

https://us1.api.mailchimp.com/3.0/ping

Back to Postman, enter https://us1.api.mailchimp.com/3.0/ping to the address bar. Select GET as the request type. Click on the Headers tab and add the following key-value entries:

  • Content-Type – application/json
  • Authorization – apikey <your API key>

You only do this once. You don’t need to touch it on subsequent requests. It should look like this in Postman:

Don’t mind the API key used here. It’s just garbled numbers. Use your API key.

Now click Send. It should send back a result that looks like this:

Congratulations! You just made your first Mailchimp API call.

Getting the default list_id

After doing the ping successfully, I thought it would be easy to subscribe a subscriber. I’ll just look for that API call and it’s this one:

But hold on, what’s list_id? Where can I get it? This was my major confusion when trying to make this work. I don’t know where to get this list_id. I’ve tried using the members id parameter used in the URL when viewing All Contacts in the website but it doesn’t work.

I thought that if I just have a name and email, I can add that to my subscribers. That’s not the case. Mailchimp maintains contacts in lists. But I didn’t make a list when I signed up. I realized that I can add contacts manually in the website so there must be a default list. I thought further that there must be an API call that gets my current lists, and there really is:

In Postman, I used https://us1.api.mailchimp.com/3.0/lists in the URL and baaam! I got my only list with its id:

Don’t use this list id. Use what appears in yours.

Take note of this id. Copy it somewhere. We’re going to need it when adding subscribers and later in code.

I think that this was really bad UX on Mailchimp’s part. I shouldn’t have to use an API call to get a list id. The different guides that I’ve read don’t mention this, too. They just tell you to use /lists/{list_id}/members without telling how to get such id. Do they just assume that the readers know? Do even web developers themselves automatically know? I would not think so.

Adding a subscriber in Postman

Now that we have the list id, we can finally add a subscriber using Postman with a few tweaks. In Postman, change the request type to POST. Use the URL https://us1.api.mailchimp.com/3.0/lists/{list_id}/members. So in my example, it’s this:

https://us1.api.mailchimp.com/3.0/lists/ca831eb509/members

This API call requires parameters. You need to pass on the name and email. This will be specified as JSON in the request body. In Postman, click on the Body tab then enter the JSON below:

{
	"email_address":"gary@gmail.com",
	"status":"subscribed",
	"merge_fields": {
		"FNAME":"Gary"
	}
}

This is just a test subscriber. The subscriber’s first name is Gary with gary@gmail.com as his email. It should look like this in Postman:

I would say that this is the minimum JSON body required to add a subscriber. If you need the last name, you can just add an “LNAME” field under merge_fields. Now click Send. The response would be a pretty long JSON but as long as it’s not an error, you just added a subscriber. To confirm this, open your Mailchimp account in your browser then go to Audience > All contacts. You should see Gary on top of the table.

Let’s do this in C#

Using Postman was just a test but it also shows a pretty good flow on how it will be translated to C# code. I was referring to this guide while studying this. I just made a few changes. Here’s the method I used to call a Mailchimp API:

private static void CallMailchimpApi(string dataCenter, string method, string requestJson, string key) {
    string endpoint = $"https://{dataCenter}.api.mailchimp.com/3.0/{method}";
    byte[] dataStream = Encoding.UTF8.GetBytes(requestJson);
    WebRequest request = WebRequest.Create(endpoint);
    try {
        request.ContentType = "application/json";
        SetBasicAuthHeader(request, "anystring", key); // BASIC AUTH
        request.Method = "POST";
        request.ContentLength = dataStream.Length;

        Stream newStream = request.GetRequestStream();
        newStream.Write(dataStream, 0, dataStream.Length);
        newStream.Close();

        WebResponse response = request.GetResponse();
        response.Close();
    } catch (WebException ex) {
        Debug.LogError(ex.Message);
        Debug.LogError(requestJson);

        Stream responseStream = ex.Response?.GetResponseStream();
        if (responseStream != null) {
            using StreamReader sr = new StreamReader(responseStream);
            Debug.LogError(sr.ReadToEnd());
        }
    }
}

private static void SetBasicAuthHeader(WebRequest request, string username, string password) {
    string auth = $"{username}:{password}";
    auth = Convert.ToBase64String(Encoding.Default.GetBytes(auth));
    request.Headers["Authorization"] = "Basic " + auth;
}

CallMailchimpApi() is basically the C# translation of what we did in Postman. It will invoke any POST Mailchimp API specified in its method parameter. There’s nothing to worry if there are errors. The function will log those errors but not rethrow the exception so as not to disrupt the flow of the game. The API will throw errors sometimes like for cases when the subscriber to be added already exists.

This is how it will be used for adding a subscriber:

// Say these are class level variables
private const string dataCenter = "us1"; // Use your data center here
private const string apiKey = "234723094230958346793259945-us1"; // Your API key here
private const string listId = "2875023586"; // Your list_id here

// Utility method to add a subscriber
public static void AddSubscriber(string name, string email) {
    // I don't know how else to make this pretty. This is just harcoded JSON.
    string requestJson = "{\"email_address\": \"" + email + "\", \"status\": \"subscribed\", \"merge_fields\": {\"FNAME\": \"" + name + "\"}}";

    // This will add the subscriber to Mailchimp
    CallMailchimpApi(dataCenter, $"lists/{listId}/members", requestJson, apiKey);
}

In an actual game, imagine you have a button with a label “Join the Family!” in the title screen. By clicking this button, it opens a modal panel that has input fields for email and first name. It also has a button labeled “Join”. The method that gets called when Join button is clicked could then be implemented like this:

// Inside a MonoBehaviour code
[SerializedField]
private Text nameField;

[SerializedField]
private Text emailField;

...

// When Join button is clicked
public void Join() {
    AddSubscriber(this.nameField.text, this.emailField.text);

    // Or you can use a static class if you place it in one
    Mailchimp.AddSubscriber(this.nameField.text, this.emailField.text);
}

I hope you grow your mailing list by doing this. And speaking of which, please subscribe to mine if you enjoy my posts. 🙂

5 thoughts on “How to add subscribers to Mailchimp within your Unity game

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s