使用 Yii2 REST 客户端消费 Yii2 REST API

Use Yii2 REST client to consume Yii2 REST API

我使用 Yii2 documentation 创建了一个 REST API。它似乎工作正常,因为我可以像这样使用 curl:

curl -i "https://example.com/api/v3/user" \
    -H "Accept:application/json"  \
    -H "Authorization: Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

我现在希望能够从另一个 Yii2 站点使用此数据。我正在尝试使用 Yii2 REST API 客户端。我不会 post 整个代码,因为它基本上是 Facebook client in yiisoft/yii2-authclient.

的副本

有谁知道可以帮助我修改此内容以消耗我的 API 的指南吗?首先,我正在为 $authUrl$tokenUrl.

设置什么而苦恼

我不确定你是否需要扩展 outh2 class 因为我相信你没有在第一个 Yii2 webapp 中完成身份验证逻辑,比如使用第一个 webapp url 然后重定向进行身份验证到第二个 webapp 从 url 中提取令牌。

创建一个具有这些方法的组件可能更简单

class YourRestClient {
  const BASE_URL = 'https://example.com/api/v3';
  private $_token = null;

  public function authenticate($username,$password){
    $client = new Client();
    $response = $client->createRequest()
    ->setMethod('POST')
    ->setUrl(BASE_URL.'/user/login')
    ->setData(['username' => $username, 'password' => $password])
    ->send();
    if ($response->isOk) {
        $this->_token = $response->data['token'];
    }
  }

    public function logout(){
      //your logut logic
    }

    public function refreshToken(){
      //your refresh logic 
    }

    public function userList(){
      $client = new Client();
      $response = $client->createRequest()
      ->setMethod('GET')
      ->setUrl(BASE_URL.'/user/users')
      ->addHeaders([
          'content-type' => 'application/json',
          'Authorization' => 'Bearer '.$_token,
      ])
      ->send();
      if ($response->isOk) {
          return $response->getData();
      }
    }
}

了解更多信息httpclient

如果我没记错的话,你需要的是使用 yiisoft/yii2-httpclient 参考:https://github.com/yiisoft/yii2-httpclient 添加它:php composer.phar require --prefer-dist yiisoft/yii2-httpclient

然后打电话«我可能会建立一个模型来处理这个»

use yii\httpclient\Client;

$client = new Client();
$response = $client->createRequest()
    ->setMethod('GET')
    ->setUrl('https://example.com/api/v3/user')
    ->addHeaders(['Authorization' => 'Bearer xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'])
    ->send();
if ($response->isOk) {
    // use your data
}