The content of this page has been automatically translated by AI. If you encounter any problems while reading, you can view the corresponding content in Chinese.

Development Guide

Last updated: 2025-04-28 15:03:02

This article introduces how developers build Chinese domestic brand mini programs based on IoT Explorer Mini Program SDK (hereinafter referred to as SDK), and use the capabilities provided by the platform obtain via SDK.

Prerequisites

1. Using SDK requires that your runtime environment include Node.js and npm.
2. Log in to the IoT Explorer console to create a project and products. For specific operations, see Product Definition.
3. Log in to the IoT Explorer Console to obtain the AppKey and AppSecret. For specific operations, see Obtain the Application AppKey and AppSecret.

Integrating the SDK

Installing the SDK

1. Under the WeChat mini program directory, install the SDK via npm .
npm install qcloud-iotexplorer-appdev-sdk
2. In the project interface of WeChat Developer Tools, click Details in the upper right corner of the interface, select Local Setting, and check "Use npm Module".


3. In the project interface of WeChat Developer Tools, select Tools > Build npm from the menu bar. After the build succeeds, the interface will display a message indicating that the build is completed.
Build npm



Configure the Domain Name of the Mini Program Server

The Mini Program SDK connects to IoT Explorer via the following domain names.
request domain name: https://iot.cloud.tencent.com
socket domain name: wss://iot.cloud.tencent.com
When integrating the Mini Program SDK, you need to add the above domain names to the server domain name list of the mini program. The steps are as follows.
1. Log in to the mini program backend.
2. Select Development Management > Development Setting.


3. On the "Server Domain Name" page, click Start Configuration (if configured before, click Modify), and complete identity confirmation according to the page guide.


4. Fill in server information.


request valid domain name: https://iot.cloud.tencent.com
valid socket domain name: wss://iot.cloud.tencent.com
5. Click Save and Submit.

Integrate WeChat Login

Use the WeChat ID registration and login API of the application side of IoT Explorer. It allows mini program users to register and log in to IoT Explorer via WeChat. For security reasons, it is not recommended to directly call the WeChat ID registration and login API on the mini program side. Please call the API in your self-built backend service to avoid key leakage.
The integration of WeChat login in a mini program requires implementing the following process:
1. The mini program invokes wx.login to obtain a temporary login credential code.
2. The mini program passes the temporary login credential code to the self-built backend service.
3. The backend service invokes the WeChat server API auth.code2Session to obtain the mini program user's OpenID through the temporary login credential code.
4. The backend service calls the IoT Explorer application endpoint API WeChat ID registration and login to obtain an AccessToken through the mini program user's OpenID.
5. The backend service returns the AccessToken to the mini program.
6. The mini program inputs the AccessToken into the Mini Program SDK to complete the initialization of the Mini Program SDK.

Sample Code

Follow the following steps and refer to the sample code to integrate WeChat login:
1. In the construct function parameter of AppDevSdk, change the value of appKey to the AppKey you actually obtain.
2. Supplement the implementation of the getAccessToken function. In the getAccessToken function, you need to call the login API of your self-built backend service, input the information required for login, and put the obtained AccessToken into the return value of the getAccessToken function.
// app.js
const { AppDevSdk } = require('qcloud-iotexplorer-appdev-sdk');

App({
onLaunch() {
this.sdk = new AppDevSdk({
appKey: 'fill in your AppKey here',
getAccessToken: () => this.getAccessToken()
});

sdk.init().then(() => {
// SDK initialization complete
});
},

async getAccessToken() {
// Obtain the mini program login credential code
const code = await new Promise((resolve, reject) => {
wx.login({
success: (res) => resolve(res.code),
fail: reject
});
});

// Call the developer's self-built backend service, input the code, and obtain the AccessToken of IoT Explorer.
// Adjust the implementation according to the actual situation.
const resp = await new Promise((resolve, reject) => {
wx.request({
url: 'URL of the developer's self-built backend service'
method: 'POST',
data: {
code: code,
nickName: default nickName of new user
avatarUrl: 'Default avatar URL for new users'
},
header: {
'content-type': 'application/json'
},
success(res) {
resolve(res.data);
},
fail(err) {
reject(err);
}
});
});

return {
Token: resp.Token,
ExpireAt: resp.ExpireAt,
};
}
})

Using SDK

Calling Application API

The application-side API is a cloud service provided by IoT Explorer to meet the needs of smart home scenarios. It is designed for users to develop their own brand's mini programs or apps. Users do not need to implement basic capabilities such as user management, equipment management, device scheduling, and family management. They can quickly complete the development of the mobile application side by calling the application-side API. For more information about the application-side API, please refer to Introduction to Application API.
SDK encapsulates the calling process of the application API. When sending a request, it will automatically carry the common parameters AccessToken and RequestId.
The following example code takes calling the application API get user bound device list as an example.
sdk.requestApi(
'AppGetFamilyDeviceList' // Action name for requesting the application API
{ FamilyId: 'default' } // Data of the request to the application side API
)
.then(data => {
// Request succeeded
console.log(data);
})
.catch(err => {
//Request failed
console.error(err);
});


