<?php
/**
 * 内部API助手类
 * Created by PhpStorm.
 * User: Ming
 * Date: 2018/3/13
 * Time: 10:21
 */

namespace common\helpers\http;
use common\helpers\Date;
use Yii;
class BackendToFrontendApi {
    /**
     * 通讯密钥
     */
    const AUTH_KEY = '';
    /**
     * 允许的时间差(秒)
     */
    const TIME_DIFF = '';
    /**
     * 请求方法
     */
    const HTTP_METHOD_POST = 'post';
    const HTTP_METHOD_GET = 'get';
    /**
     * 返回成功的标记
     */
    const RETURN_SUCCESS = 'success';
    /**
     * http client
     * @var null
     */
    /**
     * http response
     * @var null
     */
    protected static $response = null;
    /**
     * 获取密钥
     * @return string
     */
    public static function getAuthKey(){
        if(self::AUTH_KEY === ''){
            return Yii::$app->params['http']['backendToFrontendApi']['authKey'];
        }

        return self::AUTH_KEY;
    }

    /**
     * 获取允许的时间差
     * @return string
     */
    public static function getTimeDiff(){
        if(self::TIME_DIFF === ''){
            return Yii::$app->params['http']['backendToFrontendApi']['timeDiff'];
        }
        return self::TIME_DIFF;
    }
    /**
     * 生成签名
     * @param array $params
     * @return array
     */
    public static function paramsFormat(array $params){
        if(!isset($params['timestamp'])){
            $params['timestamp'] = time();
        }
        if(isset($params['signature'])){
            unset($params['signature']);
        }
        ksort($params);
        $string = '';
        foreach($params as $key=>$value){
            $string .= $key.'='.$value . '&';
        }
        $params['signature'] = sha1(trim($string,'&') . self::getAuthKey());
        return $params;
    }

    /**
     * 验证签名
     * @param $signature
     * @param array $params
     * @return bool
     */
    public static function checkSignature($signature, array $params){
        $params = self::paramsFormat($params);
        if($params['signature'] !== $signature){
            return false;
        }
        $timeDiff = (int)self::getTimeDiff();
        if($timeDiff > 0 && (Date::nowTime() - $params['timestamp']) > $timeDiff){
            return false;
        }
        return true;
    }

}