在Laravel中使用GuzzleHttp調(diào)用第三方服務(wù)的API接口代碼
背景:用laravel進行分布式開發(fā),自己寫了一個業(yè)務(wù)系統(tǒng),還寫了一個用戶中心和其他的信息中心
現(xiàn)在需要做到前端只需要訪問業(yè)務(wù)系統(tǒng)的API接口也可以獲取到其他服務(wù)上面的數(shù)據(jù)
找了很多資料,最后查到了Laravel自帶的GuzzleHttp可以達到我的需求
Guzzle中文文檔:
http://guzzle-cn.readthedocs.io/zh_CN/latest/index.html
引入安裝
在composer.json文件的“require”項中加入
"guzzlehttp/guzzle": "^6.3",
然后命令行執(zhí)行composer install
在項目中的具體用法:
1、在項目某個地方,我選擇的是在app/Http/Services目錄下面新建一個APIHelper
<?php namespace App\Http\Services; class APIHelper { public function post($body,$apiStr) { $client = new \GuzzleHttp\Client(['base_uri' => 'http://192.168.31.XX:xxx/api/']); $res = $client->request('POST', $apiStr, ['json' => $body, 'headers' => [ 'Content-type'=> 'application/json', // 'Cookie'=> 'XDEBUG_SESSION=PHPSTORM', "Accept"=>"application/json"] ]); $data = $res->getBody()->getContents(); return $data; } public function get($apiStr,$header) { $client = new \GuzzleHttp\Client(['base_uri' => 'http://192.168.31.XX:xxx/api/']); $res = $client->request('GET', $apiStr,['headers' => $header]); $statusCode= $res->getStatusCode(); $header= $res->getHeader('content-type'); $data = $res->getBody(); return $data; } }
在項目中主要我用的是post方法,
'Cookie'=> 'XDEBUG_SESSION=PHPSTORM',
這一行加進去之后可以使用XDebug進行調(diào)試,但是在真正用起來的時候不需要在header里面加這一行了
如果是調(diào)用https接口,如果有證書問題,則加入這兩項'verify' => '/full/path/to/cert.pem','verify' => false,不驗證證書。
public static function post_user($body,$apiStr) { $client = new \GuzzleHttp\Client(['verify' => '/full/path/to/cert.pem','base_uri' => 'http://xxx.xxx.com/api/']); $res = $client->request('POST', $apiStr, ['verify' => false, 'json' => $body, 'headers' => [ 'Content-type'=> 'application/json'] ]); $data = $res->getBody()->getContents(); $response=json_decode($data); return $response; }
2、具體在Controller中使用
public function index(Request $request) { $data = $request->json()->all(); $body = $data; $apiStr = '/api/xxx/list'; $api = new APIHelper(); $res =$api->post($body,$apiStr); $data = json_decode($res); $ret=new RetObject(); $ret->retCode='0000'; $ret->retMsg='Success'; $ret->data=$data; return response()->json($ret); }
這樣就可以在一個系統(tǒng)里用GuzzleHttp調(diào)用第三方的API接口了
以上這篇在Laravel中使用GuzzleHttp調(diào)用第三方服務(wù)的API接口代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于二級目錄拖拽排序的實現(xiàn)(源碼示例下載)
本篇文章介紹了,關(guān)于二級目錄拖拽排序的實現(xiàn)(源碼示例下載)。需要的朋友參考下2013-04-04PHP htmlspecialchars() 函數(shù)實例代碼及用法大全
這篇文章主要介紹了PHP htmlspecialchars() 函數(shù)實例代碼及用法大全,需要的朋友可以參考下2018-09-09laravel框架數(shù)據(jù)庫配置及操作數(shù)據(jù)庫示例
這篇文章主要介紹了laravel框架數(shù)據(jù)庫配置及操作數(shù)據(jù)庫,結(jié)合實例形式分析了Laravel數(shù)據(jù)庫的基本配置與操作實現(xiàn)技巧,需要的朋友可以參考下2019-10-10基于HTTP長連接的"服務(wù)器推"技術(shù)的php 簡易聊天室
關(guān)于HTTP長連接的“服務(wù)器推”技術(shù)原理可以查看IBM的這篇文章,我簡單的做了個DEMO.2009-10-10