LoginSignup
2
1

More than 5 years have passed since last update.

ebay ユーザートークンの取得

Last updated at Posted at 2017-09-29

ebayのユーザートークン(OAuth)の取得

テストも兼ねているため、サーバー側の情報はすべてSandboxのもの。
まず、全体のソース

usertoken.php
<?php
 //テストのため、SandboxのIDを使用した。
 $devID  = 'My Dev ID';
 $appID  = 'My App ID';
 $certID = 'My Cert ID';
 $runame = 'My RuName';

 //ログインフォームからリダイレクトした際に付加されるパラメーターを取得
 $_SESSION['code'] = $_GET['code'];
 //ユーザートークンのリクエストURL
 $token_url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token';
 //リクエストヘッダーのAuthorizationに挿入する変数
 $authorization =  base64_encode($appID.':'.$certID);

 //ユーザートークンのリクエストボディ
 $request_body = [
   'grant_type' => 'authorization_code',
   'code' => $_SESSION['code'],
   'redirect_uri' => $runame
 ];
 //ユーザートークンのリクエストヘッダー
 $request_header = [
   'Content-Type:application/x-www-form-urlencoded',
   'Authorization:Basic '.$authorization
 ];

 //念の為、リクエストの内容を確認できるようにしておく
 echo "<pre>";
 print_r($request_body);
 print_r($request_header);
 echo "</pre>";

 $curl = curl_init();

 curl_setopt($curl, CURLOPT_URL, $token_url);
 curl_setopt($curl, CURLOPT_POST, true); //POST
 curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($request_body));
 curl_setopt($curl, CURLOPT_HTTPHEADER, $request_header);
 curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
 curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($curl, CURLOPT_HEADER, true);

 $response = curl_exec($curl);

 $header_size = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
 $response_header = substr($response, 0, $header_size);
 $response_body = substr($response, $header_size);
 $result = $response_body;

 curl_close($curl);

 echo "<pre>";
 print_r($result);
 echo "</pre>";

?>

エラーしか帰ってこない。そして、その原因

リクエストの送信が出来たが、下記エラー文が帰ってきた。
{"error":"invalid_grant","error_description":"the provided authorization grant code is invalid or was issued to another client"}
ebayのフォーラムでも検索してみたがソースを見る限り、間違っていないようだったのであれこれいじってみて2時間以上。
思いつきでいじったところ、原因はURLに付加されたパラメーターの処理でした。

usertoken.php
 //エラーが出ていた時
 $_SESSION['code'] = urlencode($_GET['code']);

 //urlencodeを外したらうまく行った
 $_SESSION['code'] = $_GET['code'];

ebayのドキュメントやフォーラムで他の人のソースを見る限りだと、urlencodeでうまくいっているみたいだから、正直コレであっているか解らんが、きちんとユーザートークンが取得できたので、とりあえずコレで進めていくしか無い。

参考

WebAPIを叩く(curl)

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1