User Account Management

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.

Account types

Different types of accounts support the following specific capabilities:

  • An account that is registered with a mobile phone number supports two login methods: verification code login and password login.
  • An account that is registered with an email address also supports two login methods: verification code login and password login.
  • An app UID applies to existing account systems.

Functional description

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 the module.

import { TSmartUser } from '@thingsmart/userlib';

SmartLife App SDK supports registration and login with a user’s mobile phone number and password.

Manage verification code

Query country or region for verification code service

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 code

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:
  • 1: Send a verification code when registering an account.
  • 3: Send a verification code when resetting the account password.
  • 7: Send a verification code when changing the linked account.
  • 8: Send a verification code when deleting an account.
  • 9: Send a verification code when linking with an account.
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);
}

Verify verification code

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:
  • 1: Verify the verification code when registering an account.
  • 3: Verify the verification code when resetting the account password.
  • 7: Verify the verification code when changing the linked account.
  • 8: Verify the verification code when deleting an account.
  • 9: Verify the verification code when linking with an account.
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);
}

Manage account

Register account

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:
  • 1: Mobile phone number
  • 2: Email address
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 with account and password

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:
  • 1: Mobile phone number
  • 2: Email address
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);
}

Reset the password

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:
  • 1: Mobile phone number
  • 2: Email address
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);
}

Log in with UID

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);
}

Log out

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);
}

Inactivate or delete account

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);
}

Get user information

TSmartUser provides a series of static methods to get information about the currently logged-in user.

Check login status

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');
}

Get basic user information

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);

Modify account information

Update user information

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);
}

Update user avatar

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);
}

Set temperature unit to Celsius or Fahrenheit

API description

static updateTempUnit(tempUnit: TSmartUserTempUnit): Promise<TSmartUserResponse<boolean>>

Parameters

Parameter Type Description
tempUnit TSmartUserTempUnit The unit of temperature.
  • 1: °C (Celsius)
  • 2: °F (Fahrenheit)

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);
}

Modify the nickname

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);
}

Update user’s time zone

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);
}

Advanced features

Initialize user agent

API description

Initializes the user agent information, used for configuring device/user-specific settings.

static initUserAgent(): void

Sample code

TSmartUser.initUserAgent();

Clear user agent

API description

Clears the user agent information.

static clearUserAgent(): void

Sample code

TSmartUser.clearUserAgent();

Send event notifications

The SDK provides several event notifications that you can listen for using @ohos.events.emitter.

Event types

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

Listen for session expiration events

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:

  • No operation has been performed for an extended period, specifically no data requests have been initiated for over 45 days.
  • The account password has been modified through another device while the user is already logged in.
  • The same account has logged in on multiple devices. When the limit of concurrent device logins is exceeded, the earliest session will be forcibly logged out.

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);

Listen for login events

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);

Listen for logout events

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);

Listen for temperature unit change events

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);