我需要連接使用oAuth2的API。 我從來沒有使用oAuth2之前,我不知道如何。 提供者提供以下信息:OAuth2令牌PHP
獲取訪問令牌是通過向上述端點發送HTTP POST請求完成的。申請應包含以下標題:
Authorization: Basic [client_id]:[client_secret]
Content-Type: application/x-www-form-urlencoded
凡[client_id]
和[client_secret]
應該與您的信息替換。合成的[client_id]:[client_secret]
字符串應該是base64編碼的。
頭應該是這個樣子:
Authorization: Basic bXlfY2xpZW50X2lkOnBFUnkyTGhLYko0U2FkY3ZLcklpQW5xWnprakg5bm9STUc3aUxZcWl2MA==
最後,需要下列的請求正文:
grant_type=password&scope=read write&username=[username]&password=[password]
其中[用戶名]和[密碼]應與您的憑據來代替。如果您使用API密鑰訪問API,則應使用上面獲得的API密鑰替換[用戶名]和[密碼]。
如果您的請求是正確組成的,並且您的憑據是正確的,則服務器將返回JSON格式的access_token供您使用:
{
"access_token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9(...)",
"token_type":"Bearer",
"expires_in":3600,
"refresh_token":null
}
我想什麼是下面的,但它返回一個無效的請求消息:
$api = "KEY GOES HERE";
$authurl = "https://url.com/oauth/token";
$client_id = "ID GOES HERE";
$client_secret = "SECRET GOES HERE";
// Creating base 64 encoded authkey
$Auth_Key = $client_id.":".$client_secret;
$encoded_Auth_Key=base64_encode($Auth_Key);
$headers = array();
$headers['Authorization'] = "Basic ".$encoded_Auth_Key;
$headers['Content-Type'] = "application/x-www-form-urlencoded";
$data = "grant_type=password&scope=read write&username=".$api."&password=".$api."";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $authurl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
$auth = curl_exec($ch);
if (curl_errno($ch)){
echo 'Error: ' . curl_error($ch);
}
curl_close($ch);
$secret = json_decode($auth);
$access_key = $secret->access_token;
讓我們看看確切的錯誤信息。 –
我得到的只是這個:{「error」:「invalid_request」} –
爲什麼你使用了用戶名和密碼= api key? –