You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
wastesortingserver/baidu/BaiduAiRequest.php

89 lines
3.3 KiB

<?php
require_once $_SERVER["DOCUMENT_ROOT"] . "/entity/ApiToken.php";
require_once $_SERVER["DOCUMENT_ROOT"] . "/database/DbUtil.php";
//api请求
class BaiduAiRequest
{
private static $client_id = "keaVPslHREMgVd6FwiEQqcCx";
private static $client_secret = "vtsDKjRVbcALDc61GAflw8UAtmGYkIPX";
private $url;
/**
* BaiduAiRequest constructor.
* @param $url
*/
public function __construct($url)
{
$this->url = $url;
}
function request_token()
{
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);
if (array_key_exists("error", $json_res)) {
throw new Exception("请求异常");
} 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;
}
} catch (Exception $e) {
$GLOBALS["default_log"]->error($e);
return <<<EOF
{"msg":"百度API请求失败,请联系管理员"}
EOF;
}
}
// 发送请求
function request_with_param($param)
{
try {
$o = "";
foreach ($param as $k => $v) {
$o .= "$k=" . urlencode($v) . "&";
}
$param = substr($o, 0, -1);
if (empty($this->url) || empty($param)) {
return false;
}
$curlPost = $param;
$curl = curl_init($this->url);//初始化curl
curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
$data = curl_exec($curl);//运行curl
curl_close($curl);
$json_res = json_decode($data, true, 512, JSON_UNESCAPED_UNICODE);
info("接口响应结果:" . $data);
return $json_res;
} catch (Exception $e) {
error($e);
return <<<EOF
{"msg":"百度API请求失败,请联系管理员"}
EOF;
}
}
}