百度AK/SK配置

test
橙橙楊 5 years ago committed by luffy
parent 5b2e678b68
commit c4735215d5
  1. 109
      admin/ApiConfig.php
  2. 8
      admin/Login.php
  3. 3
      admin/WasteSorting.php
  4. 26
      api/BaiduImage.php
  5. 91
      baidu/BaiduAiRequest.php
  6. 31
      database/Query.php
  7. 48
      entity/Param.php
  8. 2
      index.php
  9. 9
      script/db.sql
  10. 8
      test.php

@ -0,0 +1,109 @@
<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/head.php";
getMenu("百度AK/SK配置");
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/Query.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/Log.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/admin/Alert.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/baidu/BaiduAiRequest.php";
if (empty($_REQUEST) or !empty($_GET["check"])) {
$result = BaiduAiRequest::get_token_config();
if (!empty($result)) {
$api_key = $result["api_key"];
$secret_key = $result["secret_key"];
}
echo <<<EOF
<!DOCTYPE html>
<html lang="zh">
<script>
$(function() {
$('[data-toggle="tooltip"]').tooltip();
Array.prototype.filter.call($("form.needs-validation"), function(form) {
form.addEventListener('submit', function(event) {
if (form.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
}, false);
});
});
function doSubmit(action) {
$("form").attr("action",action).submit()
}
</script>
<body>
<div class="container py-5">
<div class="list-group d-flex justify-content-center align-items-center w-100">
<form class="col-6 needs-validation" novalidate method="post">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">API Key</span>
</div>
<input type="text" class="form-control" placeholder="API Key" name="api_key" value="$api_key" required>
<div class="invalid-feedback">
API Key不能为空
</div>
</div>
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text">API Key</span>
</div>
<input type="text" class="form-control" placeholder="API Key" name="secret_key" value="$secret_key" required>
<div class="invalid-feedback">
Secret Key不能为空
</div>
</div>
<div class="col-6 m-auto">
EOF;
if (isset($_GET["check"]) and $_GET["check"] == "true") {
echo '<button class="btn btn-success btn-block" onclick="doSubmit(\'' . $_SERVER["PHP_SELF"] . '?action=update\')">保存</button>';
} else {
echo '<button class="btn btn-warning btn-block" onclick="doSubmit(\'' . $_SERVER["PHP_SELF"] . '?action=test\')">测试</button>';
}
echo <<<EOF
<a class="btn btn-dark btn-block" href="/">返回</a>
</div>
</form>
</div>
</div>
</body>
</html>
EOF;
} else if (!empty($_GET["action"])) {
if (empty($_POST["api_key"])) {
error_res("API Key不能为空", $_SERVER["PHP_SELF"]);
} else if (empty($_POST["secret_key"])) {
error_res("Secret Key不能为空", $_SERVER["PHP_SELF"]);
} else if ($_GET["action"] == "test") {
$api_key = $_POST["api_key"];
$secret_key = $_POST["secret_key"];
$result = BaiduAiRequest::request_token_with_config($api_key, $secret_key);
if (array_key_exists("status", $result) and $result["status"]) {
info_res("AK/SK测试通过", $_SERVER["PHP_SELF"] . "?check=true");
} else {
warn_res("AK/SK测试失败", $_SERVER["PHP_SELF"] . "?check=false");
}
} else if ($_GET["action"] == "update") {
try {
DbUtil::update("update param set param_value=? where param_key=?", "ss", $_POST["api_key"], "api_key");
DbUtil::update("update param set param_value=? where param_key=?", "ss", $_POST["secret_key"], "secret_key");
info_res("保存成功", $_SERVER["PHP_SELF"]);
} catch (Exception $e) {
error($e);
error_res("保存异常请联系管理员", $_SERVER["PHP_SELF"]);
}
} else {
error_res("非法操作!", $_SERVER["PHP_SELF"]);
}
} else {
error_res("非法操作!", $_SERVER["PHP_SELF"]);
}

@ -24,8 +24,10 @@ function update_token(QueryManager $manager_result, $msg)
info_res($msg, "/",); info_res($msg, "/",);
echo <<<EOF echo <<<EOF
<script> <script>
<!--3秒后自动跳转--> <!--3;秒后自动跳转;-->
let count=3 $(function() {
let count=3;
$("#tip").text(count+"秒后自动跳转");
let i=setInterval(function() { let i=setInterval(function() {
if(count-->0){ if(count-->0){
$("#tip").text(count+"秒后自动跳转"); $("#tip").text(count+"秒后自动跳转");
@ -34,6 +36,8 @@ let i=setInterval(function() {
} }
console.info("定时器!!!!!") console.info("定时器!!!!!")
},1000) },1000)
})
</script> </script>
<div class="alert alert-info alert-dismissible fade show col-5 m-auto text-center" role="alert"> <div class="alert alert-info alert-dismissible fade show col-5 m-auto text-center" role="alert">

@ -27,9 +27,6 @@ $(function() {
}, false); }, false);
}); });
}); });
function doList() {
console.info("查看垃圾数据")
}
</script> </script>
<body> <body>
<ul class="nav nav-pills nav-justified"> <ul class="nav nav-pills nav-justified">

