Back to News for Developers

Using QR Codes and Short Links in WhatsApp

December 12, 2022ByRashed Talukder

QR codes are an easy way to embed information-dense items into a small image. We frequently see them used for a variety of different purposes, from giving poster-viewers more information to providing diners with the menu at a restaurant.

On a fundamental level, QR codes and short links — a shortened, more readable version of a complex link — are a straightforward, accessible way of connecting with your customer. WhatsApp uses QR codes and short links to help you connect with your customers better. Together these enable your customers to initiate a conversation with you without having to input a phone number or quickly access product information, promotions, and more.

This article will demonstrate how to generate and utilize both QR codes and short links from the WhatsApp Business Platform using the Cloud API, hosted by Meta. We’ll review creating, updating, getting, and deleting a new QR code and short link and show how to send them in a WhatsApp message. You can check out the full code here, at any time.

Prerequisites

To follow this tutorial, you’ll need the following:

  1. A WhatsApp app in your Meta Developer account as per the Getting Started guide and be able to send a test message (webhook setup is not required).

  2. A system user access token with the required permissions (whatsapp_business_management, whatsapp_business_messaging, and business_management)

  3. Basic knowledge of Node.js and Express.js

Additionally, this tutorial will use several Node.js libraries — including dotenv to store the necessary configuration to make HTTP requests with the Cloud API. You’ll also use Postman to test this application’s endpoints. Finally, you’ll need this boilerplate code as the foundation for this article.

Set Up the Environment

Create and open an .env file at the root of the project and fill in all the missing variables with the values from prerequisite steps 1 and 2.

# Your WhatsApp Business app Id
APP_ID=

# Your WhatsApp Business app secret
APP_SECRET=

# Recipient phone number without "+" symbol
RECIPIENT_PHONE_NUMBER=

# Your WhatsApp phone number Id
PHONE_NUMBER_ID=

# Business Account Id
BUSINESS_ACCOUNT_ID=

# System User Access Token. Not temporary access token
ACCESS_TOKEN=

# Cloud API version number
VERSION=v15.0

# Override the default app listener port.
LISTENER_PORT=3000

Now that you’ve added the environment variables, start the application using the shortcut script npm init, which will create a skeleton application.

Creating a New QR Code and Short Link

You’ll begin by creating a new QR code and short link using the Business Management API — part of the WhatsApp Business Platform.

Per the documentation, start by sending a POST request to /{phone-number-ID}/message_qrdls endpoint with three query parameters: prefilled_message, generate_qr_image, and your access_token.

Here, you want the scanned QR code and short link to store to prefilled_message. This will allow a user to send you a pre-written message, which can be useful for customer care, e-commerce, obtaining an opt-in to marketing messages, and more.

Then, generate_qr_image enables you to support two formats for the generated QR code image: .svg or .png. You can select your preferred format using the following method. This example uses .png.

Using the boilerplate, navigate to controllers/qrCode.js and update the createQRCode method with the following code:

const qrdlObject =
  {
    "prefilled_message" : message,
    "generate_qr_image" : type
  }

  const config =
  {
    "method" : "post",
    "url" : `https://graph.facebook.com/${process.env.VERSION}/${process.env.BUSINESS_ACCOUNT_ID}/message_qrdls`,
    "headers" : {
      Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
      'Content-Type': 'application/json'
    },
    "data" : qrdlObject,
  };

  try
  {
    await axios( config );
  }
  catch( error )
  {
    console.log( "")
  }

    },
    function (err, resp, body) {
      if (err) {
        console.log("Error!");
      } else {
        res.json(JSON.parse(body));
      }
    }
  );
};

Then, you need to pass two variables from the request body: a message (which later on will be used as prefilled_message) and your image format. Then, test it using Postman.

Here’s what the request body looks like:

{
    "message":"Creating the example QR Code and Short Link",
    "type":"png"
}

When you hit the Send button in the upper right corner, the API will return the response shown in the screenshot below. The response includes deep_link_url, which acts as a short link, and qr_image_url, which acts as a QR code image. It also contains the id and prefilled_message.

Sending a WhatsApp Message with a QR Code and Short Link

Next, you’ll be able to send your newly generated QR code and short link to a customer. For that, you need to use the Cloud API. You can follow the examples in that documentation as a reference point. With the API, you’ll be able to send a short link as a text message and an image URL as a media message.

Text Messages

curl -X  POST \
 'https://graph.facebook.com/v15.0/BUSINESS_ACCOUNT_ID/messages' \
 -H 'Authorization: Bearer ACCESS_TOKEN' \
 -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "RECIPIENT_PHONE_NUMBER",
  "type": "text",
  "text": { // the text object
    "preview_url": false,
  "body": "MESSAGE_CONTENT"
  }
}'

Media Messages

curl -X  POST \
 'https://graph.facebook.com/v15.0/BUSINESS_ACCOUNT_ID/messages' \
 -H 'Authorization: Bearer ACCESS_TOKEN' \
 -d '{
  "messaging_product": "whatsapp",
  "recipient_type": "individual",
  "to": "RECIPIENT_PHONE_NUMBER",
  "type": "image",
  "image": {
  "id" : "MEDIA_OBJECT_ID"
  }
}'

You’ll create a method that accepts a similar request object and performs the HTTP request, which will call the /phone_number_id/messages endpoint and send a message. In controllers/qrCode.js, create a sendMessage method with the following code. The shell method will already be in the boilerplate.

