Creating Email Verification Application with Tuya API
Tags: javascript, webdev, beginners, tutorial
Published: 2021-12-16 03:12:20


# 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**](https://www.tuya.com/?_source=781e374dc3faa217b38cfdc6341d549a) 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3x7hmejnertpjw0xt09m.png)
 

[Tuya](https://developer.tuya.com/en/iot-core) 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**](https://developer.tuya.com/en/?_source=2993152cf5bd786a7ba5c08ae1a89b26). 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](https://paper-attachments.dropbox.com/s_DA3210F3AFBA18A6963C082C9C4D56D114EEFE0FE4466DE43C962E0A6A34F2B1_1638772007963_Tuya+Registered.png)


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](https://paper-attachments.dropbox.com/s_DA3210F3AFBA18A6963C082C9C4D56D114EEFE0FE4466DE43C962E0A6A34F2B1_1638772137765_API+Tuya.png)


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

![Asset Data Center](https://paper-attachments.dropbox.com/s_DA3210F3AFBA18A6963C082C9C4D56D114EEFE0FE4466DE43C962E0A6A34F2B1_1638772347629_Screenshot+2021-12-06+120205.png)


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

![Project Created](https://paper-attachments.dropbox.com/s_DA3210F3AFBA18A6963C082C9C4D56D114EEFE0FE4466DE43C962E0A6A34F2B1_1638772630496_Screenshot+2021-12-06+120602.png)

# 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:
```bat
    ├── public
        ├──index.html
        ├──script.js
    ├── server.js
    ├── package.json
```

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:
```bat
    npm install express --save
```

- TuyaContext from tuya-connector-nodejs: TuyaContext will handle all the requests to the server
    Command to Install
```bat
    npm install @tuya/tuya-connector-nodejs
```

Our import will look like this

```javascript
    import express from "express";
    import { TuyaContext } from "@tuya/tuya-connector-nodejs";
```

# 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.

```javascript
    app.use(express.static('public'));
    
    app.get('/', function(req, res) {
        res.sendFile(path.join(__dirname, '/index.html'));
    });
```

## Send Email Route

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

```javascript
    const tuya = new TuyaContext({
            baseUrl: 'https://openapi.tuyain.com',
            accessKey: 'XXXXXXXXXXXXXXX',
            secretKey: 'XXXXXXXXXXXXXXX',
          });
```

Choose `baseURL` according to your location.

![Chose Endpoint Location](https://paper-attachments.dropbox.com/s_74B108A034B117585FA67CB9AC8AA22244235BA2B1C94F599522EED319198B90_1638939332188_wkNf_Kk_l.jfif)


### 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.

```javascript
    code = Math.floor(Math.random() * 10000)
    if(code<1000){code=code+1000} 
```

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.

```javascript
    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}\"}`
            },
        })
```

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.

```javascript
    if(req.body.code == code){
            res.send({
                verify:true
            })    
        }
        else{
            res.send({
                verify:false
            })  
        }
```

# 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.

```html
    <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> 
```

# 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.

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

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")`.

```javascript
    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")
            }
        }) 
    }
```

# 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](https://paper-attachments.dropbox.com/s_74B108A034B117585FA67CB9AC8AA22244235BA2B1C94F599522EED319198B90_1638969740460_Screenshot+2021-12-08+185119.png)


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

![Verification Code by Tuya](https://paper-attachments.dropbox.com/s_74B108A034B117585FA67CB9AC8AA22244235BA2B1C94F599522EED319198B90_1638942478205_Screenshot+2021-12-08+111144.png)

# Play with Code

I have created a GitHub repository for this project. You can look into it by visiting [**here**](https://github.com/surajondev/tuya-email-verification). I have also deployed the project on Heroku. Visit [**tuya-email-verification**](https://tuya-email-verification.herokuapp.com/) 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](https://developer.tuya.com/en/iot-core) 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**](https://developer.tuya.com/en/?_source=2993152cf5bd786a7ba5c08ae1a89b26) as it is a great platform for getting useful APIs and programming IoT-based devices.