Device Network Configuration

The SDK currently supports softAP, SmartConfig, simpleConfig and AirKiss methods for device network configuration.

SoftAP Network Configuration

For the process of device network configuration via softAP, for details, see softAP Distribution Network Development. For detailed parameter description and process description, please refer to the Device Network Configuration section in the Mini Program SDK chapter.
const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;

const {
// Incorrect Chinese description
WifiConfErrorMsg,
// Step code
WifiConfStepCode,
// Description of step code in Chinese
WifiConfStepDesp
} = WifiConfConstants;

/**
* softap configuration
*/
function SoftApConfigure({
token,
wifiInfo = {
SSID: '';
password: '';
BSSID: '';
},
familyId = 'default',
roomId,
reporter,
onStepChange,
onStatusChange,
}) {
const onProgress = (data) => {
reporter.info(data.code, data.detail);

switch (data.code) {
case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
onStepChange(1);
break;

case WifiConfStepCode.PROTOCOL_SUCCESS:
onStepChange(2);
break;
case WifiConfStepCode.SOFTAP_GET_DEVICE_SIGNATURE_SUCCESS:
case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
onStepChange(3);
break;
case WifiConfStepCode.WIFI_CONF_SUCCESS:
onStepChange(4);
break;
}
};

const onComplete = ({ productId, deviceName }) => {
onStatusChange({
status: 'success',
productId,
deviceName,
});
};

const onError = async ({ code, detail }) => {
reporter.error(code, detail);

onStatusChange({ status: 'error' });
};

sdk.plugins['wifiConfSoftAp'].start({
wifiConfToken: token,
targetWifiInfo: wifiInfo,
autoRetry: true, // Automatic handling of failure process
familyId,
roomId,
onProgress,
onComplete,
onError
});
}

module.exports = SoftApConfigure;

SmartConfig Configuration

For the process of device network configuration via SmartConfig, for details, see SmartConfig Distribution Network Development. For detailed parameter description and process description, please refer to the Device Network Configuration section in the Mini Program SDK chapter.
const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;

const {
// Incorrect Chinese description
WifiConfErrorMsg,
// Step code
WifiConfStepCode,
// Description of step code in Chinese
WifiConfStepDesp
} = WifiConfConstants;

/**
* smartconfig one-click configuration
*/
function SmartConfigConfigure({
token,
wifiInfo = {
SSID: '';
password: '';
BSSID: '';
},
familyId = 'default',
roomId,
reporter,
onStepChange,
onStatusChange,
}) {
const onProgress = (data) => {
reporter.info(data.code, data.detail);

switch (data.code) {
case WifiConfStepCode.PROTOCOL_SUCCESS:
onStepChange(1);
break;
case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
onStepChange(2);
break;
case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
onStepChange(3);
break;
case WifiConfStepCode.WIFI_CONF_SUCCESS:
onStepChange(4);
break;
}
};

const onComplete = ({ productId, deviceName }) => {
onStatusChange({
status: 'success',
productId,
deviceName,
});
};

const onError = async ({ code, detail }) => {
reporter.error(code, detail);

onStatusChange({ status: 'error' });
};

sdk.plugins['wifiConfSmartConfig'].start({
wifiConfToken: token,
targetWifiInfo: wifiInfo,
autoRetry: true, // Automatic handling of failure process
familyId,
roomId,
onProgress,
onComplete,
onError
});
}

module.exports = SmartConfigConfigure;

SimpleConfig Configuration

For the process of device network configuration via simpleConfig, for details, see simpleConfig Distribution Network Development. For detailed parameter description and process description, please refer to the Device Network Configuration section in the Mini Program SDK chapter.
const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;

const {
// Incorrect Chinese description
WifiConfErrorMsg,
// Step code
WifiConfStepCode,
// Description of step code in Chinese
WifiConfStepDesp
} = WifiConfConstants;

/**
* SimpleConfig one-click network configuration
*/
function SimpleConfigConfigure({
token,
wifiInfo = {
SSID: '';
password: '';
},
familyId = 'default',
roomId,
reporter,
onStepChange,
onStatusChange,
}) {
const onProgress = (data) => {
reporter.info(data.code, data.detail);

switch (data.code) {
case WifiConfStepCode.PROTOCOL_SUCCESS:
onStepChange(1);
break;
case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
onStepChange(2);
break;
case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
onStepChange(3);
break;
case WifiConfStepCode.WIFI_CONF_SUCCESS:
onStepChange(4);
break;
}
};

const onComplete = ({ productId, deviceName }) => {
onStatusChange({
status: 'success',
productId,
deviceName,
});
};

const onError = async ({ code, detail }) => {
reporter.error(code, detail);

onStatusChange({ status: 'error' });
};

sdk.plugins['wifiConfSimpleConfig'].start({
wifiConfToken: token,
targetWifiInfo: wifiInfo,
autoRetry: true, // Automatic handling of failure process
familyId,
roomId,
onProgress,
onComplete,
onError
});
}