exports.sendMessage = async (req, res) => {
  const { to, type } = req.body;
  if (!to || !type) {
    return res.status(400).json({
      error: "Required Fields: to and type",
    });
  }
  request.post(
    {
      url: `https://graph.facebook.com/${process.env.VERSION}/${process.env.BUSINESS_ACCOUNT_ID}/messages`,
      headers: {
        Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
        "content-type": "application/json",
      },
      body: JSON.stringify(req.body),
    },
    function (err, resp, body) {
      if (err) {
        console.log("Error!");
      } else {
        res.json(JSON.parse(body));
      }
    }
  );
};

Next, you’ll send a message with the newly generated QR code. Copy the qr_image_url and add it as an image link to the request body.

The following is how the Postman request object looks. Here, PHONE_NUMBER_TO_SEND can be any dialable format.

{
    "messaging_product": "whatsapp",
    "recipient_type": "individual",
    "to": "RECIPIENT_PHONE_NUMBER",
    "type": "image",
    "image": {
        "link": "https://scontent.fybz2-1.fna.fbcdn.net/m1/v/t6/An95lHumHOGcQ_Fl8cDwVrARmc9T9tmtMLyeTOeSFny-OoLLAqSFHEd8gQzAYVsVS6jNm9IBVU27fcb1H05ERwyb5i87Jtp4fjsNppvFnTu26k7ss_dN8S1ZtkSl6XRZtwB68GUabG8?ccb=10-5&oh=00_AT-LCjyu6J8kkeoW1Qj2rxMZikjrHw0fvwA2C6cn9DYkEA&oe=62C8EC07&_nc_sid=f36290"
    }
}

If you get a similar response to the image below, the message is sent successfully.

The image below shows the recipient’s view of the message:

Now, when someone scans this QR code using a smartphone or any other device, it will prefill the message without the user’s input and initiate a new conversation.

Retrieving the List of Existing QR Codes and Short Links

Getting the list of existing QR codes and short links is straightforward, as you only need to make a GET request to the /{phone-number-ID}/message_qrdls endpoint. It returns an array of objects, where individual objects include code(id), prefilled_message, and deep_link_url.

In the controllers/qrCode.js file, update the method with the code below:

exports.fetchQRCodes = async (req, res) => {
  request.get(
    {
      url: `https://graph.facebook.com/${process.env.VERSION}/${process.env.BUSINESS_ACCOUNT_ID}/message_qrdls`,
      headers: {
        Authorization: `Bearer ${process.env.ACCESS_TOKEN}`
      }
    },
    function (err, resp, body) {
      if (err) {
        console.log("Error!");
      } else {
        res.json(JSON.parse(body));
      }
    }
  );
};

After adding the code, test the API with Postman. The below image shows how the request looks in Postman:

The successful response gives an array of QR codes and short links.

Updating QR Code Messages

Updating a QR code is really helpful, as it updates the message without changing the QR code image. So, you don’t need to reprint or reshare new QR codes. This feature is particularly useful when storing information such as contact and promotional details in QR codes.

To update the QR Code message, you need to know the code(id) of the created QR code, which you can pass as a query parameter to the /{BUSINESS_ACCOUNT_ID}/message_qrdls/{qr-code-id} endpoint.

In the controllers/qrCode.js file, update the method updateQRCode with the following code:

exports.updateQRCode = async (req, res) => {
  const { message, qr-code-id } = req.body;
  if (!message || !qr-code-id) {
    return res.status(400).json({
      error: "Required Fields: message and id",
    });
  }
  request.post(
    {
      url: `https://graph.facebook.com/v14.0/${process.env.META_PHONE_ID}/message_qrdls/${qr-code-id}?prefilled_message=${message}`,
      headers: {
        Authorization: `Bearer ${process.env.ACCESS_TOKEN}`,
        "content-type": "application/json",
      }
    },
    function (err, resp, body) {
      if (err) {
        console.log("Error!");
      } else {
        res.json(JSON.parse(body));
      }
    }
  );
};

When you test this in Postman, you’ll see this request object:

{
    "message":"This is my first Updated QR code",
    "id":"4WW67TGNCGPXB1"
}

The successful request sends back the updated code.

Deleting QR Codes

As QR codes don’t expire, you may want to delete it when the information inside that QR code is either outdated or no longer valid.

First, you’ll need to send a DELETE request to the /{BUSINESS_ACCOUNT_ID}/message_qrdls/{qr-code-id} endpoint.

Navigate to controllers/qrCode.js and update deleteQRCode method from the shell method using the following code:

exports.deleteQRCode = async (req, res) => {
  const { qr_code_id } = req.query;
  request.delete(
    {
      url: `https://graph.facebook.com/${process.env.VERSION}/${process.env.BUSINESS_ACCOUNT_ID}/message_qrdls/${qr_code_id}`,
      headers: {
        Authorization: `Bearer ${process.env.ACCESS_TOKEN}`
      }


    },
    function (err, resp, body) {
      if (err) {
        console.log("Error!");
      } else {
        res.json(JSON.parse(body));
      }
    }
  );
};

Here, you’re passing the code id of the QR code you want to retire as query parameters. The successful response outputs a JSON object with success set to true.

It’s worth noting that once the QR code is deleted, you can no longer use that to initiate a conversation and type a message without the user’s input.

Conclusion

In this hands-on tutorial, you learned how to create, update, fetch, and delete QR codes and short links with the WhatsApp Business Platform using the Cloud API, hosted by Meta – along with a brief look at several use cases.

WhatsApp QR codes are easy to manage and can significantly help increase engagement with your customers in a number of meaningful ways. With WhatsApp's QR code and short link capabilities, it's easier than ever before to stay connected with your user base.