<?php


namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

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

        $params = $request->all();


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

        unset($params['sign']);

        $apiSign = self::newSign($params);

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

            // 生成用户请求信息日志
            if (is_array($params)) {
                $params['sign'] =$sign;
                $request_extra = \GuzzleHttp\json_encode($params);
            } else {
                $request_extra = '';
            }
            Log::info('new 服务端-客户端-所有请求信息 ' . $request_extra);
            Log::info('new 服务端签名信息-签名失败：' . $apiSign);
            return apiReturnFail('Payment error_1');
        }

        return $next($request);

    }
    static $serectKey = 'd03cb639cbf2192dcd066277749f8412';
    public static function newSign($data)
    {

        foreach ($data as $key => &$value) {
            if ($key == 'userName' || $key == 'userEmail' || $key == 'userPhone' || $key == 'rand_str') {
                unset($data[$key]);
            }
            if (empty($value) && $value !== '0') {
                unset($data[$key]);
            }
        }
        unset($value);

        if (!is_array($data)) {
            return false;
        }

        ksort($data);

        $sign_str = '';
        foreach ($data as $k => $v) {
            $sign_str .= $k . '=' . $v . '&';
        }
        $sign_str .= 'key=' . self::$serectKey;
        $sign = md5($sign_str);
        return $sign;
    }
}
