cloud access

Cloud access to Tuya Cloud

Access mode

Cloud access diagram

As shown above, the Tuya Cloud supports third-party clouds with HTTPS, Kafka access to Tuya clouds. HTTPS access to the main scenes are: device instructions issued, the device status data acquisition, user information synchronization. Kafka access scenes are: subscribe device real-time data.

Glossary:

  • HTTPS Tuya’s API is invoked based on the HTTPS protocol,developers can encapsulate HTTPS requests based on Tuya’s ATOP protocol.

  • Kafka Kafka is a high-throughput distributed subscription messaging system that handles all of the workflow data in a consumer-scale site. The Tuya cloud platform supports KAFKA mode calls and provides the appropriate accessId and accessKey for developers to invoke.

Suggest:

  • It is recommended to use HTTPS if you need to obtain statistical statistics data or users, devices and other non-real-time data,
  • It is recommended to use Kafka subscription if you need real-time hardware data.

Call the entry

Tuya Cloud consider the enterprises within the export area combined with the distribution of submarine cable and the city’s actual results, there are three available areas the deployment of coverage of Asia, Europe, the United States.

The domain name of the calling API is as follows:

domain protocol domain name data security level service area
AY Https *. Tuyacn.com HTTPS + AES Asia
AZ Https *. Tuyaus.com HTTPS + AES Americas
EU Https *. Tuyaeu.com HTTPS + AES Europe

Note: Tuya Cloud provides Https and other communication protocols, according to business needs can be flexible to choose to use. Third-party cloud access to real-time data recommended using Kafka.

protocol overview

  • HTTPS
  • Call the process     According to the ATOP protocol, the detailed steps for invoking the cloud service via HTTPS are: fill parameters> generate signatures> assemble HTTPS requests> initiate HTTPS requests> get HTTPS responses> resolve json results.

The approximate call procedure is shown in the following figure:   HTTPS call

  • Common parameters     The common parameters that must be passed in any API call are:
parameter name parameter type whether it must be signed parameter description
a String Yes Yes API Name
v String Yes Yes API Interface Version
sid String No Yes User Login Authorization After successful, ATOP is issued to the user’s session of the application
time String Yes Yes timestamp, formatted as a number, the size is not milliseconds in seconds, and the time zone is the standard time zone, for example: 1458010495. The API server allows the client to request a maximum time error of 540 minutes.
sign String Yes No API Input Parameter Signature Results, Signature Algorithm Refer to the following introduction
clientId String Yes Yes Developer’s accessId (Note that the platform is not the same as: ios, android, and so on)
lang String No Yes APP language, such as “en”, “zh_cn”, error message automatically translated by language
ttid String No Yes APP channels or cloud channels, such as company name, for data analysis tracking
os String Yes Yes mobile operating systems such as “Android”, “ios”, cloud can write linux or write company name

Note: Because part of the cloud interface can provide client information, such as access to the device control panel, then need to be based on different clients os assignment, or can not get the correct data. Such as Android is os = Android

Access tutorial

QuickStart (SDK mode)

Tuya is recommended to use the SDK to access the Tuya Cloud, this section will introduce you to the use of HTTPS SDK and Kafka SDK access to Tuya cloud. If you need to access the Tuya Cloud Service by the API, you can view the next section directly.

If you need to call the Tuya cloud service, you need:

  1. Register developer account

  2. Contact Tuya staff to get the only accessId & accessKey (You can be get directly through the developer platform in the future)

HTTPS SDK

1.To use the HTTPS SDK, download the SDK first:HTTPS-SDK.

2.Introduce the SDK into the classpath of your project.

3.Fastjson used in this case, it is necessary to add the corresponding pom.xml dependency (the reader can also choose their favorite JSON tools).

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.14</version>
</dependency>

4.SDK need to use some of the Apache toolkit, it is also necessary to add the corresponding pom.xml dependencies.

<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpcore</artifactId>
  <version>4.4.5</version>
</dependency>
<dependency>
  <groupId>org.apache.httpcomponents</groupId>
  <artifactId>httpclient</artifactId>
  <version>4.5.2</version>
</dependency>
<dependency>
  <groupId>commons-lang</groupId>
  <artifactId>commons-lang</artifactId>
  <version>2.6</version>
</dependency>

5.Write code

Here to obtain a verification code, for example, to explain the use of SDK.

First, create the TuyaCloudClient object, which is the client that we access the Tuya cloud. Fill in the accessId & accessKey (contact Tuya get) and specify the URI and API.

Then, create a request object, and specify HTTPS attributes.

Request parameters may be required in some APIs, and we need to encapsulate these parameters in a Map as a key-value pair, passing the Map to the Request object.

Finally, the request is made through the client.sendRequest () method, and the result of the response is the return value of the method.

