ApiCenterClient.php 17.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
<?php
/**
+-----------------------------------------------------------------------------------------------------------------------
 * 工具类:百度相关api
+-----------------------------------------------------------------------------------------------------------------------
 * PHP version 7
 *
 * @category  App\Util\Baidu
 * @package   App\Util\Baidu
 * @author    Richer <yangzi1028@163.com>
 * @date      2022年7月19日09:36:06
 * @copyright 2021-2022 Richer (http://www.Richer.com/)
 * @license   http://www.Richer.com/ License
 * @link      http://www.Richer.com/
 */
namespace App\Util\Baidu;

include 'BaiduBce.phar';

use BaiduBce\Auth\BceV1Signer;
use BaiduBce\BceBaseClient;
use BaiduBce\Http\BceHttpClient;
use BaiduBce\Http\HttpHeaders;
use BaiduBce\Http\HttpMethod;
use BaiduBce\Http\HttpContentTypes;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Cache;
use DateTime;
use DateTimeZone;
use Illuminate\Support\Facades\Log;
use phpDocumentor\Reflection\DocBlock\Tags\TagWithType;
use PhpParser\Node\Stmt\TryCatch;

class ApiCenterClient extends BceBaseClient
{
    private $signer;
    private $httpClient;
    protected $api_key = 'UkB3fvjX8EqtVwmqVqVPW9T5';
    protected $secret_key = 'ekA2ZXhTaPst7yb9FFEvkb7wWPb3TCob';
    protected $path = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/address';
    protected $message = '';

    public function __construct()
    {
        $config = array(
            'credentials' => array(
                'ak' => $this->api_key,
                'sk' => $this->secret_key,
            ),
            'endpoint' => 'https://aip.baidubce.com',
        );
        parent::__construct($config, 'apiexplorer');
        $this->signer = new BceV1Signer();
        $this->httpClient = new BceHttpClient();
    }

    /**
     * @param $httpMethod
     * @param array $varArgs
     * @param $path
     * @return \stdClass
     * @throws \BaiduBce\Exception\BceClientException
     * @throws \BaiduBce\Exception\BceServiceException
     */
    private function sendRequest($httpMethod, array $varArgs, $path)
    {
        $defaultArgs = array(
            'config' => array(),
            'body' => null,
            'headers' => array(),
            'params' => array(),
        );

        $args = array_merge($defaultArgs, $varArgs);
        if (empty($args['config'])) {
            $config = $this->config;
        } else {
            $config = array_merge(
                array(),
                $this->config,
                $args['config']
            );
        }
        if (!isset($args['headers'][HttpHeaders::CONTENT_TYPE])) {
            $args['headers'][HttpHeaders::CONTENT_TYPE] = HttpContentTypes::JSON;
        }
        $response = $this->httpClient->sendRequest(
            $config,
            $httpMethod,
            $path,
            $args['body'],
            $args['headers'],
            $args['params'],
            $this->signer
        );

        $result = $this->parseJsonResult($response['body']);
        $result->metadata = $this->convertHttpHeadersToMetadata($response['headers']);
        return $result;
    }

