Generate QR Code programmatically using Azure Functions + Power Apps

Jenzus Hsu
jenzushsu
Published in
13 min readSep 16, 2020

--

QR Code is still commonly used today — this simple approach even lead to a national wide implementation of location check-in using an unique QR code for every location. This article aims to address how you can create your own QR Code programmatically internally without the use of public available options.

Photo by Roman Grachev from unsplash.com

QR Code, in short for Quick Response code, is a code that can be quickly readable (a couple of seconds) by a device with a camera attached. QR Codes are commonly used today across various industries such as logistics, retails, marketing and social media. In recent times, QR code is commonly use as a medium to re-direct users to a landing page to perform location check-in as a form for contact tracing. In Singapore, SafeEntry is the National digital check-in system allows visitors to check in by scanning their official photo ID or scanning a unique QR code at the respective location.

Photo by SafeEntry — Combating Clusters through Check-Ins from Singapore Government Developer Portal

The versality of QR Code is still prevalent and popular — having more capability of transferring information and holding more information both horizontally and vertically.

Free QR Code Generator — To use or not to use?

There are many free QR Code generators available on the public internet. It is very convenient to source and quickly generate QR Codes but there are areas of risks and concerns for organization to consider. As a high level overview, this article perfectly summarized the potential security risks such as phishing, malware, malicious website and data tracking.

Hence, some organizations prefer to find an enterprise paid service or to create their own — similar of creating a customized URL shortening service instead of using bit.ly.

If an organization chooses to build their own QR Code generator, there are open-source QR Code libraries where they can tap on.

The question now is — to build a full fledged application where they need to take care of all the typical application infrastructure considerations such as networking, security, monitoring, patching and the list go on and on.

There are so many considerations just to provide a simple service and is it worth it?

Proposed QR Code Generator Service with Azure Functions

Building QR Code Generator service using Azure Functions

Azure Functions is a serverless compute service that enables you to create event-driven actions and triggers without the need to provision or manage your own infrastructure. The best part is you only pay for what you use — pay only when your code runs. You can find the pricing model and some examples in this link.

We will only be focusing on the grey component of the above diagram:

Create an Azure Function in Azure using Visual Studio Code (VSC)

Before you get started, make sure you have the following requirements in place:

Create a local project

Select the Azure icon in the Activity bar. In the Azure: Functions area, select Create new project icon.

Create a new project

Select your desired directory location for the project workspace and choose Select.

Provide the following information at the prompts:

  • Select a language for your function project: Choose JavaScript.
  • Select a template for your project’s first function: Choose HTTP trigger.
  • Provide a function name: Type HttpExample
  • Authorization level: Choose Anonymous, which enables anyone to call your function endpoint. To learn about authorization level, see Authorization keys.
  • Select how you would like to open your project: Choose Add to workspace.

Once completed, VSC generates an Azure Functions project with an HTTP trigger. You should be able to view the local project files in the explorer. Below should be the folder structure.

Project folder structure for Azure Functions project

To learn more about the generated project files, you can refer to this link.

Run the function on localhost

VSC already integrate with Azure Functions Core Tools that allows you to run this project on your local development machine before publishing to Azure.

To call the function, press F5 to start the function app project. The output from the Core Tools will be displayed in the Terminal panel. Once the application is started, the URL endpoint of this HTTP-triggered function will be provided as shown below.

Based on current configuration, you are able to navigate to this URL to execute either GET or POST request. By default, the GET request includes ?name=<input> query string.

http://localhost:7071/api/QRCodeGeneratorTrigger?name=HelloWorld

You can either use your preferred browser or Postman to execute this GET request.

Executing the GET request in Postman

To stop the application, enter Ctrl + C to stop the Core Tools and disconnect the debugger.

Install the required package — node-qrcode

We will be using one of the community libraries — node-qrcode and you need to ensure that all dependences are installed on your Function App.

In the Terminal panel, install the required package using the following command npm install --save qrcodand run. Make sure that you are currently in the function app project root directory.

Installing node-qrcode package in this project

After successfully installing this package, you should check package.josn file, located at the root of your Function App. It should automatically define the dependency in package.json file as npm will download dependencies and devDependencies that are listed in package.json that will meet the semantic version requirements listed for the package.