The following code is to obtain a sample code verification procedures for developers reference: :

public class HttpSDKTest {

            private static final String END_URI = "https://a1.tuyacn.com/api.json";// Call China's API (you can replace it with other available areas)


            private static final String ACCESS_ID = "xxxx"; // TODO: Contact Tuya Staff to get
            
            private static final String ACCESS_KEY = "xxxxxxxxxxx"; // TODO: Contact Tuya Staff to get

    public static void main(String[] args) {
        /*
         Create client,accessId&accessKey tuya provides
         accessId as clientId
         accessKey for signature
        */
        TuyaCloudClient client = new TuyaCloudClient(ACCESS_ID, ACCESS_KEY, END_URI);

        // Constitute HTTPS request 
        RequestMessage request = new RequestMessage();
        request.setApi("tuya.m.user.mobile.sendcode"); //An API registered with a mobile number

        request.setApiVersion("1.0");
        request.setOs("Linux");
        request.setLang("zh");

        // Package request parameters (interface needs specific parameters, please refer to the API manual)
        Map<String, String> params = new HashMap<String, String>();
        params.put("countryCode", "86");
        params.put("mobile", "186xxxx7671");

        /*
         Note:
            In addition to a few interfactes for  registration and obtaining statistics, most of the interface needs sessionId.

           Refer to the API manual for sessionId.

            You can get the result from the registration and login interface and return the result field as sid

        */

        // The request parameters are added to the HTTP request

        request.setParams(params);

        /*
         Initiate a request and get a response

         If the request succeeds, the result in response will be the result of a JSON object encapsulation.
         If the request fails, look at errorMsg and errorCode and proceed accordingly.
        */
        ResponseMessage response = client.sendRequest(request);
    }

}

Run the program and found that the successful implementation of mobile phones can also receive verification code:

Send verification code successful

See the cloud API list for more APIs

HTTP / HTTPS Connection Method

Business parameters

In addition to API calls must contain public parameters, if the API itself has business-level parameters must also be filled in, each API’s business-level parameters, please refer to API documentation. Business parameters into the postData all passed to the server, for example, the API has two business parameters devId and userId, the format is postData={“devId”:“xxx”,“userId”:“xxx”}

signature

In order to prevent the API call process by hackers malicious tampering, call any API need to carry the signature, ATOP server based on the request parameters, the signature verification, signature illegal request will be rejected. ATOP currently supports multiple signature algorithms, but all signature algorithms require MD5 digests.

Note: For non-mandatory parameters and participation in the signature, the value is empty in the case of participation in the signature, only in case of value to participate in the signature.

If you call the SDK to achieve such a docking, do not care about the specific implementation of the signature.

If you need to directly call API, you can refer to the following steps to sign:

