Quick Start

Last Updated on : 2024-06-26 07:26:50download

This topic describes how to quickly build a SaaS application on the Tuya Developer Platform, and further customize microapp development tailored to your specific SaaS features.

Preparation

  1. Register with the Tuya Developer Platform.

  2. Install the microapp development tool Node.js v14 or later.

    In the terminal, run the node -v command to check if you have the correct version installed.

    ~$ node -v
    v16.16.0
    
  3. Install the Docker environment. If in Step 1, you assemble Tuya’s existing microapps and create a SaaS application tailored to your business scenarios, you do not need to develop a custom microapp. In this case, Docker is not required. The Docker environment is used for local deployment of your custom microapps. For more information about Docker installation, see the Docker website.

    In the terminal, run the docker -v command to check if you have installed Docker.

    ~$ docker -v
    Docker version 20.10.17, build 100c70
    

Overview

The following sections take an example to describe how to create a SaaS application on the Tuya Developer Platform. You can learn how to combine and configure basic microapps provided by Tuya, and develop custom microapps specific to your business scenarios to enrich your SaaS applications.

In actual use, if the SaaS application that you have created by assembling the microapps provided by Tuya already meets your business requirements, you can skip microapp development and integration steps.

The overall procedure of this sample scenario is as follows:

3. Integrate with MicroApp
Run SaaS
Application Locally  
Launch MicroApp
Subscribe to MicroApp 
2. Develop MicroApp
Integrate with Cloud-to-Cloud  
Integration Capability
Develop MicroApp Page
Develop MicroApp API 
1. Build SaaS  
Create Admin
Create SaaS  
Assemble MicroApps
  • Step 1: Build a SaaS application on the Tuya Developer Platform.
  • Step 2: Develop a microapp locally and launch it to the Tuya Developer Platform.
  • Step 3: Integrate your microapp into the SaaS application.

To sum up, by going through the above procedure, you can completely build a SaaS application system.

Quick Start

Step 1: Build a SaaS application

You can create a SaaS application, assemble Tuya’s existing basic microapps to adapt to your business scenarios, and manage permissions for the SaaS application.

1. Create a SaaS application

  1. Log in to the Tuya Developer Platform.

  2. In the left-side navigation pane, choose Cloud > SaaS Development > SaaS Management.

  3. Click Create SaaS in the top right corner of the page, select Create Manually, enter a custom SaaS name that matches your business scenario, keep the default values for other fields, and then click OK.

    Quick creation and manual creation differ as follows. Take manual creation as an example.

    • Quick creation: Quickly create a SaaS application on top of popular solutions. Quick creation is recommended when your business scenario closely matches the existing solution.

    • Manual creation: Manually set up SaaS configurations, and add microapps as needed to create your SaaS application. Manual creation is recommended when your business scenario does not match popular solutions.

      Quick StartQuick Start

  4. After the SaaS application is created, go back to the SaaS Management page and click Configure SaaS on the right of the SaaS application.

    1. In the left-side navigation pane, choose Basic Information > OEM Information and set up the SaaS style to be displayed on the terminals.
      Quick Start
    2. In the left-side navigation pane, choose Integration & Deployment > SaaS Deployment and set up the domain name to access the SaaS application.
      Quick Start

2. Assemble the microapp

  1. In the left-side navigation pane, choose Features > MicroApps.

  2. Click Select MicroApp in the top right corner of the page. On the Select MicroApp page that appears, select the desired microapps and click OK.

    Quick Start

3. Create an administrator and access the SaaS application

  1. In the left-side navigation pane, choose Basic Information > Administrator.

  2. Click Add Administrator in the top right corner of the page, add an administrator account, and then get an initial password.

  3. Click Go to SaaS in the top right corner and enter the username and password to log in to the SaaS application.

    The initial password appears only once. Please copy and save it properly. You can also reset your password if you forgot it.

    Quick Start Quick Start

Now, you have built a SaaS application hosted on the Tuya Developer Platform.

  • If this SaaS application already meets the requirements of your business scenario, you can skip the following microapp development and integration steps.
  • Otherwise, you can go through the following steps to customize the desired SaaS features.