@ -53,35 +53,31 @@ DbUtil::query("select * from api_token limit 0,1", $token_result);
// toekn如果失效,则更新token // toekn如果失效,则更新token
if (strtotime(date(default_format)) >= strtotime($token_result->getToken()->getEndTime())) { if (strtotime(date(default_format)) >= strtotime($token_result->getToken()->getEndTime())) {
info("token失效了,更新token"); info("token失效了,更新token");
$updateToken = new BaiduAiRequest("https://aip.baidubce.com/oauth/2.0/token"); $result = BaiduAiRequest::request_token();
$updateToken->request_token(); if (array_key_exists("status", $result) and $result["status"]) {
DbUtil::query("select * from api_token limit 0,1", $token_result); DbUtil::query("select * from api_token limit 0,1", $token_result);
} else {
json_res(json_encode(array("img_parse" => false, "msg" => "无法调用百度API,请联系管理员")));
return;
}
} }
//获取图片参数 //获取图片参数
if (isset($_POST["image"])) { if (isset($_POST["image"])) {
// 请求通用物体和场景识别高级版接口 // 请求通用物体和场景识别高级版接口
$image_req = new BaiduAiRequest("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general");
// 获取解析结果 // 获取解析结果
$image_res = $image_req->request_with_param(array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $_POST["image"])); $image_res = BaiduAiRequest::request_with_param("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general", array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $_POST["image"]));
query_waste_soring($image_res); query_waste_soring($image_res);
} else if ($_FILES["file"]["error"] > 0) { } else if ($_FILES["file"]["error"] > 0) {
json_res(<<<EOF json_res(json_encode(array("img_parse" => false, "msg" => "照片上传失败")));
{"msg":"文件上传失败"}
EOF
);
} else if ($_FILES["file"]["error"] == 0) { } else if ($_FILES["file"]["error"] == 0) {
// base64加密文件二进制数据 // base64加密文件二进制数据
$image = base64_encode(file_get_contents($_FILES["file"]["tmp_name"])); $image = base64_encode(file_get_contents($_FILES["file"]["tmp_name"]));
// 请求通用物体和场景识别高级版接口 // 请求通用物体和场景识别高级版接口
$image_req = new BaiduAiRequest("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general");
// 获取解析结果 // 获取解析结果
$image_res = $image_req->request_with_param(array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $image)); $image_res = BaiduAiRequest::request_with_param("https://aip.baidubce.com/rest/2.0/image-classify/v2/advanced_general", array("access_token" => $token_result->getToken()->getAccessToken(), "image" => $image));
query_waste_soring($image_res); query_waste_soring($image_res);
} else { } else {
json_res(<<<EOF json_res(json_encode(array("img_parse" => false, "msg" => "缺少图片参数")));
{"msg":"缺少图片参数"}
EOF
);
} }