Dependencies for this Function App project listed in package.json

When deploying function app from source control, any package.json file present in your repo, will trigger an npm install in its folder during deployment.

Add code

In index.js file, insert the following piece of code shown below.

Using the toDataURI API from node-qrcode module, it takes in a query string named test and returns a Data URI containing a representation of the QR Code image.

When the Data URI output is successfully generated, the variable code is returned in the object body. By default, the response’s status is defaults to 200. If the output is not successfully, it will return a message in the body with a status code of 400.

Test, test and test

Run the function on localhost

Press F5 to start the function app project. Once the application is started, the URL endpoint of this HTTP-triggered function will be provided as shown below.

Run the function with the intended query string

Based on the provided URL, you can execute a GET request with ?text=HelloWorld query string and expect a response output of a Data URI string.

http://localhost:7071/api/QRCodeHTTPTrigger?text=helloworld

Executing the GET request in Postman with the required query string

A Data URI is a base64 encoded string that represents a file (i.e., instead of specifying the URL of the file, you can insert the content of the file in a webpage). When a browser encounters a URI, it decodes and constructs the original file.

You can copy and paste the output into a browser and it should decode and construct the QR code as shown below:

QR Code — helloworld

Run the function without the query string

Now, execute the same GET request without the query string. You can uncheck the key-value under Query Params if you are using Postman.

Executing the GET request without the required query string

This will throw a status code of 500 — Internal Server Error. You can refer to the Terminal and show the error message.

Error message for QRCodeHTTPTrigger

Publish the project to Azure

Now, it’s time to deploy the function app and all the related resources in your Azure subscription.

Sign in to Azure

Before publishing, you must sign in to Azure. In the Azure: Functions area, choose Sign in to Azure. If you do not have an Azure account, you can choose + Create a Free Azure Account.

Sign in or create a new Azure account

When prompted in the browser, choose your Azure account and sign in using your Azure account credentials.

Azure Subscriptions displayed in the side bar

After you’ve successfully signed in, you can close the new browser window. The subscriptions that belong to your Azure account are displayed in the Side bar.

Publish the project

Choose the Azure icon in the Activity bar, then in the Azure: Functions area, choose the Deploy to function app button.

Deploy to function app feature in VSC

Provide the following information at the prompts:

  • Select folder: Choose a folder from your workspace or browse to one that contains your function app.
  • Select subscription: Choose the subscription to use (If you have more than 1 subscription).
  • Select Function App in Azure: Choose + Create new Function App. (Don't choose the Advanced option, which isn't covered in this article.)
  • Enter a globally unique name for the function app: Type a name that is valid in a URL path. The name you type is validated to make sure that it’s unique in Azure Functions.
  • Select a runtime: Choose the version of Node.js you’ve been running on locally. You can use the node --version command to check your version.
  • Select a location for new resources: For better performance, choose a region near you.
Notification display on deployment progress

You can also view the deployment out in the Output panel on the deployment results.

Deployment results in the Output panel

From the deployment results, there are a couple of Azure resource created in your subscription using names based on your function app name:

  • A resource group, which is a logical container for related resources.
  • A standard Azure Storage account, which maintains state and other information about your projects.
  • A consumption plan, which defines the underlying host for your serverless function app.
  • A function app, which provides the environment for executing your function code. A function app lets you group functions as a logical unit for easier management, deployment, and sharing of resources within the same hosting plan.
  • An Application Insights instance connected to the function app, which tracks usage of your serverless function.

Run the function in Azure

Once the deployment is completed successfully, head back to Azure: Functions area in the side bar, expand the new function app under your subscription.

Copying Function URL from the deployed function app

Expand Functions, right-click (Windows) or Ctrl + click (macOS) on QRCodeHTTPTrigger, and then choose Copy function URL.

Paste this copied URL to browser or Postman, add the text query string as ?text=helloworld to the end of this URL, and then execute the GET request.

https://<function-app-name>>.azurewebsites.net/api/QRCodeHTTPTrigger?text=helloworld

You should get a similar response in Postman — generated Data URI returned by the function as shown below.

Executing the GET request from the function app on Azure

The next session will be a brief walkthrough on using Power Apps — creating a simple Canvas App with basic input to call this function and return the generated QR Code Data URI.

