2016-10-03 6 views
0

oAuth2を使用しているAPIに接続する必要があります。 以前はoAuth2を使用したことがありません。 プロバイダは次の情報を提供しています。OAuth2トークンPHP

アクセストークンの取得は、HTTP POST要求を上記のエンドポイントに送信することによって行われます。要求は、次のヘッダーが含まれている必要があります

[client_id][client_secret]はあなたの情報に置き換えてください
Authorization: Basic [client_id]:[client_secret] 
Content-Type: application/x-www-form-urlencoded 

。構成された[client_id]:[client_secret]文字列は、base64でエンコードされている必要があります。

ヘッダは次のようになります。[ユーザー名]と[パスワード]は、資格情報に置き換えてください

grant_type=password&scope=read write&username=[username]&password=[password] 

Authorization: Basic bXlfY2xpZW50X2lkOnBFUnkyTGhLYko0U2FkY3ZLcklpQW5xWnprakg5bm9STUc3aUxZcWl2MA== 

を最後に、次のリクエストボディを必要としています。 APIキーを使用してAPIにアクセスする場合は、[username]と[password]の両方を上記の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キーを使用しましたか? –

答えて

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

ああ、そうです。ありがとうございました! :) –

関連する問題