DEV Community

Cover image for Creating Email Verification Application with Tuya API
Suraj Vishwakarma
Suraj Vishwakarma

Posted on • Originally published at surajondev.com

Creating Email Verification Application with Tuya API

Introduction

Today, we are going to build a web application to send verification code to the user. We will use Tuya’s Basic API to send an email. We will to verify the code and notify the user about the verification.

We will use express js as our backend for sending and verifying the code. Frontend with basic HTML, CSS, and JavaScript.

So let's get started.

What is Tuya?

Tuya provides you with APIs and a cloud development environment for managing and programming IoT-based devices. Tuya with their APIs helps you to create an application that will control [IoT devices] with ease.

Tuya

Tuya has many APIs that can be used in sending emails, messages, getting weather, etc. Among them, we are going to use their’s Mail service for sending the code to the user.

Learn more about the Mail Message API provided by Tuya here.

Tuya Setup for API

Create a tuya developers account by visiting here. After login Go to Cloud → Development → Create Cloud Project.
Registered your project by filling in the details. Choose your nearest location for Data Center for the best experience. Click on Create.

Registered your project

On the next window, you will have IoT Core and Authorization by default. Select Email Service Trial Version API from the Select API Services and then click on Authorize.

Select API Services

On the next window, fill the detail for your asset on the choosen Data Center.

Asset Data Center

Now your project is create and you will have your client ID and client secret.

Project Created

Project Structure

We will have both frontend and backend. The frontend will deal with taking emails from the user and making the request to the backend. Backend will handle making request to tuya for sending mail and generating random code. It will verify the code too. We are using the backend to prevent a user from knowing the code that we will generate to send.

File Structure:

    ├── public
        ├──index.html
        ├──script.js
    ├── server.js
    ├── package.json
Enter fullscreen mode Exit fullscreen mode

So let’s start coding by hitting npm init and creating the package.json

server.js

Let’s create our server with express. Our server will handle the following process

  • It will generate a random 4 digit code to send
  • Requests Tuya to Send Email
  • It will verify the verification code Imports

We are going to import the following libraries in the server.js file:

  • express: We are going to use express for handling our backend server. Command to Install:
    npm install express --save
Enter fullscreen mode Exit fullscreen mode
  • TuyaContext from tuya-connector-nodejs: TuyaContext will handle all the requests to the server Command to Install
    npm install @tuya/tuya-connector-nodejs
Enter fullscreen mode Exit fullscreen mode

Our import will look like this

    import express from "express";
    import { TuyaContext } from "@tuya/tuya-connector-nodejs";
Enter fullscreen mode Exit fullscreen mode

Routes

We are going to have to one GET and two POST routes. The default route / will be used for rendering our public folder. Among the POST method, one will get an email from the frontend request, generate random code, and makes a request to tuya for sending mail. Another route gets the code entered by the user and verified with the sent code.

We are using port 8000 for our backend server. That makes the URL for sending mails as
http://localhost:8000/sendcode/ and our verify route http://localhost:8000/verify. The default:8000/ will be served to render our index.html from our public folder.

    app.use(express.static('public'));

    app.get('/', function(req, res) {
        res.sendFile(path.join(__dirname, '/index.html'));
    });
Enter fullscreen mode Exit fullscreen mode

Send Email Route

TuyaContext:

Create a new TuyaContext by entering all the details. Enter accessKek and secretKey of our project.

    const tuya = new TuyaContext({
            baseUrl: 'https://openapi.tuyain.com',
            accessKey: 'XXXXXXXXXXXXXXX',
            secretKey: 'XXXXXXXXXXXXXXX',
          });
Enter fullscreen mode Exit fullscreen mode

Choose baseURL according to your location.

Chose Endpoint Location

Random Code:

Declare a variable outside both routes so that both routes can access the code. Generate a code with Math.floor and Math.random. If the number generated by Math.random is less than 0.1 the code will be 3 digits. If the code generated is 3 digits which is code<1000 add 1000 to make it 4 digits.

    code = Math.floor(Math.random() * 10000)
    if(code<1000){code=code+1000} 
Enter fullscreen mode Exit fullscreen mode

