我试图从URL获取一些jSon对象。但是有OAuth 2.0我无法通过。我发现this如何获取json数据,但我无法找到如何通过此身份验证。这就是api要我做的事情:
"要使用client_credentials授权获取访问令牌,请发送
POST
请求 / oauth / access_token 端点grant_type
,client_id
和client_secret
参数。如果 成功后,它将返回一个Session对象。"
网址是例如的 www.example.com/a1 / 我找到了一些如何通过PHP进行POST的教程,但我可能做错了。
这是我试过的
<?php
$endpoint = "www.example.com/a1/oauth/access_token";
$params = array(
"client_id" => "...",
"client_secret" => "...",
"grant_type" => "client_credentials");
$curl = curl_init($endpoint);
curl_setopt($curl, CURLOPT_HEADER, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_HEADER,'Content-Type: application/x-www-form-urlencoded');
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$postData = "";
//This is needed to properly form post the credentials object
foreach($params as $k => $v)
{
$postData .= $k . '='.urlencode($v).'&';
}
$postData = rtrim($postData, '&');
curl_setopt($curl, CURLOPT_POSTFIELDS, $postData);
echo "Performing Request...";
$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
// evaluate for success response
if ($status != 200) {
throw new Exception("Error: call to URL $endpoint failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl) . "\n");
}
curl_close($curl);
$json_data = json_decode($json_response, true);
echo "My token: ". $json_data["access_token"];
?>