    public function address($address, $options = array())
    {
        $token = $this->token();
       /* $header = $this->generateAccessKey();
        $post_data['text']   = $address;
        dump($header);

        $result = $this->clientRequest($this->path, 'POST', $header, $post_data);
        dump($result);
        if ($result === false) {
            $this->recordLog('doLoginThird end', true);
            return false;
        }
        $code = Arr::get($result, 'code');
        dd($code);*/

        $url = 'https://aip.baidubce.com/rpc/2.0/nlp/v1/address?charset=UTF-8&access_token='.$token;
        $headers['Content-Type'] = 'application/json;charset=UTF-8';
        $post_data['text']   = $address;
        $post_data  = json_encode($post_data);

//        $result ='{"lat":31.18573,"detail":"纳贤路701号百度上海研发中心F4A000","town":"张江镇","phonenum":"","city_code":"310100","province":"上海市","person":"张三","lng":121.612643,"province_code":"310000","text":"上海市浦东新区纳贤路701号百度上海研发中心 F4A000 张三","county":"浦东新区","city":"上海市","county_code":"310115","town_code":"310115125","log_id":1549234631556912507}';
//        dump($result);
        try {
            $result = $this->requestPost($url, $post_data);
            $response = json_decode($result, true);
    //        try {
    //            $result = $this->requestPost($url, $post_data);
    //            dump($result);
    //
    //            $response = json_decode($result, true);
    //
    //        } catch (\Exception $exception) {
    //            dd($exception->getMessage());
    //        }
    //        dd($response);

            $error_code = Arr::get($response, 'error_code');
            if ($error_code && $error_code !== 0) {
                $this->message =  Arr::get($response, 'error_msg');
                return false;
            }

            return $response;
        } catch (\Exception $exception) {
            $this->message =  $exception->getMessage();
            dd($exception->getMessage());

            return false;
        }
        dd($response);

        return Arr::get($response, 'error_msg');
        dd($response);

        list($config) = $this->parseOptions($options, 'config');

        $headers = array();
        $headers['Content-Type'] = 'application/json;charset=UTF-8';

        $params = array('access_token' => $token);

//        $body = "{\n    \"text\": \"上海市浦东新区纳贤路701号百度上海研发中心 F4A000 张三\"\n   \n}";

        $body['text'] = $address;
        $body = json_encode($body);

        return $this->sendRequest(
            HttpMethod::POST,
            array(
                'config' => $config,
                'params' => $params,
                'body' => $body,
                'headers' => $headers,
            ),
            '/rpc/2.0/nlp/v1/address'
        );
    }

    /**
     * 获取token
     *
     * @return array|\ArrayAccess|false|mixed
     */
    protected function token()
    {
        // 从缓存中获取请求的
        $cache_key = 'baidu_access_token';
        $access_token = Cache::get($cache_key);

        if (!$access_token) {
            $url = 'https://aip.baidubce.com/oauth/2.0/token';
            $post_data['grant_type']   = 'client_credentials';
            $post_data['client_id']      =  $this->api_key;
            $post_data['client_secret'] = $this->secret_key;
            $o = "";
            foreach ($post_data as $k => $v) {
                $o.= "$k=" . urlencode($v). "&" ;
            }
            $post_data = substr($o, 0, -1);

            $result = $this->requestPost($url, $post_data);

            $response = json_decode($result, true);
            $access_token = Arr::get($response, 'access_token');
            if (!$access_token) {
                $this->message = Arr::get($response, 'error');
                return false;
            }
            $expires_in = Arr::get($response, 'expires_in');

            Cache::put($cache_key, $access_token, $expires_in / 60);
        }
        return $access_token;
    }

    /**
     * @param string $url
     * @param string $param
     * @return bool|string
     */
    protected function requestPost($url = '', $param = '')
    {
        if (empty($url) || empty($param)) {
            return false;
        }

        $postUrl = $url;
        $curlPost = $param;
        $curl = curl_init();//初始化curl
        curl_setopt($curl, CURLOPT_URL, $postUrl);//抓取指定网页
        curl_setopt($curl, CURLOPT_HEADER, 0);//设置header
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
        curl_setopt($curl, CURLOPT_POST, 1);//post提交方式
        curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
        $data = curl_exec($curl);//运行curl
        curl_close($curl);

        return $data;
    }

    /**
     * @return string
     */
    public function getMessage()
    {
        return $this->message;
    }

