将 curl 翻译成 CakePHP 3.6 httpclient?



我正在使用BShaffer OAuth2/CakePHP 3.6以及大部分方式。但是,我在代码中遇到了一个小绊脚石,我目前正在尝试将 PHP Curl 命令转换为 Cake 友好的 httpClient 命令

有问题的 curl 命令是

curl -u testclient:testpass http://localhost/token.php -d 'grant_type=client_credentials'

而我目前对代码的尝试是

$http = new Client();
$auth = [
'_csrfToken' => $this->request->getParam('_csrfToken'),
'grant_type' => 'client_credentials',
'username' => $result->UserID,
'password' => $createCode
];
$response = $http->post('/oauth/request', $auth);

我觉得我需要将用户名/密码放入 OAuth2 的身份验证标头中,但我不是 100% 确定如何做到这一点。httpClient 的文档确实包含 OAuth2,但作为单个标头:

$http = new Client([
'headers' => ['Authorization' => 'Bearer ' . $accessToken]
]);
$response = $http->get('https://example.com/api/profile/1');

编辑:

通过评论中的示例,我已经让 PHP 的 CURL 直接工作,但是 Cake 的客户端仍然产生空白结果。这是我目前所拥有的:

$data = $this->request->getData();
$result = $this->Users->RegisterNewUser($data);
$report = $data['email'];
if ($result->result == 1)
{
$generatePrivateKey = $this->OAuth->generatePrivateKey($result->UserID);

$query = [
'client_id' => $result->UserID,
'client_secret' => $generatePrivateKey,
'redirect_uri' => ''
];
$this->OAuth->insertClientData($query);

// Insert User into clients //
$auth = [
'grant_type' => 'client_credentials'
];
// Is not working //
$http = new Client();
$response = $http->post('https://example.com/oauth/request', $auth, [
'auth' => ['username' => $result->UserID, 'password' => 
$generatePrivateKey]
]);
print_r($response->getBody());
// Works //
$ch = curl_init('https://example.com/oauth/request');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $auth);        
curl_setopt($ch, CURLOPT_USERPWD, $result->UserID . ":". $generatePrivateKey);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
$output = curl_exec($ch);
curl_close($ch); 
}

如注释中所述,您需要发出使用基本身份验证的请求,这就是显示的 Curl 请求的作用。

为此,请在auth选项中指定usernamepassword键,该选项将在客户端post()方法的第三个参数中传递:

$http = new Client();
$data = [
'grant_type' => 'client_credentials',
];
$options = [
'auth' => [
'username' => $result->UserID,
'password' => $createCode
]
];
$response = $http->post('/oauth/request', $data, $options);

例如,可以通过响应body()方法、流getContents()方法,甚至通过相应地解析数据的魔术属性(不是它们的粉丝(来检索响应正文:

$stringBody = $reponse->body();
$stringBody = $response->getBody()->getContents();
$arrayData = $response->json;

参见

  • 说明书> Http 客户端>身份验证
  • > http 客户端>读取响应正文的说明书

尝试以此为起点,它应该适用于大多数需要身份验证令牌的 cURL 方案:

$post_data = ["stuff" => $stuff, "stuff2" => $stuff2];
$data_string = json_encode($post_data);
$ch = curl_init('https://endpoint.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Authorization: Bearer ' . $your_auth_token,
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$output = curl_exec($ch);
// Do stuff with output

最新更新