AipBase.php 10 KB

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