How to Build a Zapier Integration to Scan Barcodes

Zapier is a workflow automation platform. It has integrated over 6000 applications and we can chain different applications in the same workflow without writing code.

In this article, we are going to build a Zapier app integration to scan barcodes. We can scan barcodes in a web application and the app will trigger workflows. Dynamsoft Barcode Reader is used for barcode scanning.

Scan Barcodes to Trigger Workflows in Zapier

Since an integration cannot work alone, let’s try to implement a whole solution to scan barcodes to trigger workflows in Zapier. Here are the steps:

  1. Build a barcode scanning web app.
  2. Build a Zapier app integration to use the barcode scanning web app.
  3. Build a Zap (workflow) to use the integration.

Build a Web Barcode Scanner

Let’s create a Python backend and a web frontend with vanilla JS.

The frontend generates a UUID as the unique identifier and sends the scanned barcodes to the backend.

The backend has two endpoints to serve as a polling server for a Zapier integration.

  1. /auth for authorization.
  2. /code for adding a barcode and retrieving the scanned barcode of a device (device is differentiated by UUID).

The /code endpoint would return scanned barcodes in an array like the following:

[
    {
        "id": 1710134464039,
        "barcode": "9781477701461"
    },
    {
        "id": 1710134706906,
        "barcode": "9780743258074"
    },
    {
        "id": 1710135037503,
        "barcode": "9780321344755"
    },
    {
        "id": 1710137117234,
        "barcode": "9780062874788"
    }
]

Timestamp is used as the ID so that we can scan multiple barcodes and Zapier’s deduplication mechanism will treat them as different records.

Back-End Implementation

Here we use Flask as the framework to provide two endpoints:

  1. /auth:

    @app.route('/auth', methods=['POST','GET'])
    def auth():
        response = {}
        response["success"] = True
        json_string = json.dumps(response)
        resp = Response(json_string)
        resp.headers['Content-Type'] = 'application/json'
        return resp
    

    Here, it always returns true as we are using UUID as the identifier and no authorization is actually required.

  2. /code:

    data = {}
    @app.route('/code', methods=['POST','GET'])
    def code():
        global data
        new_barcode_items = []
        if request.method == 'POST':
            uuid = request.args.get('uuid')
            barcode = request.args.get('barcode')
            barcodes = [];
            if uuid in data:
                barcodes = data[uuid]
            else:
                data[uuid] = barcodes
            item = {}
            item["id"] = int(time.time()*1000)
            item["barcode"] = barcode
            barcodes.append(item)    
        else:
            uuid = request.args.get('uuid')
            if uuid in data:
                barcodes = data[uuid]
                for item in barcodes:
                    new_barcode_items.append(item)
        json_string = json.dumps(new_barcode_items)
        resp = Response(json_string)
        resp.headers['Content-Type'] = 'application/json'
        return resp
    

    If the method is POST, add a new barcode item in the data dict. If the method is GET, return the scanned barcodes of a UUID in an array.

  3. Serve static files under the root.

    app = Flask(__name__, static_url_path='/', static_folder='./')
    

Front-End Implementation

  1. Create a new scanner.html file with the following template:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Scan Barcode to Zapier</title>
        <style>
        </style>
    </head>
    <body>
        <div id="app"></div>
        <script></script>
    </body>
    </html>
    
  2. Include Dynamsoft Barcode Reader in the page:

    <script src="https://cdn.jsdelivr.net/npm/dynamsoft-barcode-reader@10.0.21/dist/dbr.bundle.js"></script>
    
  3. Initialize the product with a license. You can apply for one here.

    let license = "DLS2eyJoYW5kc2hha2VDb2RlIjoiMjAwMDAxLTE2NDk4Mjk3OTI2MzUiLCJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSIsInNlc3Npb25QYXNzd29yZCI6IndTcGR6Vm05WDJrcEQ5YUoifQ=="; //one-day trial license
    Dynamsoft.License.LicenseManager.initLicense(license);
    
  4. Create an instance of Camera Enhancer to open the camera.

    let view = await Dynamsoft.DCE.CameraView.createInstance();
    let cameraEnhancer = await Dynamsoft.DCE.CameraEnhancer.createInstance(view);
    document.getElementById("cameraViewContainer").append(view.getUIElement());
    await cameraEnhancer.open();
    

    Add the following element as the container for the camera view.

    <style>
    #cameraViewContainer{
        position: fixed;
        width: 100%;
        height: 100%;
        top:0;
        left:0;
    }
    </style>
    <div id="cameraViewContainer"></div>
    
  5. Create an instance of Capture Router to read barcodes from the camera frames.

    let router = await Dynamsoft.CVR.CaptureVisionRouter.createInstance();
    router.setInput(cameraEnhancer);
    await router.startCapturing("ReadSingleBarcode");
    
  6. The barcode reading results can be received in the onDecodedBarcodesReceived callback. Here, we save the result in a text input.

    router.addResultReceiver({ onDecodedBarcodesReceived: (result) => {
        if (result.barcodeResultItems.length > 0) {
            document.getElementById("barcode").value = result.barcodeResultItems[0].text;
            stopScanning();
        }
    }});
    
  7. Generate or load the UUID when the app starts.

    function loadUUID(){
        let uuid = localStorage.getItem("uuid");
        if (!uuid) {
            uuid = generateUUID();
            localStorage.setItem("uuid",uuid);
        }
        document.getElementById("uuid").value = uuid;
    }
    
    function generateUUID() {
        var temp_url = URL.createObjectURL(new Blob());
        var uuid = temp_url.toString(); // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
        URL.revokeObjectURL(temp_url);
        return uuid.substr(uuid.lastIndexOf("/") + 1);
    }
    
  8. Send the barcode to the backend.

    function send(){
        let uuid = document.getElementById("uuid").value;
        let barcode = document.getElementById("barcode").value;
        let xhr = new XMLHttpRequest();
        xhr.open('POST', "/code?uuid="+uuid+"&barcode="+barcode);
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4){
                document.getElementById("barcode").value = "";
                alert("Sent");
            }
        }
        xhr.onerror = function(){
            console.log("error");
            alert("failed");
        }
        xhr.send();
    }
    

