使用令牌发出 cURL 请求,如何持久化令牌

时间:2021-07-06 12:31:04

标签: php laravel api curl

我需要从第三方 API (peplink) 获取数据。我设置的方式是使用 Laravel。首先,我发出 cURL 请求以获取令牌。然后,当我收到令牌时,我将它作为不记名令牌传递到 CURL 标头中。

所有这些都有效,但调用需要超过 1 秒才能完成。当我从终端 cURL 时,我会在 200 毫秒内得到响应。我想我走错了路,因为每次接收数据时,都会生成一个新的访问令牌。

public function login()
{
    $response = Http::asForm()->post('https://api.ic.peplink.com/api/oauth2/token', [
        'client_id' => 'xxxxxxxxxxxxxxx',
        'client_secret' => 'xxxxxxxxxxxxxxx',
        'grant_type' => 'client_credentials'
    ]);
    $this->token = json_decode($response, true)['access_token'];
}

public function list_devices()
{
    $response = Http::withHeaders([
        'Authorization' => 'Bearer ' . $this->token,
        'Keep-Alive' => 'timeout=5, max=100'
    ])->get('https://api.ic.peplink.com/rest/o/pY0gKf/n/5/d/basic');

    return $response->body();
}

以下代码用于获取数据。

use App\Http\Controllers\PeplinkController as PepClient;
...
public function testing() {
    $pepconnection = new PepClient;
    $login = $pepconnection->login();
    $devices = $pepconnection->list_devices();

    return $devices;
}

检查标题时,我也看到了一个JSESSIONID;我认为我也需要实现这一点?

Date: Tue, 06 Jul 2021 12:10:23 GMT
Content-Type: text/html;charset=UTF-8
Content-Length: 657
Connection: keep-alive
Content-Encoding: gzip
X-Powered-By: JSP/2.3
Set-Cookie: JSESSIONID=T_zvj29dOxMqY32ionUWzvM_QmMTr6AjrXyr0zq6.co6-1; path=/; secure; HttpOnly
Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization, X-CSRF-API-TOKEN, Cache-Control
Server: IC2
Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONS

0 个答案:

没有答案