Tiktok shop api 调试

记录一下调试Tiktok shop api 踩坑记录。
主要是在按官网api上规则和加密生成sign时候一直通不过的问题:
官网地址:https://partner.tiktokshop.com/doc/page/63fd743e715d622a338c4eab

直接贴代码了


import lombok.extern.slf4j.Slf4j;


import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.*;


/**
 * @author alvis
 * @date 2023/10/19
 */
@Slf4j
public class SignUtil {

    public static String getSignature(String uri, Map<String, String> parametersMap, String appSecret,String body) throws Exception {
        Map<String, String> tempParamsMap = new TreeMap<>(Comparator.naturalOrder());
        tempParamsMap.putAll(parametersMap);
        tempParamsMap.remove("sign");
        tempParamsMap.remove("access_token");
        StringBuilder input = new StringBuilder(uri);
        for (Map.Entry<String, String> entry : tempParamsMap.entrySet()) {
            input.append(entry.getKey()).append(entry.getValue());
        }
        input = new StringBuilder(appSecret + input + body + appSecret);
        return hmacSHA256(appSecret, input.toString());
    }

    public static String getSignature(String uri, Map<String, String> parametersMap, String appSecret) throws Exception {
        Map<String, String> tempParamsMap = new TreeMap<>(Comparator.naturalOrder());
        tempParamsMap.putAll(parametersMap);
        tempParamsMap.remove("sign");
        tempParamsMap.remove("access_token");
        StringBuilder input = new StringBuilder(uri);
        for (Map.Entry<String, String> entry : tempParamsMap.entrySet()) {
            input.append(entry.getKey()).append(entry.getValue());
        }
        input = new StringBuilder(appSecret + input + appSecret);
        return hmacSHA256(appSecret, input.toString());
    }

    /**
     * sha256_HMAC加密
     *
     * @param message 消息
     * @param secret  秘钥
     * @return 加密后字符串
     */
    public static String hmacSHA256(String secret, String message) throws Exception {
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        hmacSha256.init(secret_key);
        byte[] bytes = hmacSha256.doFinal(message.getBytes());
        StringBuilder hs = new StringBuilder();
        String stmp;
        for (int n = 0; bytes != null && n < bytes.length; n++) {
            stmp = Integer.toHexString(bytes[n] & 0XFF);
            if (stmp.length() == 1) {
                hs.append('0');
            }
            hs.append(stmp);
        }
        return hs.toString().toLowerCase();
    }

}

注意 :没有body参数的时候,查询使用无body的函数即可,但是body有参数的时候,此处有坑,拼接字符串的时候要单独处理,body参数构建的json字符串直接拼接在里面即可。这个问题是在postman中代码调试发现:

9a33586972b53ef4d934a5f7b9846cfb95509433/order/202309/orders/searchapp_key6aausirr0gb2fpage_size100shop_cipherTTP_CA2InQEEEEEDEtiBFSZb8SopxJlCAR4g9timestamp1697767243{"create_time_ge":1693497600,"create_time_lt":1697765675}9a33586972b53ef4d934a5f7b9846cfb95509433

你可能感兴趣的:(java,tiktok,api,tiktok,shop,api)