module.exports = SimpleConfigConfigure;

AirKiss Network Configuration

For the process of device network configuration via AirKiss, for details, see AirKiss Network Configuration Development. For detailed parameter description and process description, please refer to the Device Network Configuration section in the Mini Program SDK chapter.
const WifiConfConstants = require('qcloud-iotexplorer-appdev-plugin-wificonf-core').constants;

const {
// Incorrect Chinese description
WifiConfErrorMsg,
// Step code
WifiConfStepCode,
// Description of step code in Chinese
WifiConfStepDesp
} = WifiConfConstants;

/**
* AirKiss one-click network configuration
*/
function AirKissConfigure({
token,
wifiInfo = {
SSID: '';
password: '';
},
familyId = 'default',
roomId,
reporter,
onStepChange,
onStatusChange,
}) {
const onProgress = (data) => {
reporter.info(data.code, data.detail);

switch (data.code) {
case WifiConfStepCode.PROTOCOL_SUCCESS:
onStepChange(1);
break;
case WifiConfStepCode.CREATE_UDP_CONNECTION_SUCCESS:
onStepChange(2);
break;
case WifiConfStepCode.BUSINESS_QUERY_TOKEN_STATE_SUCCESS:
onStepChange(3);
break;
case WifiConfStepCode.WIFI_CONF_SUCCESS:
onStepChange(4);
break;
}
};

const onComplete = ({ productId, deviceName }) => {
onStatusChange({
status: 'success',
productId,
deviceName,
});
};

const onError = async ({ code, detail }) => {
reporter.error(code, detail);

onStatusChange({ status: 'error' });
};

sdk.plugins['wifiConfAirKiss'].start({
wifiConfToken: token,
targetWifiInfo: wifiInfo,
autoRetry: true, // Automatic handling of failure process
familyId,
roomId,
onProgress,
onComplete,
onError
});
}

module.exports = AirKissConfigure;

Control Device

By calling the application-side API of User Control Device, control operations can be initiated on the devices bound to users.
// Attribute data of the device to be controlled
const deviceData = {
light_switch: 0,
};

sdk.requestApi('AppControlDeviceData', {
ProductId: 'Product ID of the device to be controlled'
DeviceName: 'Device name of the device to be controlled'
Data: JSON.stringify(deviceData) // Control message JSON
})
.then(data => {
// Request succeeded
console.log(data);
})
.catch(err => {
//Request failed
console.error(err);
});

Long Connection Communication Capacity

The SDK supports reporting data and status information of the bound device to users via WebSocket. The SDK automatically connects to the WebSocket server by default during initialization.

Subscribe by Device ID List

sdk.subscribeDevices([
'Product1/Device1',
'Product1/Device2',
'Product2/Device3'
]);

Subscribe by Device List

subscribeDevices function supports importing a device list (such as the device list returned by the application side API of Obtaining the User Bound Device List) to subscribe to equipment information. The equipment information in the parameter array is required to contain the DeviceId field.
sdk.requestApi('AppGetFamilyDeviceList', { FamilyId: 'default' })
.then(data => {
sdk.subscribeDevices(data.DeviceList);
})
.catch(err => {
//Request failed
console.error(err);
});

Listen to Device-Reported Data and Status Information

Call the Event Listener API of the SDK to monitor device-reported data and status information subscribed by WebSocket. Please refer to the following example code.
const { EventTypes } = require('qcloud-iotexplorer-appdev-sdk').AppDevSdk.constants;

// Listen to device-reported data push
sdk.on(EventTypes.WsReport, ({ deviceId, deviceData }) => {
console.log('websocket device report', deviceId, deviceData);
});

// Listen to device online status change push
sdk.on(EventTypes.WsStatusChange, ({ deviceId, deviceStatus }) => {
console.log('websocket device status change', deviceId, deviceStatus);
});

// Listen to device control push
sdk.on(EventTypes.WsControl, ({ deviceId, deviceData }) => {
console.log('websocket device control', deviceId, deviceData);
});

Get User Basic Information

By reading the attributes on the SDK object, you can obtain the user's basic information. Please refer to the following example code.
// sdk.isLogin: boolean; Whether the user is logged in
console.log(sdk.isLogin);

// sdk.userId: string; user ID
console.log(sdk.userId);

// sdk.nickName: string; user nickname
console.log(sdk.nickName);

// sdk.userInfo: UserInfo; user details
console.log(sdk.userInfo);
console.log(sdk.userInfo.Avatar);

// sdk.getDefaultFamilyId: () => Promise<string>; obtain user's default Family ID
sdk.getDefaultFamilyId().then(familyId => console.log(familyId));

UserInfo Data Structure Description

Attribute Name
Attribute Description
Type
Avatar
Avatar.
string
CountryCode
Country code.
string
Email
Mailbox.
string
NickName
Nickname.
string
PhoneNumber
Phone number.
string
UserID
User ID.
string

SDK Demo

Demo usage guide: see quick start.