44 lines
1.2 KiB
PHP
44 lines
1.2 KiB
PHP
|
<?php
|
||
|
namespace app\api\service;
|
||
|
|
||
|
class ApiSignService
|
||
|
{
|
||
|
//创建sign
|
||
|
public static function makeSign($data,$appKey): string
|
||
|
{
|
||
|
ksort($data);
|
||
|
$string = self::toUrlParams($data);
|
||
|
$string = $string . "&key=" . $appKey;
|
||
|
$string = md5($string);
|
||
|
return strtolower($string);
|
||
|
}
|
||
|
|
||
|
//检验sign是否正确
|
||
|
public static function verifySign($data,$appKey): array
|
||
|
{
|
||
|
// 验证请求, 2分钟失效
|
||
|
if (time() - $data['timestamp'] > 120) {
|
||
|
return ['code' => 0, 'msg' => '签名已失效'];
|
||
|
}
|
||
|
//比对签名
|
||
|
$clientSign = $data['sign'];
|
||
|
$serverSign = self::makeSign($data,$appKey);
|
||
|
if ($clientSign == $serverSign) {
|
||
|
return ['code' => 1, 'msg' => '验证通过'];
|
||
|
} else {
|
||
|
return ['code' => 0, 'msg' => '签名校验失败'];
|
||
|
}
|
||
|
}
|
||
|
|
||
|
//生成url字符串
|
||
|
private static function toUrlParams($values): string
|
||
|
{
|
||
|
$buff = "";
|
||
|
foreach ($values as $k => $v) {
|
||
|
if ($k != "sign" && !is_array($v)) {
|
||
|
$buff .= $k . "=" . $v . "&";
|
||
|
}
|
||
|
}
|
||
|
return trim($buff, "&");
|
||
|
}
|
||
|
}
|