快速构建第三方api应用
1.使用框架和扩展
详细请看composer.json
"php": "^7.1.3",
"laravel-admin-ext/config": "^1.0",
"laravel-admin-ext/helpers": "^1.1",
"laravel/framework": "5.8.*",
"laravel/passport": "7.4.*",
"laravel/tinker": "^1.0",
"dingo/api": "2.2.*",
"encore/laravel-admin": "1.7.7",
"fideloper/proxy": "^4.0",
"jxlwqq/screenfull": "^1.0",
"mpociot/laravel-apidoc-generator": "3.17.*",
"caouecs/laravel-lang": "~4.0"
说明:
整体 -----------------php laravel框架
国际化扩展------------caouecs/laravel-lang
后台管理---------------encore/laravel-admin
后台管理扩展-----------laravel-admin-ext/config(配置) laravel-admin-ext/helpers(小助手)jxlwqq/screenfull(全屏)
后台模块编写-----------helpers中脚手架来快速构建
前台oauth认证---------laravel中默认auth模块
前台接口文档-----------mpociot/laravel-apidoc-generator
接口管理--------------dingo/api
oauth认证------------laravel/passport
2.Dingo API+ laravel passport
Dingo API 负责api route 配置部分
passport 复杂oauth2.0认证
流程:
请求接口 => oauth认证授权=>重新发起请求=> 签名认证等安全认证 => 逻辑接口 => 数据返回
App目录结构
├── Admin
│ ├── bootstrap.php
│ ├── Controllers
│ │ ├── ApiLogController.php
│ │ ├── AuthController.php
│ │ ├── ExampleController.php
│ │ ├── HomeController.php
│ │ ├── OauthClientsController.php
│ │ └── UsersController.php
│ └── routes.php
├── Console
│ └── Kernel.php
├── Exceptions
│ └── Handler.php
├── Helpers
│ └── functions.php
├── Http
│ ├── Controllers
│ │ ├── Api
│ │ │ └── ProductController.php
│ │ ├── Auth
│ │ │ ├── ForgotPasswordController.php
│ │ │ ├── LoginController.php
│ │ │ ├── RegisterController.php
│ │ │ ├── ResetPasswordController.php
│ │ │ └── VerificationController.php
│ │ ├── Controller.php
│ │ └── HomeController.php
│ ├── Kernel.php
│ └── Middleware
│ ├── ApiSign.php
│ ├── Authenticate.php
│ ├── CheckForMaintenanceMode.php
│ ├── EncryptCookies.php
│ ├── RedirectIfAuthenticated.php
│ ├── TrimStrings.php
│ ├── TrustProxies.php
│ └── VerifyCsrfToken.php
├── Models
│ ├── ApiLogModel.php
│ ├── OauthClientsModel.php
│ └── UsersModel.php
├── Observers
│ └── ApiLogObserver.php
├── Providers
│ ├── AppServiceProvider.php
│ ├── AuthServiceProvider.php
│ ├── BroadcastServiceProvider.php
│ ├── EventServiceProvider.php
│ └── RouteServiceProvider.php
└── User.php
3.核心文件代码
ApiLogObserver api观察者类
namespace App\Observers;
class ApiLogObserver
{
private $startTime = 0;
private $stopTime = 0;
//开始运行时间
public function start()
{
$this->startTime = $this->getMicrotime();
}
//结束时间
public function stop()
{
$this->stopTime = $this->getMicrotime();
}
//开始和结束之间总时长
public function spentTime()
{
return ($this->stopTime - $this->startTime);
}
private function getMicrotime()
{
list($usec, $sec) = explode(' ', microtime());
return ((float)$usec + (float)$sec);
}
}
ApiSign api签名认证
namespace App\Http\Middleware;
use Closure;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;
class ApiSign
{
private $rule = [
'api/test' => [
'keyId' => 'required|numeric|max:999999',
'sign' => 'required|max:32',
],
'api/accountInfo' => [
'keyId' => 'required|numeric|max:999999',
'sign' => 'required|max:32',
],
'api/submitOrder' => [
'keyId' => 'required|numeric|max:999999',
'sign' => 'required|max:32',
'orderJson' => 'required|json',
'updateJson' => '',
],
];
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//1.参数的验证
$routeName = $request->path();
if (!empty($this->rule[$routeName]))
{
$result = Validator::make($request->all(), $this->rule[$routeName]);
if ($result->fails())
{
return response()->json([
'message' => '不合法的请求参数',
//'errors' => $result->errors(),
'code' => '40001',
'data' => []
]);
}
}
//2.数据库验证
//获取用户key_screct
$authsiteInfo = DB::connection("mysql_shop")->table('authsite')->where('key_id', $request->input("keyId"))
->where('status', 1)->first();
if (empty($authsiteInfo))
{
return response()->json([
'message' => '不合法的请求参数: keyId非法',
'code' => '40002',
'data' => []
]);
}
//3.验证授权ip
if ($authsiteInfo->ip !='' && $authsiteInfo->ip != $request->ip())
{
return response()->json([
'message' => '不合法的请求参数: ip未授权',
'code' => '40005',
'data' => []
]);
}
//4.验证签名
$screctVal = $authsiteInfo->key_secret;
$requestArr = $request->input();
unset($requestArr['sign']);
//var_dump($this->getSign($requestArr, $screctVal));
if ($request->input("sign") != $this->getSign($requestArr, $screctVal))
{
return response()->json([
'message' => '不合法的请求参数: 签名sign错误',
'code' => '40003',
'data' => []
]);
}
return $next($request);
}
/**
* 获取sign
*/
private function getSign($tempArr, $randStr = '')
{
ksort($tempArr);
$signStr = "";
foreach ($tempArr as $key => $val)
{
$signStr .= $key . "=" . $val . "&";
}
$signStr = trim($signStr, "&");
return md5($signStr . $randStr);
}
}
DemoController 接口逻辑类
<?php
/**
* Created by PhpStorm.
* User:
* Date: 2019/10/22
* Time: 15:17
*/
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Observers\ApiLogObserver;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
/**
* @group 生产系统接口
*
* 接口为第三商城提供api接口,通过api接口可以提交绿爱生产系统!
*/
class DemoController extends Controller
{
protected $apiLogObserver;
protected $dbShop;
private $result = [
'code' => 0,
'message' => "",
'data' => []
];
//通过验证后开始提交标识
private $get_ins_id = 0;
public function __construct(ApiLogObserver $apiLogObserver)
{
$this->apiLogObserver = $apiLogObserver;
$this->apiLogObserver->start();
//商城数据库
$this->dbShop = DB::connection("mysql_shop");
}
/**
*
* 测试接口是否可用
*
* @bodyParam keyId string required 用户的appkey.
* @bodyParam sign string required 用户的签名.
*
* @authenticated
*
* @response {
* "code": 0,
* "massage": "测试可以正常使用",
* "data": []
* }
*/
public function test()
{
$this->result['massage'] = "测试可以正常使用";
return response()->json($this->result);
}
/**
*
* 查询用户平台的账户信息
*
* @bodyParam keyId string required 用户的appkey.
* @bodyParam sign string required 用户的签名.
*
* @authenticated
*
* @response {
* "code": 0,
* "massage": "查询成功",
* "data": ['balance']
* }
*/
public function getAccountInfo(Request $request)
{
// 验证
$keyId = $request->input('keyId');
$authsiteInfo = $this->dbShop->table('authsite')->select("balance")->where('status', 1)->where('key_id', $keyId)->first();
if (empty($authsiteInfo))
{
$this->result['code'] = "40002";
$this->result['message'] = "不合法的请求参数: key_id非法";
return $this->returnRespone();
}
//数据返回
$this->result['data']['balance'] = $authsiteInfo->balance;
$this->result['message'] = "查询成功";
return $this->returnRespone();
}
// 返回信息
private function returnRespone()
{
$this->apiLogObserver->stop();
return response()->json($this->result);
}
}
快速构建第三方api应用的更多相关文章
- 基于Go语言快速构建RESTful API服务
In this post, we will not only cover how to use Go to create a RESTful JSON API, but we will also ta ...
- Mysql EF Core 快速构建 Web Api
(1)首先创建一个.net core web api web项目; (2)因为我们使用的是ef连接mysql数据库,通过NuGet安装MySql.Data.EntityFrameworkCore,以来 ...
- 通过 SCF Component 轻松构建 REST API,再也不用熬夜加班了
本教程将分享如何通过 Serverless SCF Component .云函数 SCF 及 API 网关组件,快速构建一个 REST API 并实现 GET/PUT 操作. 当一个应用需要对第三方提 ...
- SpringBoot 快速构建微服务体系 知识点总结
可以通过http://start.spring.io/构建一个SpringBoot的脚手架项目 一.微服务 1.SpringBoot是一个可使用Java构建微服务的微框架. 2.微服务就是要倡导大家尽 ...
- 快速构建Windows 8风格应用12-SearchContract概述及原理
原文:快速构建Windows 8风格应用12-SearchContract概述及原理 本篇博文主要介绍Search Contract概述.Search Contract面板结构剖析.Search Co ...
- 快速构建Windows 8风格应用33-构建锁屏提醒
原文:快速构建Windows 8风格应用33-构建锁屏提醒 引言 Windows Phone(8&7.5)和Windows 8引入了锁屏概念,其实做过Windows Phone 7.5应用开发 ...
- 使用Vue.js和Axios从第三方API获取数据 — SitePoint
更多的往往不是,建立你的JavaScript应用程序时,你会想把数据从远程源或消耗一个[ API ](https:/ /恩.维基百科.org /维基/ application_programming_ ...
- 用 Flask 来写个轻博客 (36) — 使用 Flask-RESTful 来构建 RESTful API 之五
目录 目录 前文列表 PUT 请求 DELETE 请求 测试 对一条已经存在的 posts 记录进行 update 操作 删除一条记录 前文列表 用 Flask 来写个轻博客 (1) - 创建项目 用 ...
- 用 Flask 来写个轻博客 (35) — 使用 Flask-RESTful 来构建 RESTful API 之四
Blog 项目源码:https://github.com/JmilkFan/JmilkFan-s-Blog 目录 目录 前文列表 POST 请求 身份认证 测试 前文列表 用 Flask 来写个轻博客 ...
随机推荐
- FreeSql取多表数据
该篇内容由个人博客点击跳转同步更新!转载请注明出处! 以文章随笔与分类为例. 表结构 部分字段如下,其他省略,为了展示一对多关联,一个分类下可以有多个文章.一个文章属于一个分类. blog_artic ...
- ubuntu-wine
sudo dpkg --add-architecture i386 sudo add-apt-repository ppa:wine/wine-buildssudo apt-get update su ...
- goasp-onvif实现nvr server问题点滴
参考了:https://blog.csdn.net/saloon_yuan/article/details/24901597,本文以原贴为基础做了一些修改,非常感谢原作者. 1:开发框架搭建 ...
- 使用Sklearn-train_test_split 划分数据集
使用sklearn.model_selection.train_test_split可以在数据集上随机划分出一定比例的训练集和测试集 1.使用形式为: from sklearn.model_selec ...
- vue(axios)封装,content-type由application/json转换为application/x-www-form-urlencoded
现在主流的http请求头的content-type有三种(不讨论xml): application/x-www-form-urlencoded 最常见的提交数据方式,与原生form表单数据一致,在c ...
- eclipse中如何配置tomcat
1.打开eclipse上面的Windows选项,选择Preferences==>Server==>Runtime Environments==>Add 2.选择你电脑中安装的tomc ...
- C# 为什么说事件是一种特殊的委托
很多人说C#的事件是一种特殊的委托,其实并不是,这是对事件的一种误解 C# 事件模型的五个组成部分 1.事件的拥有者 2.事件成员(事件的本身) 3.事件响应者 4.事件处理器:本质上是一种回调方法 ...
- Java程序运行原理
概念介绍: ![file](https://img2018.cnblogs.com/blog/1454321/202001/1454321-20200104145655999-149562495.jp ...
- Linux学习之路--常用命令讲解
Linux常用命令讲解 1.命令格式:命令 [-选项] [参数] 超级用户的提示符是# 一般用户的提示符是$ 如:ls -la /usr说明: 大部分命令遵从该格式多个选项时,可以一起写 eg:ls ...
- Python 任务自动化工具 tox 教程
在我刚翻译完的 Python 打包系列文章中,作者提到了一个神奇的测试工具 tox,而且他本人就是 tox 的维护者之一.趁着话题的相关性,本文将对它做简单的介绍,说不定大家在开发项目时能够用得上. ...