package com.nlm.common.utils;
import com.alibaba.fastjson.JSONObject;
import com.nlm.common.error.NlmException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
/**
* 腾讯移动分析签名返回请求数据接口
*
* @author my
*/
@Slf4j
@Configuration
public class AnalysisSign {
// 签名
@Value("${analysisSign.token}")
private String TOKEN;
// 该URL 带斜杆 https://mta.qq.com/h5/api/
@Value("${analysisSign.url}")
private String URL;
@Value("${analysisSign.appid}")
private String APPID;
/**
* 参数排序 涉及到参数排序可以调用
*
* @param map
* @return
*/
public String getMapToString(Map<String, String> map) {
Set<String> keySet = map.keySet();
// 将set集合转换为数组
String[] keyArray = keySet.toArray(new String[keySet.size()]);
// 给数组排序(升序)
Arrays.sort(keyArray);
// 因为String拼接效率会很低的,所以转用StringBuilder
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
// 参数值为空,则不参与签名 这个方法trim()是去空格
if (map.get(keyArray[i]).trim().length() > 0) {
sb.append(keyArray[i]).append("=").append(map.get(keyArray[i]).trim());
}
}
return sb.toString();
}
/**
* 签名返回数据接口
*
* @param ma
* @param url
* @return
*/
public String analysisResult(Map<String, String> ma, String url) throws NlmException {
// map 转 string
ma.put("app_id", APPID);
String passBackParams = getMapToString(ma);
log.info("map转换成String,结果:{}", passBackParams);
String sign = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update((TOKEN + passBackParams).getBytes());
byte[] resultByteArray = md.digest();
sign = new BigInteger(1, resultByteArray).toString(16);
} catch (NoSuchAlgorithmException e) {
log.error("签名错误!");
}
log.info("签名,{}", sign);
ma.put("sign", sign);
String result = HttpClientUtils.getInstance().doGet(URL + url + "?", ma);
log.info("后台服务分析返回结果:{}", result);
if (result != null || !"".equals(result)) {
JSONObject jsonObject = JSONObject.parseObject(result);
if ("0".equals(jsonObject.getString("code"))) {
return jsonObject.getString("data");
}
}
return result;
}
}