{"code":0,"message":"success","data":{"title":"Sign your API request","content":"## Introduction\nWhen calling a TikTok Shop API, a signature must be included to properly authenticate your request. All requests that do not include a signature, or have an invalid signature, will be denied access.\nTikTok Shop APIs use **HMAC-SHA256** as the default algorithm for generating signatures.\n**HS256 (HMAC with SHA-256)** is a symmetric algorithm, meaning there is only one private key that is shared between the two parties. Since the same key is used to both generate and validate the signature, care must be taken to ensure that the key is not compromised.\nWhen TikTok Shop receives an authenticated request, it recreates the signature using the authentication information contained in the request. If the signatures match, the service processes the request. Otherwise, it rejects the request.\n❗ **Important**: TikTok Shop APIs use your **app secret** as the private key for authentication. You can obtain your **app secret** from your app details page in Partner Center.\n![Image](https://p16-arcosite-sg.ibyteimg.com/tos-alisg-i-k9wyc2ijk0-sg/cc8d63acb74b4e7bb18413efa3aaace7~tplv-k9wyc2ijk0-image.image)\n\nFor API version `202309` and later, send the access token in the `x-tts-access-token` request header instead of the query string. The access token is not included when generating the signature. For legacy APIs that still use `access_token` as a query parameter, exclude `access_token` from the reordered query keys.\n# Code Samples\nYou can find the code samples in GoLang, Java, Node.js, and Python below. With the code samples, you do not need to dig deep into the algorithm. If you need code samples in other languages, please highlight the sentence and provide feedback for us.\n## Signature algorithm (Go)\n```Go\nimport (  \n    \"bytes\"  \n    \"crypto/hmac\"  \n    \"crypto/sha256\"  \n    \"encoding/hex\"  \n    \"io\"  \n    \"mime\"  \n    \"net/http\"  \n    \"sort\"  \n)  \n  \n// secret: App secret  \nfunc CalSign(req *http.Request, secret string) string {  \n    queries := req.URL.Query()  \n  \n    // extract all query parameters excluding sign and access_token  \n    keys := make([]string, len(queries))  \n    idx := 0  \n    for k := range queries {  \n        // params except 'sign' \u0026 'access_token'  \n        if k != \"sign\" \u0026\u0026 k != \"access_token\" {  \n            keys[idx] = k  \n            idx++  \n        }  \n    }  \n      \n    // reorder the parameters' key in alphabetical order  \n    sort.Slice(keys, func(i, j int) bool {  \n        return keys[i] \u003c keys[j]  \n    })  \n  \n    // Concatenate all the parameters in the format of {key}{value}  \n    input := \"\"  \n    for _, key := range keys {  \n        input = input + key + queries.Get(key)  \n    }  \n  \n    // append the request path  \n    input = req.URL.Path + input  \n  \n    // if the request header Content-type is not multipart/form-data, append body to the end  \n    mediaType, _, _ := mime.ParseMediaType(req.Header.Get(\"Content-type\"))  \n    if mediaType != \"multipart/form-data\" {  \n        body, _ := io.ReadAll(req.Body)  \n        input = input + string(body)  \n          \n        req.Body.Close()  \n        // reset body after reading from the original  \n        req.Body = io.NopCloser(bytes.NewReader(body))  \n    }  \n  \n    // wrap the string generated in step 5 with the App secret  \n    input = secret + input + secret  \n  \n    return generateSHA256(input, secret)  \n}  \n  \nfunc generateSHA256(input, secret string) string {  \n    // encode the digest byte stream in hexadecimal and use sha256 to generate sign with salt(secret)  \n    h := hmac.New(sha256.New, []byte(secret))  \n  \n    if _, err := h.Write([]byte(input)); err != nil {  \n        // TODO error log  \n        return \"\"  \n    }  \n  \n    return hex.EncodeToString(h.Sum(nil))  \n}\n```\n\n## Signature algorithm (Java)\n```Java\npackage org.example;\n\nimport okhttp3.HttpUrl;\nimport okhttp3.Request;\nimport okhttp3.RequestBody;\nimport okio.Buffer;\n\nimport javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.nio.charset.StandardCharsets;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.List;\n\npublic class Main {\n    public String generateSignature(Request request, String secret) {\n    HttpUrl httpUrl = request.url();\n    List\u003cString\u003e parameterNameList = new ArrayList\u003c\u003e(httpUrl.queryParameterNames());\n\n    // extract all query parameters excluding sign and access_token\n    parameterNameList.removeIf(param -\u003e \"sign\".equals(param) || \"access_token\".equals(param));\n\n    // reorder the parameters' key in alphabetical order\n    Collections.sort(parameterNameList);\n\n    // append the request path\n    StringBuilder parameterStr = new StringBuilder(httpUrl.encodedPath());\n    for (String parameterName : parameterNameList) {\n        // Concatenate all the parameters in the format of {key}{value}\n        parameterStr.append(parameterName).append(httpUrl.queryParameter(parameterName));\n    }\n\n    // if the request header Content-type is not multipart/form-data, append body to the end\n    String contentType = request.header(\"Content-Type\");\n    if (!\"multipart/form-data\".equalsIgnoreCase(contentType)) {\n        try {\n            RequestBody requestBody = request.body();\n            if (requestBody != null) {\n                Buffer bodyBuffer = new Buffer();\n                requestBody.writeTo(bodyBuffer);\n                byte[] bodyBytes = bodyBuffer.readByteArray();\n                parameterStr.append(new String(bodyBytes, StandardCharsets.UTF_8));\n            }\n        } catch (Exception e) {\n            throw new RuntimeException(\"failed to generate signature params\", e);\n        }\n    }\n\n    // wrap the string generated in step 5 with the App secret\n    String signatureParams = secret + parameterStr + secret;\n\n    // encode wrapped string using HMAC-SHA256\n    return generateSHA256(signatureParams, secret);\n}\n\n/**\n * generate signature by SHA256\n * @param signatureParams signature params\n * @return signature\n */\npublic String generateSHA256(String signatureParams, String secret) {\n    try {\n        // Get an HmacSHA256 Mac instance and initialize with the secret key\n        Mac sha256HMAC = Mac.getInstance(\"HmacSHA256\");\n        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), \"HmacSHA256\");\n        sha256HMAC.init(secretKeySpec);\n\n        // Update with input data\n        sha256HMAC.update(signatureParams.getBytes(StandardCharsets.UTF_8));\n\n        // Compute the HMAC and get the result\n        byte[] hashBytes = sha256HMAC.doFinal();\n\n        // Convert to hex string\n        StringBuilder sb = new StringBuilder();\n        for (byte hashByte : hashBytes) {\n            sb.append(String.format(\"%02x\", hashByte \u0026 0xff));\n        }\n\n        return sb.toString();\n    } catch (Exception e) {\n        throw new RuntimeException(\"failed to generate signature result\", e);\n    }\n}\n}\n```\n\n## Signature algorithm (Node.js)\n```TypeScript\nimport crypto from \"crypto\";\nimport localVarRequest from \"request\";\nconst excludeKeys = [\"access_token\", \"sign\"] as const;\nexport const generateSign = (\n  requestOption: localVarRequest.Options,\n  app_secret: string\n) =\u003e {\n  let signString = \"\";\n  // step1: Extract all query parameters excluding sign and access_token. Reorder the parameter keys in alphabetical order:\n  const params = requestOption.qs || {};\n  const sortedParams = Object.keys(params)\n    .filter((key) =\u003e !excludeKeys.includes(key as any))\n    .sort()\n    .map((key) =\u003e ({ key, value: params[key] }));\n  //step2: Concatenate all the parameters in the format {key}{value}:\n  const paramString = sortedParams\n    .map(({ key, value }) =\u003e `${key}${value}`)\n    .join(\"\");\n\n  signString += paramString;\n\n  //step3: Append the string from Step 2 to the API request path:\n// @ts-ignore\n  const pathname = new URL(requestOption!.uri!||'').pathname;\n\n  signString = `${pathname}${paramString}`;\n\n  //step4: If the request header content-type is not multipart/form-data, append the API request body to the string from Step 3:\n  if (\n    requestOption.headers?.[\"content-type\"] !== \"multipart/form-data\" \u0026\u0026\n    requestOption.body \u0026\u0026\n    Object.keys(requestOption.body).length\n  ) {\n    const body = JSON.stringify(requestOption.body);\n    signString += body;\n  }\n\n  //step5: Wrap the string generated in Step 4 with the app_secret:\n  signString = `${app_secret}${signString}${app_secret}`;\n\n  //step6: Encode your wrapped string using HMAC-SHA256:\n  const hmac = crypto.createHmac(\"sha256\", app_secret);\n  hmac.update(signString);\n  const sign = hmac.digest(\"hex\");\n\n  return sign;\n};\n```\n\n## Signature algorithm (Python)\n```Python\nimport hmac\nimport hashlib\nfrom urllib.parse import urlparse\nimport json\n\ndef generate_sign(request_option, app_secret):\n    \"\"\"\n    Generate HMAC-SHA256 signature\n    :param request_option: Request options dictionary containing qs (query params), uri (path), headers, body etc.\n    :param app_secret: Secret key for signing\n    :return: Hexadecimal signature string\n    \"\"\"\n    # Step 1: Extract and filter query parameters, exclude \"access_token\" and \"sign\", sort alphabetically\n    params = request_option.get('qs', {})\n    exclude_keys = [\"access_token\", \"sign\"]\n    sorted_params = [\n        {\"key\": key, \"value\": params[key]}\n        for key in sorted(params.keys())\n        if key not in exclude_keys\n    ]\n\n    # Step 2: Concatenate parameters in {key}{value} format\n    param_string = ''.join([f\"{item['key']}{item['value']}\" for item in sorted_params])\n    sign_string = param_string\n\n    # Step 3: Append API request path to the signature string\n    uri = request_option.get('uri', '')\n    pathname = urlparse(uri).path if uri else ''\n    sign_string = f\"{pathname}{param_string}\"\n\n    # Step 4: If not multipart/form-data and request body exists, append the exact body string to be sent\n    content_type = request_option.get('headers', {}).get('content-type', '')\n    body = request_option.get('body', {})\n    if content_type != 'multipart/form-data' and body:\n        if isinstance(body, str):\n            body_str = body\n        else:\n            body_str = json.dumps(body, separators=(',', ':'))  # Keep JSON serialization compact and consistent with the request body\n        sign_string += body_str\n\n    # Step 5: Wrap signature string with app_secret\n    wrapped_string = f\"{app_secret}{sign_string}{app_secret}\"\n\n    # Step 6: Encode using HMAC-SHA256 and generate hexadecimal signature\n    hmac_obj = hmac.new(\n        app_secret.encode('utf-8'),\n        wrapped_string.encode('utf-8'),\n        hashlib.sha256\n    )\n    sign = hmac_obj.hexdigest()\n    return sign\n```\n\n# Step-by-step breakdown\n![Image](https://p16-arcosite-sg.ibyteimg.com/tos-alisg-i-k9wyc2ijk0-sg/9204af7b93b648a4abd51f5969b24bec~tplv-k9wyc2ijk0-image.image)\nThe following is a step-by-step breakdown of how the signature algorithm works:\n📌 **Note**: Feel free to skip straight to the **signature algorithm** sections if you do not need a step-by-step breakdown. We've provided sample code in Go, Java, Node.js, and Python\n\n1. As an example, let's assume you'd like to call the Get Authorized Shops endpoint and your `app_secret` is **e59af819cc**:\n\n```HTTP\ncurl -X GET \\\n 'https://open-api.tiktokglobalshop.com/authorization/202309/shops?app_key=29a39d\u0026sign=b596b73e0cc6de07ac26f036364178ab16b0a907af13d43f0a0cd2345f582dc8\u0026timestamp=1623812664' \\\n-H 'x-tts-access-token: TTP_pwSm2AAAAABmmtFz1xlyKMnwg74T2GJ5s0uQbS8jPjb_GkdFVCxPqzQXSyuyfXdQa0AqyDsea2tYFNVf4XeqgZHFfPyv0Vs659QqyLYfsGzanZ5XZAin3_ZkcIxxS0_In6u6XDeU96k' \\\n-H 'content-type: application/json'\n```\n\n\n2. Extract all query parameters excluding `sign` and `access_token`. Reorder the parameter keys in alphabetical order:\n\n```Go\nkeys := make([]string, len(queries))    \nidx := 0    \nfor k := range queries {    \n    // params except 'sign' \u0026 'access_token'   \n    if k != \"sign\" \u0026\u0026 k != \"access_token\" {    \n       keys[idx] = k    \n       idx++    \n    }    \n}    \nsort.Slice(keys, func(i, j int) bool {    \n    return keys[i] \u003c keys[j]    \n})\n```\n\nThe resulting reordered query keys is:\n```Plain Text\nkeys = []string{    \n    \"app_key\",       \n    \"timestamp\"    \n}\n```\n\n📌 **Note**: Some API endpoints will require the **shop_cipher** query parameter, which would then be included in the reordered query keys. Please call [Get Authorized Shops](https://partner.tiktokshop.com/docv2/page/get-authorized-shops) to obtain a shop's corresponding **shop_cipher**.\n\n3. Concatenate all the parameters in the format `{key}{value}`:\n\n```Go\n// Concatenate all the parameters in the format of {key}{value}  \ninput := \"\"    \nfor _, key := range keys {      \n   input = input + key + queries.Get(key)      \n}\n```\n\nThe resulting string becomes:\n```Plain Text\napp_key29a39dtimestamp1623812664\n```\n\n\n4. Append the string from Step 3 to the API request path. The path for Get Authorized Shops is `/authorization/202309/shops`:\n\n```Plain Text\ninput = path + input\n```\n\nThe resulting string becomes:\n```Plain Text\n/authorization/202309/shopsapp_key29a39dtimestamp1623812664\n```\n\n📌 **Note**: If the request header content-type is not multipart/form-data, append the API request body to the string as well. Use the exact body bytes that are sent in the HTTP request. Do not parse and re-serialize or reformat the body for signing, because changes to field order, whitespace, escaping, or charset can produce a different signature.\n```Plain Text\ninput = input + body\n```\n\nFor example, the [Update Shop Webhook](https://partner.tiktokshop.com/docv2/page/update-shop-webhook) endpoint includes the address and event_type parameters in the API request body (as well as the shop_cipher parameter in the query parameters). This would result in the following:\n```Plain Text\n/event/202309/webhooksapp_key68xu9ks5p4i8shop_cipherROW_xkMbgAAAeVAQra0eZWebFQq5aIKtimestamp1696909648{\"address\":\"https://partner.tiktokshop.com\",\"event_type\":\"PACKAGE_UPDATE\"}\n```\n\n\n5. Wrap the string generated in Step 4 with your `app_secret`:\n\n```Plain Text\ninput = app_secret + input + app_secret\n```\n\nThe final string becomes:\n```Plain Text\ne59af819cc/authorization/202309/shopsapp_key29a39dtimestamp1623812664e59af819cc\n```\n\n\n6. Encode your wrapped string using **HMAC-SHA256**:\n\n```Go\nimport (      \n   \"crypto/hmac\"      \n   \"crypto/sha256\"      \n   \"encoding/hex\"      \n   \"sort\"      \n)      \n/**      \n** input: string we created in step 5   \n** secret: App secret      \n**/      \nfunc generateSHA256(input, secret string) string{      \n   // encode the digest byte stream in hexadecimal and use sha256 to generate sign with salt(secret)      \n   h := hmac.New(sha256.New, []byte(secret))      \n  \n   if _, err := h.Write([]byte(input)); err != nil{      \n      // TODO error log   \n      return \"\"      \n   }      \n      \n   return hex.EncodeToString(h.Sum(nil))      \n}\n```\n\nThe resulting sign is:\n```Plain Text\nb596b73e0cc6de07ac26f036364178ab16b0a907af13d43f0a0cd2345f582dc8\n```\n\n# Common mistakes\nWhat is the most common reason for encountering the \"signature is invalid\" error during an API call?\n\n* Frequently, this error occurs when developers use incorrect app keys and secrets to generate the signature. It's essential to verify that the app key and secret match precisely.\n* Ensure `sign` and `access_token` are **not** included in the reordered query keys (Step 2).\n* For API version `202309` and later, send the access token in the `x-tts-access-token` header. Do not include this header value in the signature string.\n* Always ensure that you are using the **HMAC-SHA256** signature method (different from regular SHA-256).\n* Ensure that the timestamp is within 5 minutes of the current time when the platform receives the request. The timestamp must be represented as a 10-digit Unix timestamp.\n* If the request is not `multipart/form-data`, sign the exact body bytes that you send. Re-serializing JSON can change whitespace, field order, or escaping and cause signature verification to fail.\n","update_time":"1783340341","view_count":0,"prev_document_id":"678e3a40c0833b03100a46b1","prev_document_path":"methods-and-endpoints","next_document_id":"678e3a4278f4c20311b8b57e","next_document_path":"common-parameters","is_api_doc":false,"document_id":"678e3a3d4ddec3030b238faf","doc_type":2,"keywords":[{"keyword":"","font_color":"#141414","background_color":"#E6E6E6"}],"redirect_document_path":"sign-your-api-request"}}