laravel 接口

controller中使用
try {
            @ignore_user_abort(true);
            @set_time_limit(0);

            /** @var \App\Support\ApiRequestMTest $apiRequestTest */
            $apiRequestTest = app('App\Support\ApiRequestTest');

            $queryDBSSOption = [
                'method' => 'post',
                'urlprefix' => config('bind.prefix.testa', 'http://test.com') . '/iapi/v1/',
                'debug' => false,
                'parseApi' => true,
            ];
            $queryPath = 'report/inventory_stats';//test项目代码路径
            $queryData = [
                'syncdata' => json_encode($input),
            ];

            $result = $apiRequestTest->queryApiResponse($queryPath, $queryData, $queryDBSSOption);

            $msg = '成功.';
            Flash::message($msg);
            return redirect(route('inventoryhistory_stats.index'));
        } catch (\Exception $ex) {
            $msg = $ex->getMessage();
            Flash::error($msg);
            return redirect(route('inventoryhistory_stats.index'));
        }
配置文件bind.php 中定义

return [
   'prefix'=>
      [
        
         'testa'=>env('CORPBIND_PREFIX_DBUC','https://test.com'),
      ],



ApiRequestTest.php
<?php
/**
/
namespace App\Support;

use App\Contexts\AppConstant;
use App\Exceptions\AppRuntimeException;
use Unirest;

class ApiRequestManager
{
    /**
     * @param string $querypath
     * @param array $params
     * @param array $option
     * @return array|mixed
     */
    public static function call($querypath = '', $params = [], $option = [])
    {
        $option += [
            'urlprefix' => null,
            'method' => null,
            'debug' => false,
            'parseBody'=>true,
            'parseApi'=>true,
        ];
        $debugInfo = [];
        if (empty($option['urlprefix'])) {
            $option['urlprefix'] = env('APIURLBASE', 'http://dbp.thebizark.com/iapi/v1/');
        }
        $requestUri = $option['urlprefix'].$querypath;
        $response = null;
        if (!empty($option['method'])) {
            $option['method'] = strtolower($option['method']);
            switch ($option['method']) {
                case 'get':
                    $response = Unirest\Request::get($requestUri, [], $params);
                    break;
                case 'post':
                    $params = is_array($params) ? http_build_query($params) : $params;
                    $response = Unirest\Request::post($requestUri, [], $params);
                    break;
                case 'put':
                    $params = is_array($params) ? http_build_query($params) : $params;
                    $response = Unirest\Request::put($requestUri, [], $params);
                    break;
                case 'head':
                    $response = Unirest\Request::head($requestUri, $params);
                    break;
                case 'patch':
                    $params = is_array($params) ? http_build_query($params) : $params;
                    $response = Unirest\Request::patch($requestUri, [], $params);
                    break;
                case 'delete':
                    $params = is_array($params) ? http_build_query($params) : $params;
                    $response = Unirest\Request::delete($requestUri, [], $params);
                    break;
            }
        } else {
            if (!empty($params)) {
                $response = Unirest\Request::post($requestUri, [], $params);
            } else {
                $response = Unirest\Request::get($requestUri);
            }
        }
        if ($option['debug'] == true) {
            $debugInfo['option'] = $option;
            $debugInfo['requestUri'] = $requestUri;
            $debugInfo['params'] = $params;
            $debugInfo['response'] = $response;

            return ['data' => $debugInfo];
        }
        if ($response) {
            $responseData = $response->raw_body;
            if($option['parseBody']==true){
                if($option['parseApi']==true){
                    $responseData = $response->body;
                    if (!isset($responseData['status'])) {
                        throw new AppRuntimeException('Server Response Message Format Error', AppConstant::EXCODE_CLIENT_UNPROCESSABLE_ENTITY, ['data' => $response->raw_body]);
                    } elseif ($responseData['status'] == AppConstant::API_STATUS_ERROR) {
                        throw new AppRuntimeException($responseData['message'], $responseData['code'], $responseData['data'], $responseData['status']);
                    }
                }elseif(is_callable($option['parseApi'])){
                    $responseData = call_user_func($option['parseApi'],$response->raw_body);
                }else{
                    $responseData = $response->body;
                }
                return $responseData;
            }else{
                return $responseData;
            }
        } else {
            throw new AppRuntimeException('ResponseError:'.$requestUri, AppConstant::EXCODE_SERVER_INTERNALERROR);
        }
    }

    /**
     * Get a fresh instance of the Guzzle HTTP client.
     *
     * @return \GuzzleHttp\Client
     */
    protected function getHttpClient()
    {
        return new \GuzzleHttp\Client;
    }

    /**
     * @param string $querypath
     * @param array $params
     * @param array $option
     * @return array|mixed|\Psr\Http\Message\StreamInterface|\Psr\Http\Message\ResponseInterface
     */
    public function queryApiResponse($querypath = '', $params = [], $option = [])
    {
        $option += [
            'urlprefix' => null,
            'method' => null,
            'debug' => false,
            'returnResponse'=>false,
            'returnCurlCmd'=>false,
            'logQuery'=>false,//config('app.debug'),
            'logCurlCmd'=>false,//config('app.debug'),
            'logTrace'=>false,//config('app.debug'),
            'logPath'=>storage_path('app/api/default/'),
            'parseBody'=>true,
            'parseApi'=>false,
            'httpErrors'=>true, // Set to false to disable throwing exceptions on an HTTP protocol errors (i.e., 4xx and 5xx responses).  // Throws a \GuzzleHttp\Exception\ServerException
            'headers'=>[],
            'auth'=>[
                //'username', 'password',
                //'digest'
            ],
        ];
        $debugInfo = [];
        $curlCmd = 'curl -ivs ';
        $curlInfo = [
            'url'=>'',
            'method'=>'',
            'auth'=>[],
            'headers'=>[],
            'data'=>'',
        ];
        if (empty($option['urlprefix']) && strpos($querypath,'://')===false) {
            $option['urlprefix'] = config('site.apibase', 'http://dbp.thebizark.com/iapi/v1/');
        }
        $requestUri = $option['urlprefix'].$querypath;
        $curlInfo['url'] = $requestUri;

        $response = null;

        $client = $this->getHttpClient();
        if(empty($option['method'])){
            if(!empty($params)){
                $option['method'] = 'post';
            }else{
                $option['method'] = 'get';
            }
        }
        $option['method'] = strtolower($option['method']);

        $requestOptions = [];

        $requestOptions['headers'] = ['Accept' => 'application/json'];
        if(!empty($option['headers'])){
            $requestOptions['headers'] = array_merge($requestOptions['headers'],$option['headers']);
        }
        $curlInfo['headers'] = $requestOptions['headers'];

        if(!empty($option['auth'])){
            $requestOptions['auth'] = $option['auth'];
            $curlInfo['auth'] = $requestOptions['auth'];
        }
        $requestOptions['http_errors'] = $option['httpErrors'];
        //Log::debug('api request params',['$params'=>$params]);

        $curlInfo['method'] = strtoupper($option['method']);

        switch ($option['method']) {
            case 'get':
                is_array($params) && $requestOptions['query'] = $params;

                $parse_url = parse_url($requestUri);
                if(is_array($params) && !empty($params)){
                    if (isset($parse_url['query'])) {
                        $parse_url['query'] .= '&'.(is_array($params) ? http_build_query($params) : $params);
                    } else {
                        $parse_url['query'] = (is_array($params) ? http_build_query($params) : $params);
                    }
                }
                $url = ((isset($parse_url['scheme'])) ? $parse_url['scheme'].'://' : '')
                    .((isset($parse_url['user'])) ? $parse_url['user']
                        .((isset($parse_url['pass'])) ? ':'.$parse_url['pass'] : '').'@' : '')
                    .((isset($parse_url['host'])) ? $parse_url['host'] : '')
                    .((isset($parse_url['port'])) ? ':'.$parse_url['port'] : '')
                    .((isset($parse_url['path'])) ? $parse_url['path'] : '')
                    .((isset($parse_url['query'])) ? '?'.$parse_url['query'] : '')
                    .((isset($parse_url['fragment'])) ? '#'.$parse_url['fragment'] : '')
                ;

                $curlInfo['url'] = $url;

//                $response = $client->get($requestUri, $requestOptions);
                break;
            case 'post':
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->post($requestUri, $requestOptions);
                break;
            case 'put':
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->put($requestUri, $requestOptions);
                break;
            case 'head':
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->head($requestUri, $requestOptions);
                break;
            case 'patch':
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->patch($requestUri, $requestOptions);
                break;
            case 'delete':
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->delete($requestUri, $requestOptions);
                break;
            default:
                if(is_array($params)){
                    $requestOptions['form_params'] = $params;
                    $curlInfo['data'] = http_build_query($params);
                }else{
                    $requestOptions['body'] = $params;
                    $curlInfo['data'] = $params;
                }
//                $response = $client->request($option['method'],$requestUri, $requestOptions);
                break;
        }

        /**
         *
        $curlInfo = [
        'url'=>'',
        'method'=>'',
        'auth'=>[],
        'headers'=>[],
        'data'=>'',
        ];
         */

        if(!empty($curlInfo['auth'])){
            if(isset($curlInfo['auth'][2])){
                $curlCmd .=' --digest';
            }
            $curlCmd .=' -u "'.$curlInfo['auth'][0].':'.$curlInfo['auth'][1].'"';
        }
        $curlCmd .=' -X '.$curlInfo['method'];

        if(!empty($curlInfo['headers'])){
            foreach ($curlInfo['headers'] as $headerKey=>$headerValue) {
                $curlCmd .=' -H \''.$headerKey.':'.$headerValue.'\'';
            }
        }
        if(strlen($curlInfo['data'])>0){
            $curlCmd .=' -d \''.$curlInfo['data'].'\'';
        }
        $curlCmd .=' \''.$curlInfo['url'].'\'';

//        Log::debug('API REQUEST: '.$curlCmd);

        if($option['returnCurlCmd']==true){
            return $curlCmd;
        }


        switch ($option['method']) {
            case 'get':
                $response = $client->get($requestUri, $requestOptions);
                break;
            case 'post':
                $response = $client->post($requestUri, $requestOptions);
                break;
            case 'put':
                $response = $client->put($requestUri, $requestOptions);
                break;
            case 'head':
                $response = $client->head($requestUri, $requestOptions);
                break;
            case 'patch':
                $response = $client->patch($requestUri, $requestOptions);
                break;
            case 'delete':
                $response = $client->delete($requestUri, $requestOptions);
                break;
            default:
                $response = $client->request($option['method'],$requestUri, $requestOptions);
                break;
        }

        if($option['logQuery']==true){
            !isset($debugInfo['option']) && $debugInfo['option'] = $option;
            !isset($debugInfo['requestUri']) && $debugInfo['requestUri'] = $requestUri;
            !isset($debugInfo['params']) && $debugInfo['params'] = $params;
            !isset($debugInfo['requestOptions']) && $debugInfo['requestOptions'] = $requestOptions;
            !isset($debugInfo['responseStatusCode']) && $debugInfo['responseStatusCode'] = !empty($response)?$response->getStatusCode():0;
            !isset($debugInfo['responseBody']) && $debugInfo['responseBody'] = !empty($response)?((string)$response->getBody()):$response;
//            if($option['logTrace']==true){
//                !isset($debugInfo['callTrace']) && $debugInfo['callTrace'] = generateCallTrace();
//            }
            $_logBasePath = $option['logPath'];
            empty($_logBasePath) && $_logBasePath = storage_path('app/api/default/');
            $_logBasePath = rtrim($_logBasePath,'/ ').'/'.date('Ym');
            if(!is_dir($_logBasePath)){ @mkdir($_logBasePath,0775,true); }
            $_logFileName = date('Ymd').'.log';
            $_logContent = '['.date('Y-m-d H:i:s').'] '.var_export($debugInfo,true);

            if($option['logCurlCmd']==true){
                $_logContent.=PHP_EOL.$curlCmd;
            }
            if($option['logTrace']==true){
                $_logContent.=PHP_EOL.generateCallTrace();
            }
            @file_put_contents($_logBasePath.'/'.$_logFileName,$_logContent.PHP_EOL,FILE_APPEND);
        }
        if($option['returnResponse']){
            return $response;
        }
        if ($option['debug'] == true) {
            !isset($debugInfo['option']) && $debugInfo['option'] = $option;
            !isset($debugInfo['requestUri']) && $debugInfo['requestUri'] = $requestUri;
            !isset($debugInfo['params']) && $debugInfo['params'] = $params;
            !isset($debugInfo['requestOptions']) && $debugInfo['requestOptions'] = $requestOptions;

            !isset($debugInfo['response']) && $debugInfo['response'] = $response;
            !isset($debugInfo['responseStatusCode']) && $debugInfo['responseStatusCode'] = !empty($response)?$response->getStatusCode():0;
            !isset($debugInfo['responseBody']) && $debugInfo['responseBody'] = !empty($response)?((string)$response->getBody()):$response;
            return ['data' => $debugInfo];
        }
        if ($response) {
            $rawRespBody = isset($debugInfo['responseBody'])?$debugInfo['responseBody']:$response->getBody();
            !is_string($rawRespBody) && $rawRespBody = $rawRespBody->getContents();
            if($option['parseBody']==true){
                if($option['parseApi']===true){
                    $responseData = json_decode($rawRespBody,true);
                    if (!isset($responseData['status'])) {
                        throw new AppRuntimeException('Server Response Message Format Error', AppConstant::EXCODE_CLIENT_UNPROCESSABLE_ENTITY, ['data' => $rawRespBody]);
                    } elseif ($responseData['status'] == AppConstant::API_STATUS_ERROR) {
                        throw new AppRuntimeException($responseData['message'], $responseData['code'], $responseData['data'], $responseData['status']);
                    }
                }elseif(is_callable($option['parseApi'])){
                    $responseData = call_user_func($option['parseApi'],$rawRespBody);
                }else{
                    $responseData = json_decode($rawRespBody,true);
                }
                return $responseData;
            }else{
                return $rawRespBody;
            }
        } else {
            throw new AppRuntimeException('ResponseError:'.$requestUri, AppConstant::EXCODE_SERVER_INTERNALERROR);
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值