最新消息:imsyx老店新开,原博客因服务器问题,数据全毁,痛心!

js生成接口请求参数签名加密

代码分享 tally 967浏览

定义规则:将所有参数字段按首字母排序, 拼接成key1 = value1 & key2 = value2的格式,再在末尾拼接上key = appSecret, 再做MD5加密生成sign,方法如下:

function getSign(params, AppKey, AppSecret) {
    if (typeof params == "string") {
        return paramsStrSort(params,AppKey,AppSecret);
    } else if (typeof params == "object") {
        var arr = [];
        for (var i in params) {
            arr.push((i + "=" + params[i]));
        }
        return paramsStrSort(arr.join(("&")),AppKey,AppSecret);
    }
}

function paramsStrSort(paramsStr,AppKey,AppSecret) {
    var url = paramsStr + "&appKey=" + AppKey;
    var urlStr = url.split("&").sort().join("&");
    var newUrl = urlStr + '&key=' + AppSecret;
    return md5(newUrl);
}

调用:

var params = "id=" + id + "&type=" + type + "&page=" + page + "&pages=" + pages;
var sign = getSign(params, AppKey, AppSecret);

或:

var paramsObj = { id: id, page: page, type: type, pages: pages };
var sign = getSign(paramsObj, AppKey, AppSecret);

 

转载请注明:小码农 » js生成接口请求参数签名加密