    /**
     * 生成  Access Key
     *
     * API认证机制
     * 所有API的安全认证一律采用AccessKey与请求签名机制。 Access Key由AccessKey ID和Secret Access Key组成,均为字符串。 对于每个HTTP请求,使用下面所描述算法生成一个认证字符串。提交认证字符串放在Authorization头域里。服务端根据生成算法验证认证字符串的正确性。认证字符串的格式为
     * bce-auth-v{version}/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}/{signedHeaders}/{signature}。
     * version是正整数。
     * timestamp是生成签名时的UTC时间。
     * expirationPeriodInSeconds表示签名有效期限。
     * signedHeaders是签名算法中涉及到的头域列表。头域名之间用分号(;)分隔,如host;x-bce-date。列表按照字典序排列。(本API签名仅使用host和x-bce-date两个header)
     * signature是256位签名的十六进制表示,由64个小写字母组成。 当百度智能云接收到用户的请求后,系统将使用相同的SK和同样的认证机制生成认证字符串,并与用户请求中包含的认证字符串进行比对。如果认证字符串相同,系统认为用户拥有指定的操作权限,并执行相关操作;如果认证字符串不同,系统将忽略该操作并返回错误码。
     **
     * @return array|\ArrayAccess|false|mixed
     */
    public function generateAccessKey()
    {
//        $this->recordLog('generateAccessKey begin', true);

        $version = 1;
        $secretKey = $this->secret_key;
        $accessKey = $this->secret_key;
        // 签名的UTC时间,格式为yyyy-mm-ddThh:mm:ssZ
        $timestamp = $this->iso8601Time();//now()->toDateTimeString();
        // 签名有效期限,从timestamp所指定的时间开始计算,单位为秒。
        $expirationPeriodInSeconds = 1800;
        //bce-auth-v{version}/{accessKeyId}/{timestamp}/{expirationPeriodInSeconds}/{signedHeaders}/{signature}。
        // bce-auth-v1/f81d3b34e48048fbb2634dc7882d7e21/2022-04-18T04:17:29Z/3600/host/74c506f68c65e26c633bfa104c863fffac5190fdec1ec24b7c03eb5d67d2e1de

        // 一 :创建前缀字符串(authStringPrefix)
        $authStringPrefix = "bce-auth-v{$version}/$accessKey/$timestamp/$expirationPeriodInSeconds";
//        dump('authStringPrefix');dump($authStringPrefix);

        // 二: 创建规范请求(canonicalRequest),确定签名头域(signedHeaders)
        // 二.1 : HTTP Method 必须使用全大写的形式
        $httpMethod = strtoupper('POST');

        // 二.2 : CanonicalURI URL中的绝对路径进行编码后的结果,即CanonicalURI = UriEncodeExceptSlash(Path)。要求绝对路径Path必须以“/”开头,不以“/”开头的需要补充上,空路径为“/”
        $path = $this->path;
        $canonicalURI = $this->uriEncodeExceptSlash($path);

        // 二.3 : CanonicalQueryString 对于URL中的Query String(Query String即URL中“?”后面的“key1 = value1 & key2 = value2 ”字符串)进行编码后的结果。
        $query = '';
        parse_str($query, $params);
        $canonicalQueryString = $this->getCanonicalQueryString($params);

        // 二.4 : CanonicalHeaders 是对HTTP请求中的Header部分进行选择性编码的结果
        // 需要签名的 Header 字段
        $headers = array(
            'host' => '120.48.16.137',// Arr::first(explode(':', $this->host)), // 去掉端口
            'x-bce-date'=> $timestamp,
        );
        list($signedHeaders, $canonicalHeaders) = $this->getCanonicalHeaders($headers);

        // 三: 生成派生密钥(signingKey)
        $signingKey = hash_hmac('sha256', $authStringPrefix, $secretKey);
//        dump('signingKey:');dump($signingKey);

        // 四:生成签名摘要及认证字符串(authorization)
        // 四.1 : 生成 CanonicalRequest 公式 CanonicalRequest = HTTP Method + "\n" + CanonicalURI + "\n" + CanonicalQueryString + "\n" + CanonicalHeaders
        $arr = array($httpMethod,$canonicalURI,$canonicalQueryString,$canonicalHeaders);
        $canonicalRequest = implode("\n", $arr);
//        dump('canonicalRequest:');dump($canonicalRequest);
        // 四.2 : 生成Signature
        $signature = hash_hmac('sha256', $canonicalRequest, $signingKey);
//        dump('signature:');dump($signature);

        // 四.3 : 生成 Authorization
        $authorization = "bce-auth-v1/{$accessKey}/{$timestamp}/{$expirationPeriodInSeconds}/{$signedHeaders}/{$signature}";
//        dump($authorization);
        /* 必要的header */
        return array_merge(array(
            'Authorization'=> 'bce-auth-v1/7d7f5a6ca3eec87f8c71fc627b59df51/2022-07-08T04:06:13Z/1800/host;x-bce-date/a04ff59c5e620d02a3699bfe1b30dcf9bb6f7eca466c36cc41e0083fb9648c66',
        ), $headers);
    }
    /**
     * baidu bce sdk
     *
     * @param $path
     * @return string|string[]
     */
    protected function uriEncodeExceptSlash($path)
    {
        $str = $this->uriEncode($path);
        return str_replace('%2F', '/', $str);
    }


