How To Send a WhatsApp Message in 30 Seconds with Golang

July 29, 2021
Written by
Reviewed by
Matt Makai
Twilion

How To Send a WhatsApp Message in 30 Seconds with Golang

Twilio is all about powering communication conveniently and quickly in any programming language.  

In this tutorial you’ll learn how to deliver a message or notification via WhatsApp with a few lines of Go that can be added to any application with the new Twilio Go Helper Library. Ready? Let's get started!

Tutorial requirements

The Twilio WhatsApp sandbox

Twilio provides a WhatsApp sandbox, where you can easily develop and test your application. Once your application is complete you can request production access for your Twilio phone number, which requires approval by WhatsApp.

In this section you are going to connect your smartphone to the sandbox. From your Twilio Console, select Messaging, then select Try it Out on the sidebar. Open the WhatsApp section in the Twilio Console. The WhatsApp sandbox page will show you the sandbox number assigned to your account, and a join code.

WhatsApp Sandbox configuration

To enable the WhatsApp sandbox for your smartphone send a WhatsApp message with the given code to the number assigned to your account. The code will begin with the word "join", followed by a randomly generated two-word phrase.

Shortly after you send the message you should receive a response from Twilio indicating that your mobile number is connected to the sandbox. Your account can now start sending and receiving messages.

If you intend to test your application with additional smartphones, then you must repeat the sandbox registration process with each of them.

Configure Twilio credentials

To be able to send WhatsApp messages via Twilio, the Go application needs to have access to your Twilio account credentials to properly authenticate. The most convenient and secure way to define these configuration values is to set environment variables for them.

The Twilio credentials that you need are your “Account SID” and your “Auth Token”. You can find both on the dashboard of the Twilio Console:

Twilio account SID and auth token

In your terminal, define the following environment variables:

export TWILIO_ACCOUNT_SID=xxxxxxxxx
export TWILIO_AUTH_TOKEN=xxxxxxxxx

If you are following this tutorial on a Windows computer, use set instead of export to define your environment variables in the command prompt.

If you want to learn more about environment variables, check out our how to set environment variables tutorial.

Send a WhatsApp message with Go

With the two environment variables set as shown in the previous section, you can now write a short Go program to send a WhatsApp message. Open a terminal window, find a suitable location to store your project, and create a new directory where the Go project will live:

mkdir go-whatsapp
cd go-whatsapp

Then create a Go module for your new project:

go mod init example.com/whatsapp

After you execute the above command, a *go.mod* file will be added to your project.

The only dependency that you need for this project is the Twilio Go Helper library. You can install it as follows:

go get github.com/twilio/twilio-go

To write the application, launch your favorite code editor and open a file named *whatsapp.go* inside the project directory you created above. Enter the following code in it:

package main

import twilio "github.com/twilio/twilio-go"
import openapi "github.com/twilio/twilio-go/rest/api/v2010"
import "fmt"

func main() {
    client := twilio.NewRestClient()

    params := &openapi.CreateMessageParams{}
    params.SetTo("whatsapp:<YOUR-PHONE-NUMBER-HERE>")
    params.SetFrom("whatsapp:+14155238886")
    params.SetBody("Hello from Golang!")

    _, err := client.ApiV2010.CreateMessage(params)
    if err != nil {
        fmt.Println(err.Error())
    } else {
        fmt.Println("Message sent successfully!")
    }
}

Make sure you enter the phone number of the recipient of the WhatsApp message in the place indicated. For this number, use the E.164 format, which includes a plus sign prefix and the country code. For example, if you intend to send a WhatsApp message to number 234-567-8900 in the United States, that line should read:

    params.SetTo("whatsapp:+12345678900")

This application begins by creating a Twilio REST client object. This object is automatically initialized with the Account SID and Auth Token environment variables.

Then, it creates a CreateMessageParams structure and initializes it with the “to” and “from” phone numbers. When sending from the WhatsApp sandbox, the “from” number is whatsapp:+14155238886. For a production version of the application you will use the Twilio phone number that was approved for WhatsApp, also prefixed with whatsapp:. The last parameter added to this structure is the actual text message you are about to send.

The Twilio client object is finally used to create a new message resource, initialized with the parameter structure created above. This is all it takes to send a WhatsApp message with Twilio!

The call to CreateMessage() returns a response (which is not used in this short example) and an error object that will give you useful information should the message fail to send.

Save the *whatsapp.go* file and then go back to your terminal to run it as follows:

go run whatsapp.go

In just a moment, you will receive the message on WhatsApp!

Message received on WhatsApp

Note that to protect users against spam, WhatsApp only allows you to send freeform messages to a WhatsApp user for a period of 24 hours after the user explicitly contacted you, or in the case of the sandbox also from the moment the user sent the sandbox join code. Visit the documenationt to learn more about the WhatsApp 24-hour window, and how to work around it with message templates.

Conclusion

I hope this short tutorial gives you ideas to continue working with the Go helper library and WhatsApp. At the time I’m writing this article, this library is still being actively developed, so be sure to check the documentation and source code repository often to learn about new releases.

I can’t wait to see what you build with Twilio and Go!

Miguel Grinberg is a Principal Software Engineer for Technical Content at Twilio. Reach out to him at mgrinberg [at] twilio [dot] com if you have a cool project you’d like to share on this blog!