插件:https://underscorejs.net/
建议:单独创建一个js配置文件存放token,然后加密该文件。
一、前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>接口验签</title> </head> <body> <script src="jquery.min.js"></script> <script src="underscore-min.js"></script> <script src="md5.js"></script> <script> var url = './test.php?action=login&m=a&c=user&i=2'; var params = getQuery(url); var token = 'Yang'; params = _.sortBy(params, 'name'); params = _.uniq(params, true, 'name'); console.log(params) var sign = getSign(params, token); $.get(url+'&sign='+sign, function (res) { }) /** * 获取url所有参数 * @param url * @returns {Array} */ function getQuery (url) { var theRequest = []; if (url.indexOf("?") != -1) { var str = url.split('?')[1]; var strs = str.split("&"); for (var i = 0; i < strs.length; i++) { if (strs[i].split("=")[0] && unescape(strs[i].split("=")[1])) { theRequest[i] = { 'name': strs[i].split("=")[0], 'value': unescape(strs[i].split("=")[1]) } } } } return theRequest; } /** * 获取sign * @param params * @param token * @returns {*} */ function getSign(params, token) { var urlData = ''; for (let i = 0; i < params.length; i++) { if (params[i] && params[i].name && params[i].value) { urlData += params[i].name + '=' + params[i].value + '&'; } } return md5(urlData + token); } </script> </body> </html>
二、后端
/** * Created by PhpStorm. * User: Mr.Yang * Date: 2020/9/11 * Time: 14:40 * QQ: 2575404985 */ $token = 'Yang'; $result = checkSign(); var_dump($result); function checkSign() { global $_GET, $token; if (!empty($_GET) && !empty($_GET['sign'])) { foreach ($_GET as $key => $get_value) { if ('sign' != $key && $get_value != '') { $sign_list[$key] = $get_value; } } ksort($sign_list); $sign = http_build_query($sign_list, '', '&') . '&' . $token; $sign = urldecode($sign); return md5($sign) == $_GET['sign']; } return false; }