lcly-data-admin/app/Http/Middleware/ApiCustomToken.php

95 lines
2.6 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Http\Middleware;
use Closure;
use App\Models\ThirdLog;
use App\Models\ThirdAccess;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class ApiCustomToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
//获取body参数
$postData = $request->input();
$params = '';
$appKey = Arr::get($postData, 'appKey', '');
$timeStamp = Arr::get($postData, 'timeStamp','');
//拿出sign剩下的参数按照key排序, 拼接
$postSign = Arr::get($postData, 'sign', '');
//记录请求日志
$log = new ThirdLog();
$log->app_id = $appKey;
$log->api_path = $request->path();
$log->request_params = json_encode($postData);
if(empty($appKey) || empty($postSign) || empty($timeStamp)){
$resData = [
'respCd' => '02',
'respMsg' => '参数缺失',
];
// 不做记录
// $log->sign_status = 0;
// $log->http_code = 400;
// $log->response_params = json_encode($resData);
// $log->save();
return response()->json($resData, 400);
}
unset($postData['sign']);
ksort($postData);
foreach ($postData as $k=>$v) {
$params .= "$k=".$v."&"; //默认UTF-8编码格式
}
$postDataStr = substr($params, 0, -1);
$appSecret = ThirdAccess::where('third_appid', $appKey)->value('third_appkey');
//
$sign = md5($postDataStr.$appSecret);
if($sign !== $postSign){
$resData = [
'respCd' => '01',
'respMsg' => '签名失败',
];
//签名失败
$log->sign_status = 0;
$log->http_code = 400;
$log->response_params = json_encode($resData);
$log->save();
return response()->json($resData, 400);
}
if(abs(time() - $timeStamp) > 5*60){
$resData = [
'respCd' => '05',
'respMsg' => '签名过期',
];
//签名过期
$log->sign_status = 0;
$log->http_code = 400;
$log->response_params = json_encode($resData);
$log->save();
return response()->json($resData, 400);
}
$log->save();
$request->offsetSet('log_id', $log->id);
return $next($request);
}
}