Step 2: Develop a microapp

This section describes how to develop your own microapp, integrate it into a SaaS application, and run it in local mode.

1. Create a frontend project

  1. Open the Terminal.

  2. Go to the target directory where the project is to be created.

  3. Run the following commands to quickly initialize the microapp project.

    npx @tuya-sat/create-micro-app@latest demo -t react-ts
    

    In case initialization fails, run npm uninstall @tuya-sat/create-micro-app to uninstall the earlier version and try again. Available templates: react, react-ts, vue, and vue-ts.

  4. After the initialization is completed, a demo project is generated in the directory.

    Quick Start

2. Configure and start the project

  1. Open the demo project.

  2. Find the micro.config.js file in the project root directory.

  3. Configure the newly built SaaS domain name, administrator username, and password to the debuggerConfig item, and save it.

    debuggerConfig: {
        target: 'https://<my-first-saas-host>', // SaaS domain name
        username: 'my-first-saas-username', // SaaS administrator username
        password: 'my-first-saas-password', // SaaS administrator password
        logSign: true, // Print the request header
        mockPermissions: ['REGISTER', 'EDIT', 'DELETE'],
        customApiUrl:'' // Backend service URL for local development and joint debugging
    }
    
  4. Run the following command in the terminal to start the project. If the startup is successful, the local microapp page is opened automatically with a browser.

    npm run start
    

    Quick StartQuick Start

3. Implement custom development

  1. Modify the frontend page.

    You can customize the frontend pages. Here is an example of customizing pages to add, delete, query, and modify an asset.

    1. Find the src/pages/index.tsx file under the project, modify the Page component,

    2. and create an asset list page by introducing the <TableList /> component. Add, delete, query, and modify operations on assets are included in the <TableList /> component.

      After the file src/pages/index.tsx is modified, the code block looks like this:

      import TableList from '../components/Table';
      import { microProps } from '../index';
      import styled from './index.module.less';
      const Page = () => {
      const { dynamicProps } = microProps;
      dynamicProps.setBreadcrumb([{ type: 'auto' }]);
      return (
          <div className={styled['layout']}>
          <TableList />
          </div>
      );
      };
      export default Page;
      

    The APIs for customizing the microapp page start with /custom-api. In the sample code, the asset query API /custom-api/assets in the <TableList /> component will be routed to the /assets API of your own backend service when you initiate a request.

      function getList() {
        api.get('/custom-api/assets')
          .then(res => {
            setDataSouce({
              data: res.result.list.map(item => {
                return { ...item, asset_name: decodeURI(item.asset_name) };
              }),
              totalRecord: res.result.list.length,
            });
          })
          .catch(e => console.log(e));
      }
    
  2. Implement backend services.

    All page requests of your custom microapps require corresponding backend services. Take a simple Node.js backend service as an example. The external service is provided on port 8080 and APIs are available for you to add, query, modify, and delete assets. The server code is as follows:

    const http = require('http');
    const { TuyaContext } = require('@tuya/tuya-connector-nodejs');
    
    const hostname = '0.0.0.0';
    const port = 8080;
    const ClientID = '***'; // project Client ID
    const ClientSecret = '***'; // project Client Secret
    
    const tuya = new TuyaContext({
      baseUrl: 'https://openapi.tuyacn.com',
      accessKey: ClientID,
      secretKey: ClientSecret
    });
    
    async function assetsList() {
      return await tuya.assets.childAssets({asset_id: -1});
    }
    
    async function addAsset(params) {
      return await tuya.assets.add(params);
    }
    
    async function delAsset(params) {
      return await tuya.assets.delete(params);
    }
    
    async function update(params) {
      return await tuya.assets.update(params);
    }
    
    const server = http.createServer(async (req, res) => {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'application/json');
      res.setHeader('Access-Control-Allow-Origin', '*');
      let result = {};
      if (req.url.startsWith('/assets')) {
        result = await assetsList();
      } else if (req.url.startsWith('/add')) {
        const paths = req.url.split('/');
        const assetName = paths[paths.length - 1];
        result = await addAsset({ name: assetName });
      } else if (req.url.startsWith('/del')) {
        const paths = req.url.split('/');
        const assetId = paths[paths.length - 1];
        result = await delAsset({ asset_id: assetId });
      } else if (req.url.startsWith('/update')) {
        const paths = req.url.split('/');
        const assetName = paths[paths.length - 1];
        const assetId = paths[paths.length - 2];
        result = await update({ asset_id: assetId, name: assetName });
      }
      res.end(JSON.stringify(result));
    });
    
    server.listen(port, hostname, () => {
      console.log(`Server running at http://${hostname}:${port}`);
    });
    

    You can copy and save this code snippet to the server.js file in the specified directory, and then set the constants ClientID and ClientSecret in the code snippet to the Client ID and Client Secret of the cloud project corresponding to your SaaS respectively. You can find the corresponding cloud project in the SaaS list.


    Quick StartQuick Start

  3. After you configure the key of the cloud project, run the following command in the current directory to start the service:

    ~ % npm i @tuya/tuya-connector-nodejs
    
    ~ % node server.js
    
    # Server running at http://127.0.0.1:8080
    
  4. Meanwhile, modify the micro.config.js file in the root directory of the frontend project, configure the customApiUrl option, and set the page request to be forwarded to the local service.

    debuggerConfig: {
        target: 'https://<my-first-saas-host>', // SaaS domain name
        username: 'my-first-saas-username', // SaaS administrator username
        password: 'my-first-saas-password', // SaaS administrator password
        logSign: true, // Print the request header
        mockPermissions: ['REGISTER', 'EDIT', 'DELETE'],
        customApiUrl:'http://localhost:8080' // Backend service URL for local development and joint debugging
    }
    
  5. Open your custom page on the browser to verify the custom development feature. You can see the developed asset management feature:

    Quick Start

