本文主要演示了基础的在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
{
public function handle($request, Closure $next)
{
if(!isset($request->appid) || !isset($request->appsecret) ){
exit(json_encode(['code'=>404,'msg'=>'缺少参数']));
}
$data = [];
$data['appid'] = trim($request->appid);
$data['appsecret'] = trim($request->appsecret);
$app = DB::table('api_user')->where($data)->item();
if(empty($app)){
exit(json_encode(['code'=>404,'msg'=>'appid或appsecret错误']));
}
return $next($request);
}
}
到现在为止你的中间件已经可以正常使用了
Route::namespace('Api')->middleware(['api_auth'])->group(function(){
Route::get('member','Member@index');
});
下面开始演示
- 如果不携带appid, 提示”缺少参数“
 - 如果 appid 或 appsecret 不正确 提示”appid或appsecret错误“
 3. 如果验证通过 返回需要的数据 
总结 API 接口 没有想象中的神秘 他跟html 没什么区别 无非就是浏览器认识html文本并把它编译成可视内容罢了
|