1.For all API request parameters (including public parameters and business parameters postData, postData requires assembly and signing of values. For example, there are the following request parameters:

a=tuya.p.weather.city.info.list,v=1.0,lang=zh-Hans,os=Linux,clientId=accessId,postData={“countryCode”:“CN”},time=1490003743

2.The following parameters are sorted by parameter name according to the dictionary order of parameter names: a=tuya.p.weather.city.info.list,clientId=accessId,lang=zh-Hans,os=Linux,postData={“countryCode”:“CN”},time=1490003743,v=1.0

3.Will sort a good parameter name and parameter values assembled together, the parameters through the || connection, stitching the results as follows:

a=tuya.p.weather.city.info.list|clientId=accessId|lang=zh-Hans|os=Linux|postData={“countryCode”:“CN”}|time=1490003743|v=1.0

At this point, the assembly of the parameters is complete. Next, you need to sign the parameters.

Tuya Smart Cloud according to different business scenarios to provide multiple sets of signature algorithms, cloud-to-cloud signature algorithm specifically as follows:

4.AccessKey is added to the top of the concatenated request string, assuming accessKey is accessKey, and the last signed string is:

accessKeya=tuya.p.weather.city.info.list|clientId=accessId|lang=zh-Hans|os=Linux|postData={“countryCode”:“CN”}|time=1490003743|v=1.0

5.The assembled string using utf-8 encoding, the use of MD5 algorithm on the byte stream after the summary of the summary of the value of 9aa12fb3dde7fb89146aba0bb3abfb97

6.Assemble an HTTPS request, URL-encode all parameter names and parameter values in utf-8 (the order of parameters is optional, but must include signature parameters), and then initiate the request with GET or POST. Assembled requests are as follows:

https://a1.tuyacn.com/api.json?a=tuya.p.weather.city.info.list&time=1490004310&lang=zh-Hans&v=1.0&os=Linux&clientid=accessKey&sign=9aa12fb3dde7fb89146aba0bb3abfb97&postData={“countryCode”:“CN”}

Specific signature tools to achieve the following categories:

public class AtopThirdCloudMobileSignUtil {

//Encapsulates the request parameters
private static TreeMap<String, String> paramsBuild(ApiRequestDO apiRequestDo) {
TreeMap<String, String> params = new TreeMap<String, String>();
params.put("a", apiRequestDo.getApi());
params.put("v", apiRequestDo.getApiContextDo().getApiVersion());
params.put("lat", apiRequestDo.getApiContextDo().getLat());
params.put("lon", apiRequestDo.getApiContextDo().getLon());
params.put("lang", apiRequestDo.getApiContextDo().getLang());
params.put("deviceId", apiRequestDo.getApiContextDo().getDeviceid());
params.put("appVersion", apiRequestDo.getApiContextDo().getAppVersion());
params.put("ttid", apiRequestDo.getApiContextDo().getTtid());
params.put("os", apiRequestDo.getApiContextDo().getOs());
params.put("clientId", apiRequestDo.getAppInfoDo().getClientId());
if (StringUtils.isNotBlank(apiRequestDo.getN4h5())) {
params.put("n4h5", apiRequestDo.getN4h5());
}
params.put("sp", apiRequestDo.getSp());
params.put("time", apiRequestDo.getT());
if (StringUtils.isNotBlank(apiRequestDo.getSession())) {
params.put("sid", apiRequestDo.getSession());
}
if (StringUtils.isNotBlank(apiRequestDo.getData())) {
params.put("postData", apiRequestDo.getData());
}
return params
}

//The concatenation parameter string
private static String signAssembly(TreeMap<String, String> params, String secretKey) {
StringBuilder str = new StringBuilder();
str.append(secretKey);
Set<String> keySet = params.keySet();
Iterator<String> iter = keySet.iterator();
while (iter.hasNext()) {
String key = iter.next();
if (StringUtils.isBlank(params.get(key))) {
continue;
}
str.append(key);
str.append("=");
str.append(params.get(key));
str.append("|");
}
String strValue = str.toString();
strValue = strValue.substring(0, (strValue.length() - 1));
return strValue;
}

//Get the signature
private static String getSign(ApiRequestDO apiRequestDo, String secretKey) {
TreeMap<String, String> params = paramsBuild(apiRequestDo);
String signString = signAssembly(params, secretKey);
return signString;
}

//MD5
public static String getMD5(byte[] source) {
String s = null;
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(source);
byte tmp[] = md.digest(); // MD5 results in a 128-bit long integer,
//Byte is 16 bytes
char str[] = new char[16 * 2]; // Each byte in hexadecimal, then the use of two characters,
//Therefore, 32 hexadecimal characters are required
int k = 0; //Indicates the corresponding character position in the conversion result
for (int i = 0; i < 16; i++) { //Starting from the first byte, for every byte of MD5
//Convert to hexadecimal characters
byte byte0 = tmp[i]; //Take the i-th byte
str[k++] = hexDigits[byte0 >>> 4 & 0xf]; //Take the high 4-bit digital conversion,
// >>> For the logical right shift, move the sign bit to the right
str[k++] = hexDigits[byte0 & 0xf]; // The lower 4 digits of the byte are converted
}
s = new String(str); //The result is converted to a string

} catch (Exception e) {
logger.warn("MD5 encryption exception!", e);
}
return s;
}

public static void main(String[] args) {
ApiRequestDO apiRequestDo = new ApiRequestDO();

apiRequestDo.setApi("tuya.p.weather.city.info.list");
ApiContextDO apiContextDO = new ApiContextDO();
apiContextDO.setApiVersion("1.0");
apiContextDO.setOs("Linux");
apiContextDO.setLang("zh-Hans");

AppInfoDO appInfoDO = new AppInfoDO();
appInfoDO.setClientId("accessId");
apiRequestDo.setAppInfoDo(appInfoDO);

apiRequestDo.setT("1490004310");
apiRequestDo.setData("{\"countryCode\":\"CN\");

apiRequestDo.setApiContextDo(apiContextDO);

String s = getSign(apiRequestDo, "accessKey");
String sign = MD5Util.getMD5(s.getBytes());
System.out.println(sign);
}
}

note:

  • All request and response data are encoded in UTF-8 format, URL in all parameter names and parameter values do URL encoding

  • PostData uses POST transmission, other parameters support POST and GET

  • To request a different available zone,make sure to use the appropriate domain name

  • The reasons for providing multiple different domain names:

1.Different domain names can be resolved by different DNS service providers to provide the best analytical stability and acceleration services in each region;

2.Can more effectively avoid the operator hijacking problem;

3.Reduce the number of parsing, you can more stable optimization of some remote DNS service provider performance problems.

400 Call

Consult

400-881-8611