<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class CheckSign
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {   //验证接口调用签名。md5后转大写，time为时间戳
        date_default_timezone_set('PRC');
        $app_id=$request->input('app_id');
        $time=$request->input('time');  //时间戳
        $nonce=$request->input('nonce');
        $sign=$request->input('sign');
        $timeDiff = abs(time() - $time); // 获取时间差的绝对值

        if ($timeDiff >= 600) return \Yz::echoError1('时间异常');
        $cha_s=DB::table('outside_user')->where(['app_id'=>$app_id])->get();
        if(!count($cha_s)==1) return \Yz::echoError1('第三方用户不存在');
        $s_sign=strtoupper(md5($app_id.$time.$nonce.$cha_s[0]->app_secrect));
        if($sign<>$s_sign) return \Yz::echoError1('签名验证失败');

        return $next($request);
    }
}