@ -7,51 +7,78 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
//api请求 //api请求
class BaiduAiRequest class BaiduAiRequest
{ {
private static $client_id = "keaVPslHREMgVd6FwiEQqcCx";
private static $client_secret = "vtsDKjRVbcALDc61GAflw8UAtmGYkIPX";
private $url;
/** public static function get_token_config()
* BaiduAiRequest constructor.
* @param $url
*/
public function __construct($url)
{ {
$this->url = $url; $config_query = new QueryParam();
DbUtil::query("select * from param where param_key in('api_key','secret_key')", $config_query);
if (!empty($config_query->getParamList())) {
$config_result = $config_query->getParamList();
if (array_key_exists("api_key", $config_result) && array_key_exists("secret_key", $config_result)) {
if ($config_result["api_key"] instanceof Param and $config_result["secret_key"] instanceof Param
and !empty($config_result["api_key"]->getParamValue()) and !empty($config_result["secret_key"]->getParamValue())) {
return array("api_key" => $config_result["api_key"]->getParamValue(), "secret_key" => $config_result["secret_key"]->getParamValue());
}
}
}
return null;
}
public static function request_token()
{
$config_result = self::get_token_config();
if (empty($config_result)) {
error("初始化配置失败,请联系管理员");
// return <<<EOF
// {"msg":"初始化配置失败,请联系管理员"}
// EOF;
return array("msg" => "初始化配置失败,请联系管理员", "status" => false);
} else {
return self::request_token_with_config($config_result["api_key"], $config_result["secret_key"]);
}
} }
function request_token() public static function request_token_with_config($apikey, $secret_key)
{ {
try { try {
if (empty(self::$client_id) or empty(self::$client_secret)) {
throw new Exception("");
}
$post_data['grant_type'] = 'client_credentials';
$post_data['client_id'] = self::$client_id;
$post_data['client_secret'] = self::$client_secret;
$json_res = $this->request_with_param($post_data); $config_result = self::get_token_config();
if (array_key_exists("error", $json_res)) { if (empty($config_result)) {
throw new Exception("请求异常"); error("初始化配置失败,请联系管理员");
// return <<<EOF
// {"msg":"初始化配置失败,请联系管理员"}
// EOF;
return array("msg" => "初始化配置失败,请联系管理员", "status" => false);
} else { } else {
DbUtil::delete("delete from api_token"); $post_data['grant_type'] = 'client_credentials';
$token = new ApiToken(null, $json_res["refresh_token"], $json_res["expires_in"], null, $json_res["scope"], $json_res["session_key"], $json_res["access_token"], $json_res["session_secret"]); $post_data['client_id'] = $apikey;
DbUtil::insert("insert into api_token (refresh_token, expires_in, end_time, scope, session_key, access_token, session_secret) values (?,?,?,?,?,?,?)", $post_data['client_secret'] = $secret_key;
$types = "sisssss", $token->getRefreshToken(), $token->getExpiresIn(), date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($token->getExpiresIn() . " seconds")), default_format), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
info("token保存成功"); $json_res = self::request_with_param("https://aip.baidubce.com/oauth/2.0/token", $post_data);
return $token; if (array_key_exists("error", $json_res)) {
return array("msg" => "百度API请求失败,请联系管理员", "status" => false, "res" => $json_res);
} else {
DbUtil::delete("delete from api_token");
$token = new ApiToken(null, $json_res["refresh_token"], $json_res["expires_in"], null, $json_res["scope"], $json_res["session_key"], $json_res["access_token"], $json_res["session_secret"]);
DbUtil::insert("insert into api_token (refresh_token, expires_in, end_time, scope, session_key, access_token, session_secret) values (?,?,?,?,?,?,?)",
$types = "sisssss", $token->getRefreshToken(), $token->getExpiresIn(), date_format(date_create(date(default_format))->add(date_interval_create_from_date_string($token->getExpiresIn() . " seconds")), default_format), $token->getScope(), $token->getSessionKey(), $token->getAccessToken(), $token->getSessionSecret());
info("token保存成功");
// return $token;
return array("msg" => "百度API请求成功", "status" => true, "token" => $token);
}
} }
} catch (Exception $e) { } catch (Exception $e) {
$GLOBALS["default_log"]->error($e); error($e);
return <<<EOF // return <<<EOF
{"msg":"百度API请求失败,请联系管理员"} // {"msg":"百度API请求失败,请联系管理员"}
EOF; // EOF;
return array("msg" => "百度API请求失败,请联系管理员", "status" => false);
} }
} }
// 发送请求 // 发送请求
function request_with_param($param) public static function request_with_param($url, $param)
{ {
try { try {
@ -60,11 +87,11 @@ class BaiduAiRequest
$o .= "$k=" . urlencode($v) . "&"; $o .= "$k=" . urlencode($v) . "&";
} }
$param = substr($o, 0, -1); $param = substr($o, 0, -1);
if (empty($this->url) || empty($param)) { if (empty($url) || empty($param)) {
return false; return false;
} }
$curlPost = $param; $curlPost = $param;
$curl = curl_init($this->url);//初始化curl $curl = curl_init($url);//初始化curl
curl_setopt($curl, CURLOPT_HEADER, 0);//设置header curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);//post提交方式 curl_setopt($curl, CURLOPT_POST, 1);//post提交方式

@ -5,6 +5,7 @@ require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Garbage.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Question.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Question.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Answer.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Answer.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Manager.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Manager.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Param.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
//Token查询 //Token查询
abstract class AbstractTokenQuery implements DoExcute abstract class AbstractTokenQuery implements DoExcute
@ -305,3 +306,33 @@ class QueryManager implements DoExcute
} }
//查询系统参数
class QueryParam implements DoExcute
{
private $param_list = array();
public function bind_param(mysqli_stmt $stmt, array $param = null)
{
if (!empty($param)) {
$stmt->bind_param("sss", $param[0], ...array_slice($param, 1));
}
}
public function doResult(mysqli_stmt $stmt)
{
$stmt->bind_result($col1, $col2, $col3);
while ($stmt->fetch()) {
$this->param_list[$col1] = new Param($col1, $col2, $col3);
}
}
/**
* @return array
*/
public function getParamList(): array
{
return $this->param_list;
}
}

@ -0,0 +1,48 @@
<?php
class Param
{
private $param_key;
private $param_value;
private $param_desc;
/**
* Param constructor.
* @param $param_key
* @param $param_value
* @param $param_desc
*/
public function __construct($param_key, $param_value, $param_desc)
{
$this->param_key = $param_key;
$this->param_value = $param_value;
$this->param_desc = $param_desc;
}
/**
* @return mixed
*/
public function getParamKey()
{
return $this->param_key;
}
/**
* @return mixed
*/
public function getParamValue()
{
return $this->param_value;
}
/**
* @return mixed
*/
public function getParamDesc()
{
return $this->param_desc;
}
}

@ -16,7 +16,7 @@ if (!check_login()) {
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Menu.php"; require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/Menu.php";
//菜单信息 //菜单信息
$menus = array("API" => new Menu("百度API配置", "/admin/ApiConfig.php"), new Menu("垃圾分类", "/admin/WasteSorting.php"), new Menu("题目管理", "/admin/Question.php")); $menus = array("API" => new Menu("百度AK/SK配置", "/admin/ApiConfig.php"), new Menu("垃圾分类", "/admin/WasteSorting.php"), new Menu("题目管理", "/admin/Question.php"));

@ -33,7 +33,7 @@ create table param
# 参数名 # 参数名
param_key varchar(16) primary key, param_key varchar(16) primary key,
# 参数值 # 参数值
param_value varchar(16), param_value varchar(128),
# 参数描述 # 参数描述
param_desc varchar(32) param_desc varchar(32)
); );
@ -76,4 +76,9 @@ create table manager
# 超级管理员账号 # 超级管理员账号
insert manager (manager_name, manager_pwd) insert manager (manager_name, manager_pwd)
values ('admin', md5('admin')); values ('admin', md5('admin'));
# 初始化参数
insert param
values ('api_key', null, null),
('secret_key', null, null);

@ -24,8 +24,8 @@
//EOF; //EOF;
//var_dump(array_search(new Answer(1, 2, 3, 4), array(new Answer(4, 5, 6, 7), new Answer(2, 2, 3, 4)))); //var_dump(array_search(new Answer(1, 2, 3, 4), array(new Answer(4, 5, 6, 7), new Answer(2, 2, 3, 4))));
$s1 = "dotcoo world!"; //$s1 = "dotcoo world!";
$s2 = "dotcoo"; //$s2 = "dotcoo";
$s3 = "hello dotcoo"; //$s3 = "hello dotcoo";
var_dump(substr($s1, -strlen($s2)) === $s2); //var_dump(substr($s1, -strlen($s2)) === $s2);

Loading…
Cancel
Save