Send SMS Notifications for Gumroad Orders with Python and Twilio

October 24, 2020
Written by
Dotun Jolaoso
Contributor
Opinions expressed by Twilio contributors are their own

Send SMS Notifications for Gumroad Orders with Python and Twilio

Gumroad is a simple ecommerce tool that allows creators to sell digital products such as films, courses, e-books etc. Gumroad provides Ping, which is an alert in the form of an HTTP POST request that notifies you in real time whenever a product has been purchased.

In this tutorial we’ll build a Flask application that automatically sends you SMS notifications whenever there is a sale of one of your products on Gumroad.

Technical requirements

To follow along, you’ll need the following:

Creating a Python environment

Let’s create a directory where our project will reside. From the terminal, run the following command:

$ mkdir twilio_gumroad

Next, cd into the project directory and run the following command to create a virtual environment.

$ python -m venv venv

To activate the virtual environment, run the following command:

$ source venv/bin/activate

If you are using a Windows computer, then the activation command is different:

$ venv\Scripts\activate

Next, we’ll install all the dependencies our project will be needing:

Run the following command to install all of the dependencies at once:

$ pip install flask twilio python-dotenv gunicorn

To complete the Python set up, run the following command:

$ pip freeze > requirements.txt

This will generate a requirements.txt file for us which contains all our project’s dependencies along with their versions.

Setting up Ngrok

Since we’ll be building and testing our application locally, there is no way for Gumroad’s HTTP Ping request to reach our application. Thankfully, this is where Ngrok comes in handy, allowing us to set up a temporary public URL so that our app is accessible over the web.

Run the following command on your terminal window to start ngrok:

$ ngrok http 5000

In this command, 5000 refers to the port your Flask application will eventually be listening on.

You should now be presented with a screen similar to the one below:

Ngrok-console

Take note of the https:// “Forwarding” URL as we’ll be making use of it shortly.

It’s important to note that when using ngrok for free, the public URLs it creates are only valid for a period of eight hours. We’ll use these URLs only as a development tool. Later on, we’ll cover how to deploy the application we’ll be building to Heroku to come up with a permanent solution.

Configuring Gumroad

Now we need to configure Gumroad to send sales notifications to the ngrok URL. To begin we need to generate a token to include as a query string in the URL. This is so that our Flask application can verify that the sales notification request is legitimate and was sent from Gumroad.

To generate a uuid to use as the token, you can open up another terminal and run the following command:

$ python
>>> import uuid
>>> print(uuid.uuid4())
8c544bc7-b87c-4228-a57b-87f2764307c4

Next, Head over to the Settings page of your Gumroad account. Select the “Advanced” tab and under the “Ping” field, paste the ngrok https:// URL we noted earlier with  /incoming/sales?token=xxxx added at the end. Replace xxxx with the uuid that was generated for you above.

Gumroad settings

Make sure the “Send ‘Purchase’ events for free ($0) sales” option is checked and then click the “Update account details” button towards the end of the page.


At the root of your project’s directory, create a .env file and add the token that was appended to the end of the Ping URL as an environment variable .

GUMROAD_TOKEN=xxxx

Setting up Twilio

Head over to the Twilio Console, and take note of your Account SID and Auth Token. We are going to need these values to authenticate with the Twilio service.

Twilio-console

Add your Twilio credentials, along with the Twilio phone number associated with your account to the .env file we created earlier:

GUMROAD_TOKEN=xxxx
TWILIO_ACCOUNT_SID=xxxx
TWILIO_AUTH_TOKEN=xxxx
TWILIO_NUMBER=xxxx
TO_PHONE_NUMBER=xxxx

The TO_PHONE_NUMBER is the phone number SMS notifications would be sent to. The TWILIO_NUMBER and TO_PHONE_NUMBER need to be given in the canonical E.164 format.

Creating a Webhook Endpoint

Within the twilio_gumroad directory, create a main.py and add the following code to the file:

import os
from flask import Flask, request, Response
from dotenv import load_dotenv
from twilio.rest import Client
load_dotenv()

app = Flask(__name__)
twilio_client = Client()


@app.route('/incoming/sales', methods=['POST'])
def send_sms():
    gumroad_token = request.args.get('token')
    if gumroad_token != os.getenv('GUMROAD_TOKEN'):
        return Response()
    product_name = request.form['product_name']
    message = f"Hello, you just made a Sale! Your product {product_name} was just purchased on Gumroad!"
    twilio_from = os.getenv("TWILIO_NUMBER")
    to_phone_number = os.getenv("TO_PHONE_NUMBER")
    twilio_client.messages.create(body=message, from_=f"{twilio_from}", to=f"{to_phone_number}")
    return Response()