Now, you have completed the entire frontend and backend development process of a microapp.

The requests for your microapp page are sent to your own backend services. The backend services work across programming languages and development frameworks. You can choose the preferred technology stack. Through cloud-to-cloud integration, your backend services can also access Tuya’s open APIs and subscribe to messages. For more information, see Cloud Development.

Step 3: Integrate with the microapp

You can try out your custom microapps and integrate them into SaaS applications. For this purpose, you need to push and activate the microapp on the Tuya Developer Platform first.

1. Publish the microapp

  1. Install the command line interface (CLI).

    sudo npm i -g @tuya-sat/sdf-cli
    
  2. Run the cli command to configure the keys.

    # Enter developer App Key and Secret Key in sequence.
    sdf config
    
    ? appKey: YTw ******** h2kn
    ? secretKey: pfo ***************************** 9kD
    ? endpoint: default
    ✔ config success
    

    Go to SaaS Development > MicroApp Dev and click View Development Credentials to get the App Key and Secret Key.

    Quick Start
  3. Publish the microapp.

    npm run build
    
  4. After the build is successful, run the following command:

    sdf publish
    
    ✔ manifest validate success 🔍
    ⠋ packing tgzextractLang
    path en.ts
    path index.ts
    path zh.ts
    ✔ pack success 📦
    ✔ push success 🚀
    ✔ publish success 🎉
    

2. Select the microapp

The backend services corresponding to your custom microapps are deployed on your server. Therefore, you need to change the SaaS deployment mode to hybrid deployment mode and install the runtime environment.

  1. Change the SaaS deployment mode.

    1. On the page of SaaS Management, click Configure SaaS.

    2. In the left-side navigation pane, choose Integration & Deployment > SaaS Deployment.

    3. Click Edit, change the deployment mode to Hybrid Deployment, and then enter the custom domain name.

      Quick Start
  2. Select the microapp.

    1. For a newly published microapp, you need to set a version label to distinguish between versions, so you can easily select the desired microapp.

      After the microapp is published in local mode, you can go to SaaS Development > MicroApp Dev to see the newly published microapp. Click Manage and go to Labels. Click Add Label, enter the label name, and then bind the label with the target version.

    2. On the SaaS Management page, click Configure SaaS. Choose Features > MicroApps and click Select MicroApp. On the page that appears, click the Private MicroApp tab, select the desired microapps, and then click OK.

      Quick Start

