<?php


namespace App\Http\Middleware;

use App\Util;
use Closure;
use App\Http\helper\ApiSign as Sign;
use Illuminate\Support\Facades\Log;

class ApiSign
{
    /**
     * 验证签名 API接口
     * @param \Illuminate\Http\Request $request
     * @param Closure $next
     */
    public function handle($request, Closure $next)
    {

//        return $next($request);

        $params = $request->all();

        // 生成用户请求信息日志
        if (is_array($params)) {
            try {
                $request_extra = \GuzzleHttp\json_encode($params);
            }catch (\Exception $exception){
                Util::WriteLog("signerror",http_build_query($params));
                $request_extra='';
            }
        } else {
            $request_extra = '';
        }

        $sign = $params['sign'] ?? '';

        unset($params['sign']);

        $apiSign = Sign::sign($params);

        if (!empty($params) && $sign != $apiSign) {



//            Util::WriteLog("signerror",$params);
            Util::WriteLog("signerror",[$params,$_REQUEST,$_SERVER]);

            Log::info('服务端-客户端-所有请求信息 ' . $request_extra);
            Log::info('服务端签名信息-签名失败：' . $apiSign);
            return apiReturnFail('Payment error_1');
        }

        return $next($request);

    }
}
