API 接口通用的检测基类 [ 2.0 版本 ]
<?php
namespace app\controllers;
use yii\web\Controller;
use Yii;
/**
* 核心的app类
* Class AppController
* @package app\controllers
*/
class AppController extends Controller {
public $enableCsrfValidation = false;
public $msg = ['status' => 0,'msg' => '数据请求失败','data'=>[]];
/**
* 初始化的数据程序
*/
public function init()
{
//parent::init();
$this->setHeader();
if(YII_DEBUG == false){
$this->checkSign();
$this->checkLogin();
}
}
/**
* 设置头部信息
*/
protected function setHeader()
{
Yii::$app->response->headers->set('Access-Control-Allow-Origin','*');
//Yii::$app->response->headers->set("Access-Control-Allow-Headers", "Content-Type,token");
Yii::$app->response->headers->set("Access-Control-Allow-Methods", "POST,GET");
}
/**
* 检测请求的签名
* @return \yii\web\Response
*/
public function checkSign()
{
$appid = Yii::$app->request->headers->get('appid');
$reqtime = Yii::$app->request->headers->get('reqtime');
$sign = Yii::$app->request->headers->get('sign');
if(empty($appid)){
$this->msg['code'] = 10000;
$this->msg['msg'] = '应用id不能为空';
Yii::$app->end(0,$this->asJson($this->msg));
}
if(empty($reqtime)){
$this->msg['code'] = 10001;
$this->msg['msg'] = '当前的请求时间不能为空';
Yii::$app->end(0,$this->asJson($this->msg));
}
$expirsetime = time()- $reqtime;
if($expirsetime < 0 || $expirsetime >3){
$this->msg['code'] = 10002;
$this->msg['msg'] = '请求已过期';
Yii::$app->end(0,$this->asJson($this->msg));
}
if(empty($sign)){
$this->msg['code'] = 10003;
$this->msg['msg'] = '应用签名不能为空';
Yii::$app->end(0,$this->asJson($this->msg));
}
$signString = 'appid='.$appid.'&reqtime='.$reqtime.'&key=123456';
$mySign = md5($signString);
if($sign !==$mySign){
$this->msg['code'] = 10004;
$this->msg['msg'] = '非法请求';
$this->msg['data'] = ['sign'=>$sign,'mySign'=>$mySign];
Yii::$app->end(0,$this->asJson($this->msg));
}
}
/**
* 检查用户是否登陆
* @throws \yii\base\ExitException
*/
protected function checkLogin()
{
$token = Yii::$app->request->headers->get('token');
if(empty($token)){
$this->msg['code'] = 10005;
$this->msg['msg'] = 'token 不能为空';
Yii::$app->end(0,$this->asJson($this->msg));
}
$userSessionInfo = Yii::$app->session->readSession($token);
$userSessionInfo = json_decode($userSessionInfo,true);
if(empty($userSessionInfo)){
$this->msg['code'] = 10006;
$this->msg['msg'] = '登录的时间超时,请重新登录';
Yii::$app->end(0,$this->asJson($this->msg));
}
}
public function getUid()
{
$token = Yii::$app->request->headers->get('token');
$userSessionInfo = Yii::$app->session->readSession($token);
$userSessionInfo = json_decode($userSessionInfo,true);
return $userSessionInfo;
}
}
wonderwong 深圳
注册时间:2012-03-21
最后登录:2024-06-01
在线时长:10小时29分
最后登录:2024-06-01
在线时长:10小时29分
- 粉丝8
- 金钱290
- 威望70
- 积分1090
共 1 条评论
按照你的这个代码写法,返回得是 error Attempt to assign property "format" on string
是不是需要在main文件里面配置这个呢
'response' => [
'format' => yii\web\Response::FORMAT_JSON, 'charset' => 'UTF-8', // ... ],
现在才看到,你这个返回数据不是数组 ,是字符串。