一,添加controller/中间件/路由
1,添加中间件
liuhongdi@lhdpc:/data/site/gsapi$ php artisan make:middleware ApiSignINFO Middleware [app/Http/Middleware/ApiSign.php] created successfully.
2,添加路由:
在routes/api.php文件中
Route::controller(VirtualController::class)->group(function () {Route::get('/virtual/info', 'info')->middleware([ApiSign::class]);
});
二,代码
1,中间件:
<?phpnamespace App\Http\Middleware;use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App\extend\result\Result;class ApiSign
{/*** Handle an incoming request.** @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next*/public function handle(Request $request, Closure $next): Response{$post_data = $request->all();if (!$this->getSign($post_data)) {return Result::ErrorCode(1,'接口签名验证错误');} else {return $next($request);}}private function getSign(array $params): bool{//从配置文件中得到secret$app_secret = config("client.my_secret");if (empty($params)) {return false;}if (!isset($params['sign'])) {return false;}$sign = $params['sign'];unset($params['sign']);ksort($params);$strParams = [];foreach ($params as $k => $v) {if (preg_match('/\/\S+\/\S+/', $k) != 0 || preg_match('/\S+\/\S+/', $k) != 0) {continue;}$strParams[] = "$k_$v";}$inputStr = implode('&', $strParams)."&secret_".$app_secret;$creSign = md5($inputStr);return $creSign !== $sign ? false : true ;}}
2,controller:
class VirtualController extends Controller
{//测试接口签名验证public function info(Request $request) {$data = ['name'=>'老张'];return Result::Success($data);}
}
三,测试效果
用postman提交参数: