签名生成
约 775 字大约 3 分钟
调用引力 openapi 接口时,部分接口需要Authorization
和 sign
字段,本文主要给出示例,我们提供了以下 Java
、Golang
和 Python
版本的实例,请参照示例生成签名。
主要分为两个方法如下:
获取 sign
获取 sign
时,先组装 params
参数,参数为接口除了 sign
字段之外的其他所有字段的字典集合,组装完成后,调用 getSign
方法获取 sign 字符串。
提示
params 参数,不同的接口有不同的要求,具体请参考各个接口说明文档。
获取 Authorization
使用上一步获取的sign
和app_key
,调用 getAuthorization
方法获取 Authorization
字符串,其中 app_key 为您申请的开发者应用的 key,您可以在引力后台-设置-引力开发者中查看。
代码示例
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import com.alibaba.fastjson2.JSONObject;
import com.google.common.base.Charsets;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.hash.Hashing;
import org.junit.jupiter.api.Test;
import java.util.*;
public class TestJWT {
@Test public void test() {
String appKey = "your_app_key";
HashMap<String, Object> params = Maps.newHashMap();
params.put("date_list", Arrays.asList("2023-08-14", "2023-08-19"));
params.put("metrics_list", Lists.newArrayList("AdCost","AppActivateStandard","AppROI"));
params.put("dims_list", Lists.newArrayList("date","advertiser_id"));
params.put("statistics_caliber", "user_activated_time");
params.put("decimal_point", 4);
params.put("app_id", 13467210);
// 使用TreeMap保证key按字典序排序,否则可能会校验失败!
TreeMap<String, Object> filtering = new TreeMap<>();
filtering.put("ad_platform_list", Lists.newArrayList());
filtering.put("channel_list", Lists.newArrayList());
filtering.put("version_list", Lists.newArrayList());
filtering.put("turbo_promoted_object_id_list", Lists.newArrayList());
params.put("filtering", filtering);
params.put("sign", "");
String sign = getSign(params, appKey);
System.out.println(sign);
params.put("sign", sign);
String authorization = getAuthorization(appKey, sign);
System.out.println(authorization);
}
/** * 参数加签 *
* @param map 参数
* @param appKey 申请的引力APPKEY
* @return 签名 */
public String getSign(Map<String, Object> map, String appKey) {
List<String> params = new ArrayList<>();
for (Map.Entry<String, Object> entry : map.entrySet()) {
if (entry.getKey().equals("sign")) {
continue;
}
params.add(entry.getKey() + "=" + JSONObject.toJSONString(entry.getValue()));
}
Collections.sort(params);
StringBuilder sb = new StringBuilder();
sb.append(Joiner.on("&").join(params));
sb.append(appKey);
String str = sb.toString().replaceAll("\"", "");
return Hashing.md5().newHasher().putString(str, Charsets.UTF_8).hash().toString();
}
/** * 请求头加签 *
* @param appKey 申请的引力APPKEY
* @param sign 参数加签
* @return 请求头签名
*/ public String getAuthorization(String appKey, String sign) {
HashMap<String, Object> payload = Maps.newHashMap();
payload.put("app_key", appKey);
JWTSigner jwtSigner = JWTSignerUtil.hs256(sign.getBytes());
return JWTUtil.createToken(payload, jwtSigner);
}
}
package test
// install github.com/dgrijalva/jwt-go
import ( "crypto/md5"
"encoding/json"
"fmt"
"github.com/dgrijalva/jwt-go"
"sort"
"strings"
"testing"
)
// 参数签名
// @param params map[string]interface{} 参数
// @param appKey string app key
func getSign(params map[string]interface{}, appKey string) string { paramsList := make([]string, 0)
for k, v := range params {
if k == "sign" {
continue
}
jsonString, _ := json.Marshal(v)
paramString := fmt.Sprintf("%s=%s", k, jsonString)
paramsList = append(paramsList, paramString)
}
sort.Strings(paramsList)
currentString := strings.ReplaceAll(strings.ReplaceAll(strings.Join(paramsList, "&")+appKey, "\"", ""), " ", "")
sign := fmt.Sprintf("%x", md5.Sum([]byte(currentString)))
return sign
}
// 获取请求 authorization
// @param sign string 签名
// @param appKey 请求key
func getAuthorization(sign, appKey string) string { type MyClaims struct {
AppKey string `json:"app_key"`
jwt.StandardClaims
}
claims := MyClaims{
AppKey: appKey,
StandardClaims: jwt.StandardClaims{},
}
t := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
token, _ := t.SignedString([]byte(sign))
return token
}
func Test(t *testing.T) {
params := map[string]interface{}{
"statistics_caliber": "user_activated_time",
"decimal_point": 2,
"metrics_list": []string{"AdCost"},
"date_list": []string{"2023-11-20", "2023-11-20"},
"dims_list": []string{"date"},
"app_id": 1877777,
}
// print sign
sign := getSign(params, "you_app_key")
fmt.Println(sign)
// print Authorization
authorization := getAuthorization(sign, "you_app_key")
fmt.Println(authorization)
}
def get_sign(params: dict , app_key: str) -> str:
"""
@param params: 参数
@param app_key: 引力申请的开发者应用KEY
"""
param_list = []
for k, v in params.items():
if k == "sign":
continue
param_list.append(f"{k}={json.dumps(v,sort_keys=True)}")
param_list.sort()
sb = "&".join(param_list) + app_key
current_str = sb.replace("\"", "").replace(" ", "")
return hashlib.md5(current_str.encode("utf-8")).hexdigest()
def get_authorization(sign: str, app_key: str) -> str:
"""
@param sign: 签名
@param app_key: 引力申请的开发者app_key
"""
return jwt.encode({"app_key": app_key}, sign, algorithm="HS256")
get_authorization(get_sign({}, 'your_app_key'), 'you_app_key')