服务端相关

RESTful接口的ThinkPHP3.2实现

2017-05-17  本文已影响768人  AiDede

RESTful

什么是RESTful接口呢?这里引几个文章,可以先行阅读

我们为什么要用RESTful

Try it!

这里我们实现一个登陆换取TOKEN的例子

namespace V1\Controller;
use Think\Controller\RestController;//use Rest的控制器
class AuthController extends RestController //继承Rest控制器
{
    //protected $allowMethod  = array('get','post','put','delete'); // REST允许的请求类型列表
    //protected $allowType    = array('json','html'); // REST允许请求的资源类型列表
    public function index(){
      
    }
 }
image.png

于是我们就可以新建一个方法login_post

public function login_post(){
  echo "test";  
  //TODO
}

注意这里都是POST请求

private $res=array(
        'code'=>200,
        'msg'=>'ok',
        'data'=>array()
    );
public function login_post(){
        $uuid = $_POST['uuid'];
        $open = $_POST['open'];
        $timestamp = $_POST['timestamp'];
        if ($uuid==''||$open==''||$timestamp==''){
            $this->res['code']=401;
            $this->res['msg']='Incomplete parameters';
            $this->response($this->res,"json");
            exit();
        }
        $now = time();
        if ($now-$timestamp>3600){
            $this->res['code']=401;
            $this->res['msg']='Login Timeout';
            $this->response($this->res,"json");
            exit();
        }
        $user = M('user');
        $where['uuid']=$uuid;
        $where['open']=$open;
        $result = $user->where($where)->select();
        if (empty($result)){
            $this->res['code']=404;
            $this->res['msg']='Invalid UserID or openid';
            $this->response($this->res,'json');
            exit();
        }else{
            $token = self::_applyTokenAndSaveInRedis($uuid,$open);
            $this->res['data']=array(
                'TOKEN'=>$token,
                'Expiretime'=>3600
            );
            $this->response($this->res,'json');
        }
    }
    private static function _applyTokenAndSaveInRedis($uuid,$open,$expiretime=3600){
        $redis=new \Redis();
        $redis->connect('地址','端口');
        $redis->auth('密码');
        $s = rand(10000,99999);
        $string = $open.$uuid.$s.time();
        $token = md5($string);
        $save = $token."*".(time()+$expiretime);
        $redis->set($uuid,$save);
        return $token;
    }

这里的功能,是收取uuidopentimestamp三个参数,然后首先验证参数是完整,然后验证时间戳是否过期,然后链接数据库验证账号,然后保存生成token并保存在Redis里,然后返回token和过期时间。

参数不全 时间戳过期 参数错误 正常返回

结束

var author = {
  name:'丁波',
  GitHub:'dingbo1028',
  University:'BNUZ'
}
上一篇下一篇

猜你喜欢

热点阅读