2016-10-03 126 views
0

我需要連接使用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; 
+0

讓我們看看確切的錯誤信息。 –

+0

我得到的只是這個:{「error」:「invalid_request」} –

+0

爲什麼你使用了用戶名和密碼= api key? –

回答

1

除了POST字段數據,您的所有代碼看起來都不錯。 問題是您的查詢字符串已被編碼。 當您撥打curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));時,再次編碼。

我建議你給變量$data設置爲數組:

$data = array(
    'grant_type' => 'password', 
    'scope'  => 'read write', 
    'username' => $api, 
    'password' => $api, 
); 

查詢字符串時將http_build_query被稱爲正確編碼。

+0

啊,我明白了。謝謝! :) –