Making request to Tuya:
Make a request to tuya with tuya.request and store the data in the data variable. Request contains method as POST, path is our endpoint to the API which is /v1.0/iot-03/messages/mails/actions/push . The body contains the following 4 parameters:

  • to_address: It is the address to which the mail will be sent. We will get an email from the request that we will send from the frontend to the backend.
  • reply_to_address: An email to which the user can reply.
  • template_id: It is a predefined email template ID by Tuya. MAIL_1624531323 is for verification code.
  • template_patam: It is the parameter for email. {\"code\":\"${code}\"} is the correct parameter and it will contain our generated code.
    const  data  = await tuya.request({
        method: 'POST',
        path: '/v1.0/iot-03/messages/mails/actions/push',
        body: {
            "to_address": req.body.emailaddress,
            "reply_to_address": "test@example.com",
            "template_id": "MAIL_1624531323",
            "template_param": `{\"code\":\"${code}\"}`
            },
        })
Enter fullscreen mode Exit fullscreen mode

And that’s it for the sending mail route.

Code Verification Route

It’s quite a simple route to verify the code entered by the user and the code that we have sent. It is a POST request. Thecode will be passed in the body while making a request to the backend from the frontend. We will send only true if the code is correct and false if the code is incorrect.

    if(req.body.code == code){
            res.send({
                verify:true
            })    
        }
        else{
            res.send({
                verify:false
            })  
        }
Enter fullscreen mode Exit fullscreen mode

index.html

We are going simple and have just two inputs, one for email and the other for code. The two buttons, one for initiating a request to the backend for sending mail and the other for verifying the code.

Add stylesheet according to you.

    <p>Name:</p>
    <input id="email" type="email" placeholder="Enter Email">
    <button onclick=sendCode()>Send Code</button>
    <p>Code:</p>
    <input id="verify" type="number" placeholder="Enter Code">
    <button onclick=verifyCode()>Verify Code</button> 
Enter fullscreen mode Exit fullscreen mode

script.js

We are having two functions. sendCode() will make a request to our server with the body containing the entered email address. It will POST request as it contain body. JSON.Stringify() will convert the body into JSON so that server can read it.

    const sendCode = ()=>{
        const email = document.getElementById("email").value
        fetch("http://localhost:8000/",{
                method:"POST",
                headers:{
                    "Content-Type":"application/json"
                },
                body:JSON.stringify({
                    emailaddress: email
                })
            })
    }
Enter fullscreen mode Exit fullscreen mode

The other function verifyCode will make a POST request to the server for verifying the entered code. This request will send us data regarding verification either verify:true or false. We will alert the user regarding code verification. If the code is correct window.alert("VERIFIED") and if the code is incorrect window.alert("INCORRECT CODE").

    const verifyCode = () =>{
        const enteredCode = document.getElementById("verify").value
        fetch("http://localhost:8000/verify",{
            method:"POST",
            headers:{
                "Content-Type":"application/json"
            },
            body:JSON.stringify({
                code : enteredCode
            })
        })
        .then(function(response){
            return response.json()
        })
        .then(function(data){
            if(data.verify){
                window.alert("VERIFIED")
            }
            else{
                window.alert("INCORRECT CODE")
            }
        }) 
    }
Enter fullscreen mode Exit fullscreen mode

Output

Run the server by running the command node server.js. Enter the email and click on send the email on the http://localhost:800. If everything goes well, you will get the email with a code on your device.

Email Code

If you entered the right code, you will see the alert box with the message VERIFIED.

Verification Code by Tuya

Play with Code

I have created a GitHub repository for this project. You can look into it by visiting here. I have also deployed the project on Heroku. Visit tuya-email-verification to see the working of the project live.

Conclusion

The project is doing its job. The Tuya API is working great and can send an email with generated code to enter email in real-time.

The APIs provided by tuya do a lot of heavy lifting for us. Tuya has many other APIs like Mail Messages. They have Short Messages, Voice messages, Weather, Country codes, IoT-based APIs, and many more.

With their libraries, you can make requests easily with access code and secret code. I recommend you to look into Tuya as it is a great platform for getting useful APIs and programming IoT-based devices.

Top comments (1)

Collapse
 
liviufromendtest profile image
Liviu Lupei

FYI, in case you ever want to test that email flow, you can use the Endtest Mailbox, it's free to use and doesn't require an account.