1、安装thinkphp
composer create-project topthink/think=5.1.* tp5
2、在框架中安装JWT扩展
composer require firebase/php-jwt
3、新建API模块
建议 使用版本控制,api/v1/controller
在API模块下common.php中定义接口 返回参数码
const ERRNO_MAP = [
'OK' => '成功',
'DBERR' => '数据库查询错误',
'NODATA' => '无数据',
'DATAEXIST' => '数据已存在',
'DATAERR' => '数据错误',
'SESSIONERR' => '用户未登录',
'LOGINERR' => '用户登录失败',
'PARAMERR' => '参数错误',
'USERERR' => '用户不存在或未激活',
'ROLEERR' => '用户身份错误',
'PWDERR' => '密码错误',
'REQERR' => '非法请求或请求次数受限',
'IPERR' => 'IP受限',
'THIRDERR' => '第三方系统错误',
'IOERR' => '文件读写错误',
'SERVERERR' => '内部错误',
'UNKOWNERR' => '未知错误',
];
const ERRNO = [
'OK' => '0',
'DBERR' => '4001',
'NODATA' => '4002',
'DATAEXIST' => '4003',
'DATAERR' => '4004',
'SESSIONERR' => '4101',
'LOGINERR' => '4102',
'PARAMERR' => '4103',
'USERERR' => '4104',
'ROLEERR' => '4105',
'PWDERR' => '4106',
'REQERR' => '4201',
'IPERR' => '4202',
'THIRDERR' => '4301',
'IOERR' => '4302',
'SERVERERR' => '4500',
'UNKOWNERR' => '4501',
];
3.1、定义返回数据方法和获取和 解密token方法
/**
* @return \think\response\Json
* @throws Exception
* @author: LuckyHhy
* @date: 2020/3/12
* @name: ajaxReturn
* @describe:向前端返回JSON数据
*/
function ajaxReturn() {
// 形参个数
$args_num = func_num_args();
// 形参列表
$args = func_get_args();
if (1 === $args_num) {
return json([
'errno' => ERRNO['OK'],
'msg' => '成功',
'data' => $args[0]]);
}
if (2 === $args_num) {
return json([
'errno' => $args[0],
'msg' => $args[1]]);
}
if (3 === $args_num) {
return json([
'errno' => $args[0],
'msg' => $args[1],
'data' => $args[2]]);
}
throw new Exception("Error The number of parameters can be one or two or three");
}
/**
* @param $data
* @return JWT|string
* @author: LuckyHhy
* @date: 2020/3/12
* @name: setJWT
* @describe:设置JWT
*/
function setJWT($data) {
$jwt = new JWT();
$token = array(
// "iss" => "http://example.org", // 签发者
// "aud" => "http://example.com", // 认证者
'iat' => time(), // 签发时间
'nbf' => time(), // 生效时间
'exp' => (time() + 60 * 60 * 24 * 7), // 过期时间 7天后的时间戳
'data' => $data,
);
$jwt = $jwt::encode($token, \config('jwt_key'), 'HS256');
return $jwt;
}
/**
* @param $token
* @return array|null
* @author: LuckyHhy
* @date: 2020/3/12
* @name: getJWT
* @describe:获取JWT内容
*/
function getJWT($token) {
$jwt = new JWT();
$data = null;
try {
$jwt_data = $jwt::decode($token, \config('jwt_key'), array('HS256'));
$data = (array) ($jwt_data->data);
} catch (\Throwable $e) {
Log::write($e->getMessage(), 'error');
return null;
}
return $data;
}
4、在API模块下 新建 check目录,新建 ApiCheck.php和ApiCheckLogin.php
4.1 ApiCheck.php (不需要验证登录就可以调取接口所需继承的控制器)
/**
* Class ApiCheck
* @package app\common\controller
*/
class ApiCheck extends Controller
{
protected function initialize()
{
parent::initialize(); // TODO: Change the autogenerated stub
//设置跨域请求
header('content-type:application/json;charset=utf8');
header('Access-Control-Allow-Origin:*');
header('Access-Control-Allow-Methods:POST,GET');
header('Access-Control-Allow-Headers:x-requested-with,content-type');
}
/**
* @return \think\response\Json
* @author: LuckyHhy
* @date: 2020/3/12
* @name: miss
* @describe: 路由miss方法
*/
public function miss() {
return json([
'errno' => \ERRNO['PARAMERR'],
'msg' => '访问接口不存在或参数错误']);
}
}
4.2、ApiCheckLogin (需要验证登录的继承这个验证控制器)
/**
* Class ApiCheckLogin
* @package app\common\controller
*/
class ApiCheckLogin extends ApiCheck
{
/**
* @var
* @author: LuckyHhy
* @date: 2020/3/12-11:50
*/
protected $user_info;
/**
* @return \think\response\Json|void
* @author: LuckyHhy
* @date: 2020/3/14 0014
* @name: initialize
* @describe:
*/
public function initialize() {
$header=$this->request->header();
//获取请求token
$token = isset($header['token'])?$header['token']:null;
/**
* 验证是否登录
*/
if (is_null($token)) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode([
'errno' => ERRNO['SESSIONERR'],
'msg' => ERRNO_MAP['SESSIONERR']]));
}
/**
* 验证登录是否过期
*/
$user_info = getJWT($token);
if (is_null($user_info)) {
header('Content-Type:application/json; charset=utf-8');
exit(json_encode([
'errno' => ERRNO['SESSIONERR'],
'msg' => '登录已过期']));
}
/**
* 存储用户信息
*/
$this->user_info = $user_info;
}
}
5、需要验证登录的登录控制器 login.php
class Login extends ApiCheck
{
/**
* @return \think\response\Json
* @throws \Exception
* @author: LuckyHhy
* @date: 2020/3/14 0014
* @name: login
* @describe:用户登录接口请求验证
*/
public function login(){
//接受登录传过来的信息
$param=$this->request->param();
//1、验证登录信息
// 密码账号等,假如通过
//查询 用户所有信息
$userInfo=['uid='=>1,"username"=>'jackhhy','password'=>'123456'];
//返回用户信息 给与前端保存
return ajaxReturn(setJWT($userInfo));
}
6、获取数据
//不需登录继承
use app\api\check\ApiCheck;
//需登录继承
use app\api\check\ApiCheckLogin;
/**
* Class Comment
* @package app\api\controller\v1
*/
class Comment extends ApiCheckLogin
{
/**
* @return \think\response\Json
* @throws \Exception
* @author: LuckyHhy
* @date: 2020/3/12
* @name: getComment
* @describe:
*/
public function getComment(){
//查询数据
$wechat_fans=db("wechat_fans")->paginate(15);
return ajaxReturn(ERRNO['OK'],'查询数据成功',$wechat_fans);
}
}
7、定义 miss路由,在 route.php中
// 定义miss路由
Route::miss('check/ApiCheck/miss');
8、整个api模块结构
9、数据返回
10、源代码下载