[graffiti Internet of things footprint] graffiti cloud platform interface description

Time:2021-7-28

_ Preface series > > >[graffiti Internet of things footprint] API and SDK introduction

Our series of articles will focus on how to complete the development of an intelligent “space kissing machine”. I hope the lovers of different countries can help each other!

In this article, we will briefly explain the API call methods, specifications, examples and integration SDK related contents involved in development based on OpenAPI. The content will be hard core, please pay attention!

IDevelopment process

  1. Register [developer account]https://auth.tuya.com/registe…://www.tuya.com/cn/&_source=3b65cc767b2db97c5102cd1dfb50f34d)。
  2. Cloud development creates cloud application projects and obtains   client_ id & secret。

explain: the name of the developer platform key   accessId & accessKey。

  1. Create SDK: inGraffiti IOT platform, select  App workbench > App SDK > Get SDK > Fill in the parameters as required > obtainschema(channel identification)
  2. Business development based on OpenAPI.
  3. After the test is correct, the developer will release it by himself.

IIAuthorization process

Token verification is required for each business OpenAPI.

explain: graffiti OpenAPI follows OAuth 2.0 protocol standard.

3、 Simple mode

For cloud docking scenarios, graffiti provides implicit authorization:

[graffiti Internet of things footprint] graffiti cloud platform interface description

  1. According to the graffiti cloud OpenAPI interface specification   client_ id   and   secret   Perform signature authentication.
  2. The graffiti cloud verifies and issues tokens to the third-party cloud.

explain: token obtained by implicit authorization. The permission dimension is the developer dimension. The operation permission range of token is the scope that the developer has permission to operate, such as operating (adding, deleting, modifying and querying) the application user data of the developer, the device data under the product and the device data bound by the user under the application.

IVinterface specification

Environmental description

The user of each interface shall call the corresponding interface according to its own region.

China proper https://openapi.tuyacn.com

American region https://openapi.tuyaus.com

European Region https://openapi.tuyaeu.com

India region https://openapi.tuyain.com

Request mode

The supported request methods are as follows:

  • GET
  • PUT
  • POST
  • DELETE

explain: when the request method isPOSTWhen,Content-Type  Need to useapplication/json

Request header settings

You need to add any of the following parameters to the header interface:

[graffiti Internet of things footprint] graffiti cloud platform interface description

explain: parameters are required for business interface (non token interface) requestsaccess_token

5、 Signature specification

The graffiti cloud uses hmac-sha256 to create a summary. According to different application scenarios, two sets of signature algorithms are currently provided:

  • Token management interface (get token, refresh token)

sign = HMAC-SHA256(client_id + t, secret).toUpperCase()

Use the requested client_ ID and the currently requested 13 bit standard timestamp are spliced into a string to be signed. The cloud application secret is used as the key to participate in the hash summary. The obtained string is finally capitalized;

  • Service interface

sign = HMAC-SHA256(client_id + access_token + t, secret).toUpperCase()

Use the cloud application client applied to_ ID + the currently valid request token + the 13 bit standard timestamp of the current request are spliced into a string to be signed. The cloud application secret applied is used as the key to participate in the hash summary. The obtained string is finally capitalized.

  • Signature example
  1. Prepare parameters:

client_id:1KAD46OrT9HafiKdsXeg

secret:4OHBOnWOqaEC1mWXOpVL3yV50s0qGSRC

t:1588925778000

access_token:3f4eda2bdec17232f67c0b188af3eec1

  1. Token management interface signature:

String to be signed: 1kad46ort9hafikdsxeg1588925778000

Signature result: hmac-sha256 (1kad46ort9hafikdsxeg1588925778000,4ohbonwoqaec1mwxopvl3yv50s0qgsrc)

ceaafb5ccdc2f723a9fd3e91d3d2238ee0dd9a6d7c3c365deb50fc2af277aa83

To capital: ceaafb5ccdc2f723a9fd3e91d3d2238ee0dd9a6d7c3c365deb50fc2af277aa83

3. Service interface:

String to be signed: 1kad46ort9hafikdsxeg3f4eda2bdec17232f67c0b188af3eec1158825778000

Signature result: hmac-sha256 (1kad46ort9hafikdsxeg3f4eda2bdec17232f67c0b188af3eec115882577800,4ohbonwoqaec1mwxopvl3yv50s0qgsrc)

36c30e300f226b68add014dd1ef56a81edb7b7a817840485769b9d6c96d0faa1

