<?php
/**
 * @function:Token的生成验证与解析
 * @author:木小果
 * @link:https://blog.muxiaoguo.cn
 * @date:2022/2/24
 */

/*例子 Start*/
$token = generate_access_token('123','456','789');//生成token
echo '生成的token:'.$token.'<br /><br /><br />';
echo '解析token:'.json_encode(analysis_access_token($token));//解析token
/*例子 End*/

/**
 * 生成token
 * @param $appID string 应用ID
 * @param $secretKey string  应用私钥
 * @param $appKey int 应用公钥
 * @return string
 */
function generate_access_token($appID , $secretKey, $appKey)
{
    $time = time();
    $sign = sha1($time . $appID . $secretKey);
    $token = base64_encode("{$time},{$appID},{$appKey},{$sign}");
    return $token;
}

/**
 * 解析TOKEN
 * @param $access_token
 * @return array
 */
function analysis_access_token($access_token)
{
    $token_array = base64_decode($access_token);
    $token_array = explode(',', $token_array);//分割token,分隔符由Token生成算法决定
    if (count($token_array)!=4) {//格式是否错误
        call_back(1101, 'Access Token Format Error');
    }
    
    $time = $token_array[0];//时间戳
    $appID = $token_array[1];//应用ID
    $appKey = $token_array[2];//暴露在外的公钥
    $sign = $token_array[3];//签名
    
    if ($time < (time() - 30) || $time > (time() + 30)) {//校验时间可以自定义,默认30
        call_back(1101, 'Access Token expire');
    }

    $third_platform_app_key = [
     /*appKey => secretKey*/
        '789' => '456'
    ];// app_id-app_key对应表(应从数据库获取)
    
    if (!isset($third_platform_app_key[$appKey])) {//appKey是否存在
        call_back(1101, 'Access Token App id Error');
    }

    $secretKey = $third_platform_app_key[$appKey];

    $local_sign = sha1($time . $appID . $secretKey);// 利用私钥进行签名,验证有效性
    /*sign是否正确*/
    if ($local_sign === $sign) {
        return [
            'access_token' => $access_token,
            'appID' => $appID,
            'time' => $time,
            'appKey' => $appKey,
            'secretKey' => $secretKey,
        ];
    } else {
        call_back(1101, 'Access Token Sign Error');
    }
}
function call_back($code,$msg,$data = []) {
    $data = [
        'code' => $code,
        'msg' => $msg,
        'data' => $data
    ];
    die(json_encode($data,320));
}
最后修改:2022 年 02 月 24 日
如果觉得我的文章对你有用,请随意赞赏