Proposed QR Code Generator App using Power Apps

In order to demonstrate the use of newly created function app, I will be creating a simple Canvas App with simple input and populate the generated output from the function.

The high level process flow as follows:

  1. User launches the canvas app.
  2. User enters the text and click Generate button. When clicked, it will trigger a Power Automate flow.
  3. Using a HTTP action, the GET request of the function app can be executed and passing the text input from the canvas app as a query string.
  4. The GET request returns the output.
  5. Using flow, set the output as a response to a PowerApp or flow.
  6. Canvas app receive the output from the flow and programmatically set the relevant controls/labels with the output.
  7. User will then see the updated view of the canvas app.

From the above diagram, I will be briefly going through the following components:

Create the QR Code Generator Canvas App

I will assume that you have a basic understanding of creating a Power App. if not, you can refer to my previous article — 8 Days of Power Platform — Day 4 on Basic PowerApps development.

For this QR Code Generator Canvas App, I have created a single screen with the following components — splitting into 2 sections in the screen.

Overview design

Overview design

Input Section

Input Section

Output Section

Output Section

Create the Power Automate Flow

Power Automate Studio

Go to Power Automate Studio, select Create on the left drawer and select Instant flow under Start from blank.

From Build an instant flow dialog, provide the following information and click Create:

  • Flow name: Generate QR Code PowerApps button (Give it a meaningful name)
  • Choose how to trigger this flow: Select PowerApps (Use a button or a link in PowerApps to trigger an action in this flow)
Proposed actions for flow

Once the initial flow project is created, add the following actions and configurations:

HTTP action

  • Method: GET
  • URI: <<function app url>>/api/QRCodeHTTPTrigger
  • Queries (Key-value pair): text (key) and Initializevariable_value (value). Initializevariable_value is a parameter that you can pass from PowerApps to flow. This is inserted using the Dynamic content by selecting Ask in Power Apps.

Respond to a PowerApp or flow action

  • Title: code (can be referenced by variable in the canvas app)
  • Value: Body from the HTTP action

Once completed, save the flow and return to the canvas app.

Associate flow to button

Select the Generate button, click Power Automate in the Action panel and select the flow which you have created.

Under OnSelect property of the button, you should see the following code in the formula bar and add TextInput.Text — passing the text input from the Input section as a parameter.

<<flow name>>.Run(TextInput.Text)

To reference the code value from flow, set a variable QRcode variable and assign to the following components under the Output section:

  • Data URI Label — set QRCode variable in the Text property
  • Image Control — set QRCode variable in the Image property

Append the following code in the OnSelect property of the Generate button

Set(QRCode, <<flow name>>.Run(TextInput.Text).code

Once the flow is triggered, the variable QRCode will be set with the value of the output code from the flow.

Test the Canvas App

Preview the app

You can test the canvas app before publishing by selecting Preview the app or press F5.

Publish the Canvas App

In Power Apps Studio, select Save on the File menu (on the left edge), and then follow either of these steps:

  • If you’ve never saved the app before, selecting Save from the File menu automatically takes you to Save as. Select location as The cloud, provide a name for it, and then select Save.
  • Select Publish
  • In the Publish dialog box, select Publish this version to publish the app to all users with whom the app is shared.

Once published successfully, you can access this canvas app on mobile or browser.

Demo

Below is a demo of using this app on my iPhone. I have entered a couple of text to generate the respective QR Code and reset the app status.

Sample QR Code Generator app using PowerApps using mock.video

Repo

You can refer to the following repo for this sample code and solution package:

Summary

Using Azure Functions and Power Apps, we are able to create a functional application to create QR Code within the organization. Using Function-as-a-Service, you only need to pay the numbers of call of the services without the need to worry about infrastructure. Coupled with Power Apps and Power Automate, you can quickly develop a landing page/application with a workflow.

As always, I enjoyed the process to think through the problem statement and find the most practical approach to meet the requirements.

Now, back to regular work channels.

Happy #powerhacking away, stay safe, mask up and wash your hands regularly 😃

The opinions and views expressed here are those of my own and do not necessarily state or reflect those of Microsoft Singapore or Microsoft Corporation.

--

--

Jenzus Hsu
jenzushsu

Closet geek. Love Baseball. Git + LinkedIn: jenzushsu