To capital: 36c30e300f226b68add014dd1ef56a81edb7b7a817840485769b9d6c96d0faa1

4. Implementation of HMAC sha256 in various languages:

Javascript HMAC SHA256

/**
Run the code online with this jsfiddle. Dependent upon an open source js library calledhttp://code.google.com/p/crypto-js/.
**/

<script></script>
<script></script>

<script> var hash = CryptoJS.HmacSHA256("Message", "secret");
  var hashInBase64 = hash.toString().toUpperCase();
  document.write(hashInBase64); </script>

PHP HMAC SHA256

/**
PHP has built in methods for hash_hmac (PHP 5) and base64_encode (PHP 4, PHP 5) resulting in no outside dependencies. Say what you want about PHP but they have the cleanest code for this example.
**/

$s = hash_hmac('sha256', 'Message', 'secret', true);
echo strtoupper(var_dump($s));

Java HMAC SHA256

/**
Dependent on Apache Commons Codec to encode in base64.
**/

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class ApiSecurityExample {
  public static void main(String[] args) {
    try {
     String secret = "secret";
     String message = "Message";

     Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
     sha256_HMAC.init(secret_key);

      byte[] bytes = sha256_HMAC.doFinal(message.getBytes());
     String hash = new HexBinaryAdapter().marshal(bytes).toUpperCase();
     System.out.println(hash);
    }
    catch (Exception e){
     System.out.println("Error");
    }
   }
}

 C# HMAC SHA256

using System;
using System.Security.Cryptography;

namespace Test
{
  public class MyHmac
  {
    public static string Encrypt(string message, string secret)
            {
                secret = secret ?? "";
                var encoding = new System.Text.UTF8Encoding();
                byte[] keyByte = encoding.GetBytes(secret);
                byte[] messageBytes = encoding.GetBytes(message);
                using (var hmacsha256 = new HMACSHA256(keyByte))
                {
                    byte[] hashmessage = hmacsha256.ComputeHash(messageBytes);
                    StringBuilder builder = new StringBuilder();
                    for (int i = 0; i < hashmessage.Length; i++)
                    {
                        builder.Append(hashmessage[i].ToString("x2"));
                    }
                    return builder.ToString().ToUpper();
                }
            }
  }
} 

The returned results are uniformly returned in JSON. The general format is as follows:

Request succeeded

{
    "success": true,
    "result": {
        //object
    }
}

Request exception

{
    "success": false,
    "code": 1010,
    "MSG": "illegal token"
}

6、 Integrated SDK Javasummary

The currently provided Java based Tuya cloud SDK encapsulates token related, user related and device related interfaces to accelerate the development of cloud cloud docking.

Developers only need to pay attention to the call of the business function methods used, build the corresponding tuyaclient instance, and the instance will automatically update the token and complete the call of the corresponding API. The SDK mainly includes the following functions. For detailed interface information, please refer to the corresponding modules later:

Token related (no user call required)

User related (get user list, register user, get device list under user)

Equipment related (interfaces such as obtaining the equipment distribution network token, obtaining the list of all devices under the distribution network token, etc.)

Integrated SDK

Idea import jar package:https://jingyan.baidu.com/article/0f5fb0993e9e1f6d8334ead2.html

Eclipse import jar package:https://jingyan.baidu.com/article/ca41422fc76c4a1eae99ed9f.html

GitHub address

https://github.com/TuyaInc/tuya_cloud_sdk_java

General module

Since some newly added interfaces cannot be synchronously integrated into the SDK in time, developers can horizontally expand through the common interface of the SDK to meet the development requirements.

Get header list:

/**
 *Get header list
 *Is @ param istoken a token related request, usually false
 * @return
 */
public List<Header> getHeaders(Boolean isToken)

Universal graffiti interface:

/**
 *Universal graffiti interface
 * @param url
 *@ param method request type (for example: get)
 *@ param headers request header content (additional headers)
 * @param body
 * @return
 */
public String commonHttpRequest(String url, HttpMethod method, Map<String, String> headers, Object body)

Call example

The following is an example of a registered user:

​
TuyaClient client = new TuyaClient(clientId, secret, RegionEnum.CN);
String uid = client.registerUser("testApp","86","18212345678", MD5Util.getMD5("123456")"nickName",UserTypeEnum.MOBLIE);
System. Out. Println ("successfully synchronized user:" + uid);

​

Golang

For the source code address of the golang SDK, seeGolang SDK