我正在使用 Laravel 调用外部 API。
这是我的客户:
<?php
use GuzzleHttp\Client;
$client = new Client();
$response = $client->request('POST',
'https://example.org/oauth/token', [
'headers' => [
'cache-control' => 'no-cache',
'Content-Type' => 'application/x-www-form-urlencoded',
],
'form_params' => [
'client_id' => '2',
'client_secret' => 'client-secret',
'grant_type' => 'password',
'username' => 'username',
'password' => 'password',
],
]);
$accessToken = json_decode((string)$response->getBody(),
true)['access_token'];
现在我可以用它来获取一些东西:
<?php
$response = $client->request('GET',
'https://example.org/api/items/index', [
'headers' => [
'Accept' => 'application/json',
'Authorization' => 'Bearer '.$accessToken,
],
]);
所以现在我不想再次在每个方法上启动客户端。所以也许有一种很酷/类似 Laravel 的方式来$client在特定路由上向控制器提供?
我考虑过应用服务提供商或中间件,但我希望看到一个示例 :-)
catspeake