    /**
     * 取自 baidu bce sdk
     *
     * @param $arr
     * @return string
     */
    protected function getCanonicalQueryString($arr)
    {
        if (!$arr) {
            return '';
        }
        $data = array();
        foreach ($arr as $k => $v) {
            if ($k == 'authorization') {
                continue;
            }
            $data[] = sprintf("%s=%s", $this->uriEncode($k), $this->uriEncode($v));
        }
        krsort($data);
        return implode('&', $data);
    }

    /**
     * 取自 baidu bce sdk
     *
     * @param $arr
     * @return array|string
     */
    protected function getCanonicalHeaders($arr)
    {
        if (!$arr) {
            return '';
        }
        $data = array();
        $keys = array();
        foreach ($arr as $k => $v) {
            $k = strtolower($k);
            $v = trim($v);
            $keys[] = $k;
            $data[] = sprintf("%s:%s", $this->uriEncode($k), $this->uriEncode($v));
        }
        asort($data);
        asort($keys);
        return array(implode(";", $keys), implode("\n", $data));
    }

    /**
     * ISO8601规范时间 - 取自 baidu bce sdk
     *
     * @return string
     */
    protected function iso8601Time()
    {
//        return '2022-07-08T08:15:02Z';
        $now = new DateTime();
        $now->setTimezone(new DateTimeZone("UTC"));
        return $now->format("Y-m-d\TH:i:s\Z");

        return $nowInLondonTz =  Carbon::now('Europe/London');
    }

    /**
     * 取自 baidu bce sdk
     *
     * @param $value
     * @return string
     */
    protected function uriEncode($value)
    {
        static $PERCENT_ENCODED_STRINGS = null;
        if(null === $PERCENT_ENCODED_STRINGS){
            $PERCENT_ENCODED_STRINGS = array();
            for ($i = 0; $i < 256; ++$i) {
                $PERCENT_ENCODED_STRINGS[$i] = sprintf("%%%02X", $i);
            }
            foreach (range('a', 'z') as $ch) {
                $PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
            }

            foreach (range('A', 'Z') as $ch) {
                $PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
            }

            foreach (range('0', '9') as $ch) {
                $PERCENT_ENCODED_STRINGS[ord($ch)] = $ch;
            }
            $PERCENT_ENCODED_STRINGS[ord('-')] = '-';
            $PERCENT_ENCODED_STRINGS[ord('.')] = '.';
            $PERCENT_ENCODED_STRINGS[ord('_')] = '_';
            $PERCENT_ENCODED_STRINGS[ord('~')] = '~';
            //echo 'init---';
        }

        $result = '';
        for ($i = 0; $i < strlen($value); ++$i) {
            $result .= $PERCENT_ENCODED_STRINGS[ord($value[$i])];
        }
        return $result;
    }

    /**
     * 进行 http 请求
     *
     * @param $url
     * @param $method
     * @param string[] $header
     * @param array $data
     * @return false|mixed
     * @throws GuzzleException
     */
    protected function clientRequest($url, $method, $header = ['Content-Type'=> 'application/json'], $data = [])
    {
        $client = new Client();
        dump($method);
        dump($url);
        dump($header);
        dump($data);
        try {
            $response =  $client->request($method, $url, [
                'headers'   => $header,
                'json'      => $data
            ]);
        } catch (\Exception $e) {
            $this->message = $e->getMessage();
            dump($this->message);
        }

        dd($response);

        $this->recordLog('请求 url: ' . $url);
        $this->recordLog('请求 参数: ' . json_encode($data));

        $status = $response->getStatusCode(); // 200
        $this->recordLog('响应 status: ' . $status);

        $reason = $response->getReasonPhrase(); // OK
        $this->recordLog('响应 reason: ' . $reason);
        if ($status == 200) {
            $content = obj_2_array(json_decode($response->getBody()->getContents()));
            $this->recordLog('响应 content: ' . json_encode($content));

            // 判断是否操作成功
            $errno = Arr::get($content, 'errno');
            if ($errno !== 0) {
                $this->message = '' ;// Arr::get($this->error_code_options, $errno);;
                return false;
            }
            return  $content;
        } else {
            $this->message = $reason;
            return false;
        }
    }

    /**
     * 记录操作日志
     *
     * @param $info
     * @param bool $is_start
     */
    public function recordLog($info, $is_start = false)
    {
        if ($is_start) {
            $info = '============================================== '.$info.' ==============================================';
        }
        Log::channel('third-party')->info($info);
    }
}