The web barcode scanner is implemented. We can deploy it to a platform like Vercel for production usage.

Build a Zapier Integration

Go to developer.zapier.com and let’s build a new integration with Platform UI.

new integration

Authentication

  1. Choose API Key to set up the authentication.

    authentication

  2. Add two authentication fields: UUID and device name.

    authentication fields

  3. Set up the endpoint URL for authentication. Here, we use https://zapier-barcode-reader.vercel.app/auth.

    authentication endpoint

  4. Specify Device Name as the connection label so that users can see the name in a zap’s setup page.

    authentication connection label

Trigger

  1. Create a new trigger named Barcode Scanned.

    new trigger

  2. Configure the API request.

    1. Choose the type as Polling.
    2. Set up the endpoint URL. Here, we use https://zapier-barcode-reader.vercel.app/code.

      trigger's API configuration

    3. Provide a sample data:

      {
        "id": 1710134464039,
        "barcode": "9780321344755"
      }
      

      trigger's sample data

Create a New Zap

Now that the integration is done. Let’s use it in a zap.

Here is the workflow we are going to make.

  1. Trigger the workflow when an ISBN barcode of a book is scanned.
  2. Query the book’s info via Google’s API by running JavaScript.
  3. Create a new Notion record to store the scanned book.

Zap

Here are the detailed steps:

Barcode Reader Trigger

  1. Create a new zap and select Dynamsoft Barcode Reader integration we made as the trigger.

    Select Trigger

  2. Connect to an account by entering the UUID and device name.

    Connection

  3. Scan a barcode in the web barcode scanner and send it to Zapier. Then, we can get the records in the test step.

    Barcode Reader Test Result

Query Book’s Info

Next, create a step to run JavaScript code to get the book’s info like title, author and description.

  1. Select Code by Zapier as the action.

    Select Code Action

  2. Select Run JavaScript.

    Select Code Action's Type

  3. Use Barcode in the previous step as the input data.

    Select Code Action's Input Data

  4. In the code input, enter the following JavaScript code to query the book’s info.

    output = [];
    let response = await fetch("https://www.googleapis.com/books/v1/volumes?q=isbn:"+inputData.barcode);
    let object = await response.json()
    let items = object["items"]
    if (items.length>0) {
      let item = items[0];
      let title = item["volumeInfo"]["title"];
      let desc = item["volumeInfo"]["description"]; 
      let authors = item["volumeInfo"]["authors"].join(" ");
      output = [{"title":title,"desc":desc,"authors":authors}];
    }
    
  5. In the test step, we should be able to get the following results.

    Code Action's Test Result

Create a New Book Record in Notion

  1. In Notion, create a new database with the following fields: ISBN, title, author and description.
  2. Create a new step. Select Notion and select Create Database Item as the action.

    Notion Action

  3. Connect your Notion account via OAuth.
  4. Go to Notion and connect the database to Zapier.

    Notion Connection

  5. In the action part, fill in the info.

    Notion Action Details

  6. Run the test and we can see a new item is inserted into the Notion database.

    Notion Database

All right, we’ve now gone through the steps of scanning barcodes into Zapier.

Source Code

Get the source code of the web barcode scanner to have a try:

https://github.com/tony-xlh/Zapier-Barcode-Reader