3. Run the SaaS application in local mode

  1. Install the runtime environment.

    1. Go to the target directory in local mode.

    2. Run the download script and unzip the installation package.

      # If you use curl
      curl -Ljo sdf-deploy-rt.zip https://github.com/tuya-sat/sdf-deploy/archive/refs/tags/rt.zip
      
      # If you use wget
      wget https://github.com/tuya-sat/sdf-deploy/archive/refs/tags/rt.zip -O sdf-deploy-rt.zip
      
    3. After download is completed, unzip the installation package.

      unzip sdf-deploy-rt.zip
      

      After the package is unzipped, you can see files with the following directory structure:

      # sdf-deploy-rt directory
      ├── LICENSE
      ├── README.md
      ├── docker-compose
      │   ├── README.md
      │   └── docker-compose.yml
      │   └── redis
      
  2. Configure the developer App Key and Secret Key of the SaaS application.

    1. Go to SaaS Development > MicroApp Dev.

    2. Click View Development Credentials in the top right corner of the microapp list to get the App Key and Secret Key.

    3. Follow the steps below to configure the key and backend service address. Tuya’s backend service is local, and all local service addresses are set to the local IP address.

      The service address cannot be set to 127.0.0.1, because the Docker service cannot access external services through 127.0.0.1.

      cd sdf-deploy-rt/docker-compose/    # Go to the docker-compose directory
      vi .env                          # Edit the .env file.
      
      # developer Configuration information
      APP_KEY=Developer App Key
      SECRET_KEY=Developer Secret Key
      
      # Backend service address
      CUSTOM_API_URL=http://172.16.120.224:8080
      
  3. Run the following command to start the microapp container:

    docker compose up
    # For Docker compose of an early version, run the command docker-compose up
    
    # When mqtt MQTT client status: connect appears, it means the startup is successful
    
    [+] Running 2/0
     ⠿ Container sdf-redis Created    0.0s
     ⠿ Container sdf-fgw    Created    0.0s
    Attaching to sdf-fgw, sdf-redis
    sdf-redis | 1:C 08 Jun 2023 11:54:08.807 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo
    ......
    sdf-fgw | 2023-06-08T11:58:15.500Z INFO microadmin request https://micro-app-admin.tuyacn.com/v1.0/sdf/developer/mqtt/auth
    sdf-fgw | 2023-06-08T11:58:15.518Z INFO mqtt MQTT client status: end
    sdf-fgw | 2023-06-08T11:58:15.627Z INFO mqtt MQTT client config:     {"clientId":"sdf_developer_key_clientid_52 ******** 3","username":"sdf_developer_key_username_523 ******** d","password":"6***5","wsUrl":"wss://mqtt-im.tuyacn.com:443/mqtt"}
    sdf-fgw | 2023-06-08T11:58:15.809Z INFO mqtt MQTT client status: connect
    sdf-fgw | 2023-06-08T11:58:15.909Z INFO mqtt MQTT client status: connect
    ......
    

4. Access the SaaS application

Your runtime environment is built locally, so you need to modify the hosts configuration and map the custom domain name of your SaaS to the local server. Then, verify your access to the SaaS application with the SaaS domain name and the default port 80 for verification.

  1. Modify the hosts configuration:

    sudo vi /etc/hosts
    # 127.0.0.1 demo002.myhost.com
    # After the configuration is modified, you can ping demo002.myhost.com to verify the effect.
    
  2. Through the SaaS domain name and the default port 80, access the SaaS application http://demo002.myhost.com.

    Without a local certificate, you can access the SaaS application over HTTP only, instead of HTTPS.

    Quick Start

Congratulations! You have tried out the complete procedure of SaaS build, microapp development, integration, and deployment.