本文主要演示了基础的在laravel框架上的用户携带appid与appsecret 请求数据 返回JSON 的过程
- 第一步 创建演示控制器
api/member.php
php artisan make:controller Api/member
- 第二步 创建中间件
php artisan make:middleware ApiAuth
- 第三步 注册中间件
在app/http/Kernel.php
中的protected $routeMiddleware
数组添加新创建的中间件并给他一个别名
- 第四步 在新建的中间件中写鉴权
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
class ApiAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// api鉴权中间件
// 请求需要 appid appsecret 两个值
// 验证是否有传值
if(!isset($request->appid) || !isset($request->appsecret) ){
exit(json_encode(['code'=>404,'msg'=>'缺少参数']));
}
// 拿到参数
$data = [];
$data['appid'] = trim($request->appid);
$data['appsecret'] = trim($request->appsecret);
// 去查数据库存不存在 访问量大建议存redis
$app = DB::table('api_user')->where($data)->item();
// 如果不存在
if(empty($app)){
exit(json_encode(['code'=>404,'msg'=>'appid或appsecret错误']));
}
// 如果存在继续往下执行
return $next($request);
}
}
到现在为止你的中间件已经可以正常使用了
- 创建新的api路由 带上新创建中间件
// API模块
/**
* namespace指向Api文件夹 因为控制器在Controllers/Api文件夹中 后面路由就不用写了
* 如果不加namespace 路由这样写
* Route::get('member','Api\Member@index');
* 加了namespace
* Route::get('member','Member@index');
*/
Route::namespace('Api')->middleware(['api_auth'])->group(function(){
// 定义get请求
Route::get('member','Member@index');
});
下面开始演示
- 如果不携带appid, 提示”缺少参数“
- 如果 appid 或 appsecret 不正确 提示”appid或appsecret错误“
3. 如果验证通过 返回需要的数据
总结
API 接口 没有想象中的神秘 他跟html 没什么区别 无非就是浏览器认识html文本并把它编译成可视内容罢了