AipBase.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. <?php
  2. /*
  3. * Copyright (c) 2017 Baidu.com, Inc. All Rights Reserved
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License"); you may not
  6. * use this file except in compliance with the License. You may obtain a copy of
  7. * the License at
  8. *
  9. * Http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. * License for the specific language governing permissions and limitations under
  15. * the License.
  16. */
  17. require_once 'AipHttpClient.php';
  18. require_once 'AipBCEUtil.php';
  19. /**
  20. * Aip Base 基类
  21. */
  22. class AipBase {
  23. /**
  24. * 获取access token url
  25. * @var string
  26. */
  27. protected $accessTokenUrl = 'https://aip.baidubce.com/oauth/2.0/token';
  28. /**
  29. * 反馈接口
  30. * @var string
  31. */
  32. protected $reportUrl = 'https://aip.baidubce.com/rpc/2.0/feedback/v1/report';
  33. /**
  34. * appId
  35. * @var string
  36. */
  37. protected $appId = '';
  38. /**
  39. * apiKey
  40. * @var string
  41. */
  42. protected $apiKey = '';
  43. /**
  44. * secretKey
  45. * @var string
  46. */
  47. protected $secretKey = '';
  48. /**
  49. * 权限
  50. * @var array
  51. */
  52. protected $scope = 'brain_all_scope';
  53. /**
  54. * @param string $appId
  55. * @param string $apiKey
  56. * @param string $secretKey
  57. */
  58. public function __construct($appId, $apiKey, $secretKey){
  59. $this->appId = trim($appId);
  60. $this->apiKey = trim($apiKey);
  61. $this->secretKey = trim($secretKey);
  62. $this->isCloudUser = null;
  63. $this->client = new AipHttpClient();
  64. $this->version = '2_2_4';
  65. $this->proxies = array();
  66. }
  67. /**
  68. * 查看版本
  69. * @return string
  70. *
  71. */
  72. public function getVersion(){
  73. return $this->version;
  74. }
  75. /**
  76. * 连接超时
  77. * @param int $ms 毫秒
  78. */
  79. public function setConnectionTimeoutInMillis($ms){
  80. $this->client->setConnectionTimeoutInMillis($ms);
  81. }
  82. /**
  83. * 响应超时
  84. * @param int $ms 毫秒
  85. */
  86. public function setSocketTimeoutInMillis($ms){
  87. $this->client->setSocketTimeoutInMillis($ms);
  88. }
  89. /**
  90. * 代理
  91. * @param array $proxy
  92. * @return string
  93. *
  94. */
  95. public function setProxies($proxies){
  96. $this->client->setConf($proxies);
  97. }
  98. /**
  99. * 处理请求参数
  100. * @param string $url
  101. * @param array $params
  102. * @param array $data
  103. * @param array $headers
  104. */
  105. protected function proccessRequest($url, &$params, &$data, $headers){
  106. $params['aipSdk'] = 'php';
  107. $params['aipSdkVersion'] = $this->version;
  108. }
  109. /**
  110. * Api 请求
  111. * @param string $url
  112. * @param mixed $data
  113. * @return mixed
  114. */
  115. protected function request($url, $data, $headers=array()){
  116. try{
  117. $result = $this->validate($url, $data);
  118. if($result !== true){
  119. return $result;
  120. }
  121. $params = array();
  122. $authObj = $this->auth();
  123. if($this->isCloudUser === false){
  124. $params['access_token'] = $authObj['access_token'];
  125. }
  126. // 特殊处理
  127. $this->proccessRequest($url, $params, $data, $headers);
  128. $headers = $this->getAuthHeaders('POST', $url, $params, $headers);
  129. $response = $this->client->post($url, $data, $params, $headers);
  130. // var_dump($response);die;
  131. $obj = $this->proccessResult($response['content']);
  132. //
  133. if(!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110){
  134. echo $obj['error_code'];die;
  135. $authObj = $this->auth(true);
  136. $params['access_token'] = $authObj['access_token'];
  137. $response = $this->client->post($url, $data, $params, $headers);
  138. $obj = $this->proccessResult($response['content']);
  139. }
  140. if(empty($obj) || !isset($obj['error_code'])){
  141. $this->writeAuthObj($authObj);
  142. }
  143. // echo 678;die;
  144. }catch(Exception $e){
  145. return array(
  146. 'error_code' => 'SDK108',
  147. 'error_msg' => 'connection or read data timeout',
  148. );
  149. }
  150. return $obj;
  151. }
  152. /**
  153. * Api 多个并发请求
  154. * @param string $url
  155. * @param mixed $data
  156. * @return mixed
  157. */
  158. protected function multi_request($url, $data){
  159. try{
  160. $params = array();
  161. $authObj = $this->auth();
  162. $headers = $this->getAuthHeaders('POST', $url);
  163. if($this->isCloudUser === false){
  164. $params['access_token'] = $authObj['access_token'];
  165. }
  166. $responses = $this->client->multi_post($url, $data, $params, $headers);
  167. $is_success = false;
  168. foreach($responses as $response){
  169. $obj = $this->proccessResult($response['content']);
  170. if(empty($obj) || !isset($obj['error_code'])){
  171. $is_success = true;
  172. }
  173. if(!$this->isCloudUser && isset($obj['error_code']) && $obj['error_code'] == 110){
  174. $authObj = $this->auth(true);
  175. $params['access_token'] = $authObj['access_token'];
  176. $responses = $this->client->post($url, $data, $params, $headers);
  177. break;
  178. }
  179. }
  180. if($is_success){
  181. $this->writeAuthObj($authObj);
  182. }
  183. $objs = array();
  184. foreach($responses as $response){
  185. $objs[] = $this->proccessResult($response['content']);
  186. }
  187. }catch(Exception $e){
  188. return array(
  189. 'error_code' => 'SDK108',
  190. 'error_msg' => 'connection or read data timeout',
  191. );
  192. }
  193. return $objs;
  194. }
  195. /**
  196. * 格式检查
  197. * @param string $url
  198. * @param array $data
  199. * @return mix
  200. */
  201. protected function validate($url, &$data){
  202. return true;
  203. }
  204. /**
  205. * 格式化结果
  206. * @param $content string
  207. * @return mixed
  208. */
  209. protected function proccessResult($content){
  210. return json_decode($content, true);
  211. }
  212. /**
  213. * 返回 access token 路径
  214. * @return string
  215. */
  216. private function getAuthFilePath(){
  217. return dirname(__FILE__) . DIRECTORY_SEPARATOR . md5($this->apiKey);
  218. }
  219. /**
  220. * 写入本地文件
  221. * @param array $obj
  222. * @return void
  223. */
  224. private function writeAuthObj($obj){
  225. if($obj === null || (isset($obj['is_read']) && $obj['is_read'] === true)){
  226. return;
  227. }
  228. $obj['time'] = time();
  229. $obj['is_cloud_user'] = $this->isCloudUser;
  230. @file_put_contents($this->getAuthFilePath(), json_encode($obj));
  231. }
  232. /**
  233. * 读取本地缓存
  234. * @return array
  235. */
  236. private function readAuthObj(){
  237. $content = @file_get_contents($this->getAuthFilePath());
  238. if($content !== false){
  239. $obj = json_decode($content, true);
  240. $this->isCloudUser = $obj['is_cloud_user'];
  241. $obj['is_read'] = true;
  242. if($this->isCloudUser || $obj['time'] + $obj['expires_in'] - 30 > time()){
  243. return $obj;
  244. }
  245. }
  246. return null;
  247. }
  248. /**
  249. * 认证
  250. * @param bool $refresh 是否刷新
  251. * @return array
  252. */
  253. private function auth($refresh=false){
  254. //非过期刷新
  255. if(!$refresh){
  256. $obj = $this->readAuthObj();
  257. if(!empty($obj)){
  258. return $obj;
  259. }
  260. }
  261. $response = $this->client->get($this->accessTokenUrl, array(
  262. 'grant_type' => 'client_credentials',
  263. 'client_id' => $this->apiKey,
  264. 'client_secret' => $this->secretKey,
  265. ));
  266. $obj = json_decode($response['content'], true);
  267. $this->isCloudUser = !$this->isPermission($obj);
  268. return $obj;
  269. }
  270. /**
  271. * 判断认证是否有权限
  272. * @param array $authObj
  273. * @return boolean
  274. */
  275. protected function isPermission($authObj)
  276. {
  277. if(empty($authObj) || !isset($authObj['scope'])){
  278. return false;
  279. }
  280. $scopes = explode(' ', $authObj['scope']);
  281. return in_array($this->scope, $scopes);
  282. }
  283. /**
  284. * @param string $method HTTP method
  285. * @param string $url
  286. * @param array $param 参数
  287. * @return array
  288. */
  289. private function getAuthHeaders($method, $url, $params=array(), $headers=array()){
  290. //不是云的老用户则不用在header中签名 认证
  291. if($this->isCloudUser === false){
  292. return $headers;
  293. }
  294. $obj = parse_url($url);
  295. if(!empty($obj['query'])){
  296. foreach(explode('&', $obj['query']) as $kv){
  297. if(!empty($kv)){
  298. list($k, $v) = explode('=', $kv, 2);
  299. $params[$k] = $v;
  300. }
  301. }
  302. }
  303. //UTC 时间戳
  304. $timestamp = gmdate('Y-m-d\TH:i:s\Z');
  305. $headers['Host'] = isset($obj['port']) ? sprintf('%s:%s', $obj['host'], $obj['port']) : $obj['host'];
  306. $headers['x-bce-date'] = $timestamp;
  307. //签名
  308. $headers['authorization'] = AipSampleSigner::sign(array(
  309. 'ak' => $this->apiKey,
  310. 'sk' => $this->secretKey,
  311. ), $method, $obj['path'], $headers, $params, array(
  312. 'timestamp' => $timestamp,
  313. 'headersToSign' => array_keys($headers),
  314. ));
  315. return $headers;
  316. }
  317. /**
  318. * 反馈
  319. *
  320. * @param array $feedbacks
  321. * @return array
  322. */
  323. public function report($feedback){
  324. $data = array();
  325. $data['feedback'] = $feedback;
  326. return $this->request($this->reportUrl, $data);
  327. }
  328. /**
  329. * 通用接口
  330. * @param string $url
  331. * @param array $data
  332. * @param array header
  333. * @return array
  334. */
  335. public function post($url, $data, $headers=array()){
  336. return $this->request($url, $data, $headers);
  337. }
  338. }