小程序接口签名及PHP验签

签名算法

所有参数按字典序排序后用&连接,然后拼接上&key='value',做MD5

小程序生成签名

sign.js

var m = require("./md5.js");

function sort(data)
{
    var keys = Object.keys(data).sort();
    var result = {};
    for(var i = 0; i < keys.length; i++){
        var key = keys[i];
        result[key] = data[key];
    }
    return result;
}



function mtRand(min, max)
{
    var result = Math.random() * (max - min + 1) + min;
    return parseInt(result);
}

function sign(appkey, json)
{
    json.timestamp = Date.parse(new Date()) / 1000;
    json.nonce_str = mtRand(100000, 999999);
    json = sort(json);
    var str = '';
    for (var k in json) {
        if (str != '') 
            str += '&'
        str += k + '=' + json[k]
        }
    str += '&key=' + appkey;
    console.log(str) 
    json.key = appkey;
    json.sign = m(str).toUpperCase();
    delete json.key;
    return json;
}

var x = {
    sign: sign
};
module.exports = x;

php验签

 /**
     * 接口验签
     */
    public function checkSign()
    {
        global $_W;
        $key = Option::get('app_token')->option_value;
        $data = request()->param();
        $timestamp = $data['timestamp'] ?? 0;
        if (time() - $timestamp > 60 || time() - $timestamp < 0 )
            ajaxResponse('',1,'接口过期');
        checkSign($data,$key) || ajaxResponse('',1,'签名错误');



    }

function signature($data, $key)
{
    if (isset($data["sign"])) {
        unset($data["sign"]);//剥离签名
    }
    if (isset($data["key"])) {
        unset($data["key"]);//剥离密匙
    }
    ksort($data);
    $data["key"] = $key;
    $sign = urldecode(http_build_query($data));
    $sign = strtoupper(md5($sign));
    return $sign;
}

/**验证签名
 * @param $data
 * @param $key
 * @return bool
 */
function checkSign($data, $key)
{
    $sign = $data['sign'] ?? '';
    if ($sign == signature($data, $key))
        return true;
    return false;
}

 

你可能感兴趣的:(php,小程序,thinkPHP)