Last Updated on : 2026-03-03 06:14:11download
Tuya SmartLife App SDK for HarmonyOS supports multiple types of user accounts, such as mobile phone numbers, email addresses, and app UIDs.
Different types of accounts support the following specific capabilities:
In this module, the TSmartUser object is frequently called. This object is a static class that stores all data of the current user, including login and registration methods.
import { TSmartUser } from '@thingsmart/userlib';
SmartLife App SDK supports registration and login with a user’s mobile phone number and password.
To strengthen data security, Tuya has optimized the verification code service and placed limits on accounts. The verification code can only be received by the mobile phone number registered within the covered regions.
To enable verification with mobile phone SMS messages, you must subscribe to and configure the service Verify with Mobile Phone SMS. After this service is enabled, users can register and log in with an app account or reset the password using their mobile phone number. They can also bind their mobile phone number with the app.
API description
static getWhiteListCanSendMobileCode(): Promise<TSmartUserResponse<ITSmartUserRegionWhiteListBean>>
Return values
| Parameter | Description |
|---|---|
| success | Indicates whether the operation is successful. |
| result | The returned result, containing a list of country codes for which verification codes can be sent. |
| errorMsg | The error message. |
| errorCode | The error code. |
ITSmartUserRegionWhiteListBean structure
| Field | Type | Description |
|---|---|---|
| countryCodes | string[] | A list of country codes where SMS verification codes can be sent. |
Sample code
try {
const result = await TSmartUser.getWhiteListCanSendMobileCode();
if (result.success) {
console.log('Country or region for verification code service:', result.result?.countryCodes);
} else {
console.error('Query failed:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during the query:', error);
}
Send verification codes for scenarios such as registration, login, and password reset. This interface supports both mobile phone numbers and email addresses.
To send a verification code using a mobile phone number, you need to call getWhiteListCanSendMobileCode first to check the permissions.
API description
static sendAuthCode(params: ITSmartUserSendAuthCodeParams): Promise<TSmartUserResponse<boolean>>
Parameters
ITSmartUserSendAuthCodeParams structure
| Parameter | Type | Description |
|---|---|---|
| account | string | The mobile phone number or email address. |
| countryCode | string | The country code. Example: 86. |
| codeType | TSmartUserAuthCodeType | The purpose of the verification code. Valid values:
|
| region | string (optional) | The region where the user registered. |
Sample code
Phone number:
try {
const result = await TSmartUser.sendAuthCode({
account: '13800138000',
countryCode: '86',
codeType: TSmartUserAuthCodeType.REGISTER
});
if (result.success) {
console.log('A verification code is sent successfully');
} else {
console.error('Failed to send a verification code:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when sending a verification code:', error);
}
Email address:
try {
const result = await TSmartUser.sendAuthCode({
account: 'user@example.com',
countryCode: '86',
codeType: TSmartUserAuthCodeType.REGISTER
});
if (result.success) {
console.log('A verification code is sent to the email address successfully');
} else {
console.error('Failed to send a verification code to the email address:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when sending a verification code to the email address:', error);
}
API description
Verify the verification codes for scenarios such as registration, login, and password reset. This interface supports both mobile phone numbers and email addresses.
static verifyAuthCode(params: ITSmartUserVerifyAuthCodeParams): Promise<TSmartUserResponse<boolean>>
Parameters
ITSmartUserVerifyAuthCodeParams structure
| Parameter | Type | Description |
|---|---|---|
| account | string | The mobile phone number or email address. |
| countryCode | string | The country code. Example: 86. |
| codeType | TSmartUserAuthCodeType | The purpose of the verification code. Valid values:
|
| authCode | string | The verification code received and entered by the user. |
| region | string (optional) | The region. It is empty by default. |
| sid | string (optional) | The session ID. It is required only in specific scenarios. |
Sample code
Phone number:
try {
const result = await TSmartUser.verifyAuthCode({
account: '13800138000',
region: 'CN',
countryCode: '86',
codeType: TSmartUserAuthCodeType.REGISTER,
authCode: '123456'
});
if (result.success && result.result) {
console.log('The verification code is valid');
} else {
console.log('The verification code is invalid');
}
} catch (error) {
console.error('Failed to verify the verification code:', error);
}
Email address:
try {
const result = await TSmartUser.verifyAuthCode({
account: 'user@example.com',
region: 'CN',
countryCode: '86',
codeType: TSmartUserAuthCodeType.REGISTER,
authCode: '123456'
});
if (result.success && result.result) {
console.log('The verification code is valid');
} else {
console.log('The verification code is invalid');
}
} catch (error) {
console.error('Failed to verify the verification code:', error);
}
Before registering an account, you need to obtain a verification code and verify it. This interface supports both mobile phone numbers and email addresses.
API description
static registerAccount(params: ITSmartUserRegisterParams): Promise<TSmartUserResponse<boolean>>
Parameters
ITSmartUserRegisterParams structure
| Parameter | Type | Description |
|---|---|---|
| account | string | The mobile phone number or email address. |
| countryCode | string | The country code. Example: 86. |
| authCode | string | The verification code received and entered by the user. |
| password | string | The password. |
| accountType | TSmartUserAccountType | The account type. Valid values:
|
| region | string (optional) | The country/region. |
Sample code
Register with a phone number:
try {
const result = await TSmartUser.registerAccount({
account: '13800138000',
region: 'CN',
countryCode: '86',
authCode: '123456',
password: 'your_password',
accountType: TSmartUserAccountType.PHONE
});
if (result.success) {
console.log('Registered successfully');
} else {
console.error('Failed to register:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during registration:', error);
}
Register with an email address:
try {
const result = await TSmartUser.registerAccount({
account: 'user@example.com',
region: 'CN',
countryCode: '86',
authCode: '123456',
password: 'your_password',
accountType: TSmartUserAccountType.EMAIL
});
if (result.success) {
console.log('Registered with the email address successfully');
} else {
console.error('Failed to register with the email address:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when registering with the email address:', error);
}
Log in using an account and password. This interface supports both mobile phone numbers and email addresses.
API description
static loginAccount(params: ITSmartUserLoginParams): Promise<TSmartUserResponse<boolean>>
Parameters
ITSmartUserLoginParams structure
| Parameter | Type | Description |
|---|---|---|
| account | string | The mobile phone number or email address. |
| countryCode | string | The country code. Example: 86. |
| password | string | The password. |
| accountType | TSmartUserAccountType | The account type. Valid values:
|
| twiceCode | string (optional) | The verification code of two-factor authentication. |
Sample code
Log in with a phone number:
try {
const result = await TSmartUser.loginAccount({
account: '13800138000',
countryCode: '86',
password: 'your_password',
accountType: TSmartUserAccountType.PHONE
});
if (result.success) {
console.log('Logged in successfully');
} else {
console.error('Failed to log in:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during login:', error);
}
Log in with an email address:
try {
const result = await TSmartUser.loginAccount({
account: 'user@example.com',
countryCode: '86',
password: 'your_password',
accountType: TSmartUserAccountType.EMAIL
});
if (result.success) {
console.log('Logged in with the email address successfully');
} else {
console.error('Failed to log in with the email address:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during login with the email address:', error);
}
Before resetting the password, you need to obtain a verification code and verify it. This interface supports both mobile phone numbers and email addresses.
API description
static resetPassword(params: ITSmartUserResetPasswordParams): Promise<TSmartUserResponse<boolean>>
Parameters
ITSmartUserResetPasswordParams structure
| Parameter | Type | Description |
|---|---|---|
| account | string | The mobile phone number or email address. |
| countryCode | string | The country code. Example: 86. |
| authCode | string | The verification code received and entered by the user. |
| newPassword | string | The new password. |
| accountType | TSmartUserAccountType | The account type. Valid values:
|
| region | string (optional) | The country/region. |
Sample code
Reset the password by using a mobile phone:
try {
const result = await TSmartUser.resetPassword({
account: '13800138000',
region: 'CN',
countryCode: '86',
authCode: '123456',
newPassword: 'your_new_password',
accountType: TSmartUserAccountType.PHONE
});
if (result.success) {
console.log('The password was reset successfully');
} else {
console.error('Failed to reset the password:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when resetting the password:', error);
}
Reset the password by using an email address:
try {
const result = await TSmartUser.resetPassword({
account: 'user@example.com',
region: 'CN',
countryCode: '86',
authCode: '123456',
newPassword: 'your_new_password',
accountType: TSmartUserAccountType.EMAIL
});
if (result.success) {
console.log('The password was reset using the emaill address successfully');
} else {
console.error('Failed to reset the password using the emaill address:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when resetting the password using the emaill address:', error);
}
Login with a user ID (UID) is implemented with the API method that integrates with registration and login. This applies to existing accounts. The UID is a unique identifier to identify a user in your system.
The UID is a unique identifier to identify a user in your own system. Using UID, you can establish a connection between your system database and Tuya’s database.
API description
Automatically enables login if an account is registered, or enables registration and login if the account is not registered.
static loginOrRegisterByUid(params: ITSmartUserAccountUidParams): Promise<TSmartUserResponse<Record<string, Object>> | TSmartUserResponse<undefined>>
Parameters
ITSmartUserAccountUidParams structure
| Parameter | Type | Description |
|---|---|---|
| uid | string | An anonymous ID, uniquely identifying a user, with no specific format requirements. |
| countryCode | string | The country code. Example: 86. |
| password | string | A unique random identifier assigned to each user ID. It is not the user’s actual password. |
| createHome | boolean | Specifies whether to create a default home. |
Sample code
try {
const result = await TSmartUser.loginOrRegisterByUid({
uid: 'your_uid',
countryCode: '86',
password: 'your_password',
createHome: true
});
if (result.success) {
console.log('Login successful with UID:', result.result);
} else {
console.error('Failed to log in with the UID:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during login with the UID:', error);
}
API description
static logout(): Promise<TSmartUserResponse<boolean>>
Sample code
try {
const result = await TSmartUser.logout();
if (result.success) {
console.log('Logged out successfully');
// Redirect to login page
} else {
console.error('Failed to log out:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred during logout:', error);
}
API description
Delete a user account. During the week following this delete operation, if the user is logged in again, the delete request is canceled. If not, the user is permanently disabled and all its information is deleted after this week.
static cancelAccount(): Promise<TSmartUserResponse<boolean>>
Sample code
try {
const result = await TSmartUser.cancelAccount();
if (result.success) {
console.log('Account was successfully deleted');
} else {
console.error('Failed to delete the account:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when deleting the account:', error);
}
TSmartUser provides a series of static methods to get information about the currently logged-in user.
API description
static isLogin(): boolean
Return value
| Return value | Description |
|---|---|
| boolean | true: logged in. false: not logged in. |
Sample code
const isLoggedIn = TSmartUser.isLogin();
if (isLoggedIn) {
console.log('User has logged in');
} else {
console.log('User is not logged in');
}
API description
// Get username
static getUserName(): string | undefined
// Get phone number
static getPhoneNumber(): string | undefined
// Get email address
static getEmail(): string | undefined
// Get country code
static getCountryCode(): string | undefined
// Get region code
static getRegionCode(): string | undefined
// Get user ID
static getUid(): string | undefined
// Get session ID
static getSid(): string | undefined
// Get nickname
static getNickname(): string | undefined
// Get avatar URL
static getHeadIconUrl(): string | undefined
// Get time zone ID
static getTimezoneId(): string | undefined
// Get temperature unit
static getTempUnit(): TSmartUserTempUnit | undefined
// Get partner identity
static getPartnerIdentity(): string | undefined
// Get electronic code
static getEcode(): string | undefined
// Get registration source
static getRegFrom(): ThingRegType
// Get user alias
static getUserAlias(): string | undefined
// Get additional information
static getExtras(): Map<string, string>
Sample code
// Get complete user information
const userInfo = {
isLoggedIn: TSmartUser.isLogin(),
username: TSmartUser.getUserName(),
phoneNumber: TSmartUser.getPhoneNumber(),
email: TSmartUser.getEmail(),
countryCode: TSmartUser.getCountryCode(),
regionCode: TSmartUser.getRegionCode(),
uid: TSmartUser.getUid(),
sid: TSmartUser.getSid(),
nickname: TSmartUser.getNickname(),
headIconUrl: TSmartUser.getHeadIconUrl(),
timezoneId: TSmartUser.getTimezoneId(),
tempUnit: TSmartUser.getTempUnit(),
partnerIdentity: TSmartUser.getPartnerIdentity(),
ecode: TSmartUser.getEcode(),
regFrom: TSmartUser.getRegFrom(),
userAlias: TSmartUser.getUserAlias(),
extras: TSmartUser.getExtras()
};
console.log('User information:', userInfo);
API description
Refreshes and updates user information.
static updateUserInfo(): Promise<TSmartUserResponse<boolean>>
Sample code
try {
const result = await TSmartUser.updateUserInfo();
if (result.success) {
console.log('User information was updated successfully');
} else {
console.error('Failed to update the user information:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when updating the user information:', error);
}
API description
static updateHeadIcon(url: string): Promise<TSmartUserResponse<boolean>>
Parameters
| Parameter | Type | Description |
|---|---|---|
| url | string | The URL of the specified avatar. |
Sample code
try {
const result = await TSmartUser.updateHeadIcon('https://example.com/avatar.jpg');
if (result.success) {
console.log('Avatar was updated successfully');
} else {
console.error('Failed to update the avatar:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when updating the avatar:', error);
}
API description
static updateTempUnit(tempUnit: TSmartUserTempUnit): Promise<TSmartUserResponse<boolean>>
Parameters
| Parameter | Type | Description |
|---|---|---|
| tempUnit | TSmartUserTempUnit | The unit of temperature.
|
Sample code
try {
const result = await TSmartUser.updateTempUnit(TSmartUserTempUnit.CELSIUS);
if (result.success) {
console.log('Temperature unit was updated successfully');
} else {
console.error('Failed to update the temperature unit:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when updating the temperature unit:', error);
}
API description
static updateNickName(nickName: string): Promise<TSmartUserResponse<boolean>>
Parameters
| Parameter | Type | Description |
|---|---|---|
| nickName | string | The nickname. |
Sample code
try {
const result = await TSmartUser.updateNickName('New nickname');
if (result.success) {
console.log('Nickname was updated successfully');
} else {
console.error('Failed to update the nickname:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when updating the nickname:', error);
}
API description
static updateTimezondId(timezondId: string): Promise<TSmartUserResponse<boolean>>
Parameters
| Parameter | Type | Description |
|---|---|---|
| timezondId | string | The time zone ID. Example: Asia/Shanghai. |
Sample code
try {
const result = await TSmartUser.updateTimezondId('Asia/Shanghai');
if (result.success) {
console.log('Time zone was updated successfully');
} else {
console.error('Failed to update the time zone:', result.errorMsg);
}
} catch (error) {
console.error('An error occurred when updating the time zone:', error);
}
API description
Initializes the user agent information, used for configuring device/user-specific settings.
static initUserAgent(): void
Sample code
TSmartUser.initUserAgent();
API description
Clears the user agent information.
static clearUserAgent(): void
Sample code
TSmartUser.clearUserAgent();
The SDK provides several event notifications that you can listen for using @ohos.events.emitter.
| Event constant | Description |
|---|---|
| TSMART_USER_LOGIN_EVENT | User login notification |
| TSMART_USER_AUTO_LOGIN_EVENT | User auto-login notification |
| TSMART_USER_LOGOUT_EVENT | User logout notification |
| TSMART_USER_SESSION_INVALID | User session expiration notification |
| TSMART_USER_TEMPERATURE_UNIT_CHANGE_EVENT | Temperature unit change notification |
To ensure a good user experience, it is crucial to properly handle the login session expiration issue. Below are common scenarios that might lead to session expiration:
In these scenarios, you need to listen for the TSMART_USER_SESSION_INVALID event and guide the user to navigate to the login page to re-authenticate.
Sample code
import emitter from '@ohos.events.emitter';
import { TSMART_USER_SESSION_INVALID } from '@thingsmart/userlib';
// Listen for session expiration events
const sessionInvalidCallback = (eventData: emitter.EventData): void => {
console.log('User session expired. Please log in again');
// Redirect to login page
// router.pushUrl({ url: 'pages/LoginPage' });
};
// Subscribe to events
emitter.on(TSMART_USER_SESSION_INVALID, sessionInvalidCallback);
// Unsubscribe when appropriate
emitter.off(TSMART_USER_SESSION_INVALID sessionInvalidCallback);
Sample code
import emitter from '@ohos.events.emitter';
import { TSMART_USER_LOGIN_EVENT } from '@thingsmart/userlib';
const loginCallback = (eventData: emitter.EventData): void => {
console.log('Logged in successfully');
// Logic for handling login
};
emitter.on(TSMART_USER_LOGIN_EVENT, loginCallback);
Sample code
import emitter from '@ohos.events.emitter';
import { TSMART_USER_LOGOUT_EVENT } from '@thingsmart/userlib';
const logoutCallback = (eventData: emitter.EventData): void => {
console.log('User has logged out');
// Clear user data
// Redirect to login page
};
emitter.on(TSMART_USER_LOGOUT_EVENT, logoutCallback);
Sample code
import emitter from '@ohos.events.emitter';
import { TSMART_USER_TEMPERATURE_UNIT_CHANGE_EVENT } from '@thingsmart/userlib';
const tempUnitChangeCallback = (eventData: emitter.EventData): void => {
console.log('Temperature unit has changed');
const newTempUnit = TSmartUser.getTempUnit();
console.log('New temperature unit:', newTempUnit);
// Update UI display
};
emitter.on(TSMART_USER_TEMPERATURE_UNIT_CHANGE_EVENT, tempUnitChangeCallback);
Is this page helpful?
YesFeedbackIs this page helpful?
YesFeedback