if __name__ == '__main__':
    app.run()

At the top of the file, we’ve imported all the major dependencies our project will be needing:

  • The load_dotenv() function loads our environment variables from the .env file.
  • The twilio_client object will be used for interacting with the Twilio API to send the SMS notification. The TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN environment variables loaded by the load_dotenv() function will be automatically used to authenticate against the Twilio service.

We’ve defined an HTTP POST endpoint at /incoming/sales. This is the endpoint Gumroad will make a HTTP POST request to whenever any of your products has been sold. When a request is received at this endpoint, the token query string along with the name of the product that was sold are obtained using Flask’s request object. The product name comes in the payload of the POST request with a key of product_name. You can check here for additional data contained in the request payload. A check is then carried to ensure the token query string matches the GUMROAD_TOKEN value stored in the environment. Once the check is successful, an SMS notification is sent to the configured phone number using Twilio.

From the terminal, run the following command to start the application

$ python main.py

Testing

There are different ways to go about testing. If you already have a product on Gumroad and have made a few test purchases as the product owner, you can simply go to the Advanced tab on the Settings page, and under the “Ping” field, click “Send test ping to URL”. Gumroad will then make a HTTP POST request to the webhook endpoint we added earlier and you should receive an SMS notification.

If you are new to Gumroad and have yet to add a product, head over to the products page on your Gumroad account. Select the type of product you would like to sell and provide a suitable name and price for your product.

Gumroad new product page

Click the “Next: Customize” button. You’ll be presented with further configuration settings for the product. You can customize the product as needed and once you’re done, Click the “Publish” button at the top of the page. Once the product has been published, you’ll be presented with a screen similar to the one below:

Gumroad share product page

Hover around the product preview section to the right and then click the diagonal arrow that comes up on the section. This will open the product page in a new tab. Select “I want this!”, you’ll be presented with a checkout screen with an already prefilled test card and all you have to do is click “Pay”. Gumroad always allows you to make test purchases of your own product while logged into your account.

Gumroad checkout product page

You should then receive an SMS notification informing you about the sale.

Twilio SMS notification

Deploying to Heroku

In this section, we’ll be covering how we can deploy the application to Heroku, so that it is permanently available without having to run it on your computer. If you don’t have an account on Heroku, you can create one here. You’ll also need to have the Heroku CLI installed locally.

To get started, create a file named Procfile with the following line in it:

web: gunicorn main:app

This tells Heroku how to run our application.

Next we need to commit all our files to source control using git. At the root of your project’s directory, run the following command:

$ git init
$ git add .
$ git commit -m "Initial commit" 

From the terminal, run the following command to login into Heroku:

$ heroku login

This will prompt you to login into Heroku by pressing any key. After you’ve successfully logged in, run the following command to create an app on Heroku:

$ heroku create app-name

Replace app-name with an actual unique name you find suitable for the application. If the name that you pick is taken you will receive an error message. Try different names until you find one that is unique.

Now you can push from your local repository to the Heroku remote by running the following command:

$ git push heroku master

Congrats! Your application has been deployed. However, there’s still one more thing left, we need to set all our environment variables. To do that run the following commands:

$ heroku config:set GUMROAD_TOKEN=xxxx TWILIO_ACCOUNT_SID=xxxx TWILIO_AUTH_TOKEN=xxxx TWILIO_NUMBER=xxxx TO_PHONE_NUMBER=xxxx

Don’t forget to replace xxxx with their actual values, which you can find in your .env file. Your application should now be live at https://app-name.herokuapp.com/. Don’t forget to replace app-name with the actual name of your application.

Now, you can head back to the Settings page of your Gumroad account and update the Ping URL with the Heroku URL. The URL that you enter should be https://app-name.herokuapp.com/incoming/sales?token=xxx, with app-name and xxxx replaced with the correct values for your project.

Conclusion

In this tutorial, we’ve learnt how to send SMS notifications with Twilio whenever a sale is recorded on your Gumroad account. The source code for this tutorial can be found here.

Dotun Jolaoso

Website: https://dotunj.dev/
Github: https://github.com/Dotunj
Twitter: https://twitter.com/Dotunj_