<?php
namespace frontend\controllers;

use Yii;
use yii\web\Controller;
use yii\web\Response;

abstract class BaseController extends Controller
{
    /**
     * @inheritdoc
     */
    public function init()
    {
        parent::init();
        $this->enableCsrfValidation = false;
    }

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {
        if (parent::beforeAction($action)) {
            //检验签名
            if (true || $this->checkRequestToken()) {
                return true;
            } else {
                $this->outJson(0, '', '验签失败');
                return false;
            }
        }

        return false;
    }

    /**
     * json 输出方法
     * @param int $code api code 码  0 失败 1 正常
     * @param array $data 输出信息
     * @param string $msg 提示语
     * @return Response
     */
    public function outJson($code = 0, $data = array(), $msg = null)
    {
        $data = [
            'code' => $code,
            'message' => $msg,
            'data' => $data,
            'timestamp' => time()
        ];
        return $this->asJson($data);
    }

    /**
     * 验证签名
     * @return bool true验证成功 false验证失败
     */
    private function checkRequestToken()
    {
        $strOauth = '';
        $params = array_merge(Yii::$app->getRequest()->get(), Yii::$app->getRequest()->post());
        $secret = Yii::$app->params['appSignSecret'];//密钥
        //去掉sign值
        $token = isset($params['token']) ? trim($params['token']) : '';
        if ($token == '') {
            return false;
        }
        unset($params['token']);
        ksort($params);//升序排序
        foreach ($params as $key => $val) {
            if ($key == 'token' || is_array($val) || $val === null) {
                continue;
            }
            $strOauth .= $key . '=' . $val . '&';//&符拼接
        }
        $strOauth = rtrim($strOauth, '&') . $secret;//加上密钥
        //md5后验证签名
        if (strcmp(md5($strOauth), $token) !== 0) {
            return false;
        }
        return true;
    }
}