個人情報の取得
次に、ボタンウィジェットから返ってきたアクセストークンを利用して、Amazon Payにアクセスしてユーザの個人情報を取得することができます。アクセストークンはユーザがサイトにログインした時に認証サーバから承諾されています。アクセストークンはクライアント、ユーザ、アクセススコープで特定しております。クライアントは顧客の個人データを取得するためにアクセストークンを使用しなければなりません。サーバサイドアプリケーションでは、/handle_login.phpで作成したリクエストをハンドリングし、アクセストークンとProfile RESTのAPIを利用して個人情報を取得します。
サンプル
PHPサンプル
$c = curl_init('https://api.sandbox.amazon.com/auth/o2/tokeninfo?access_token='
. urlencode($_REQUEST['access_token']));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$r = curl_exec($c);
curl_close($c);
$d = json_decode($r);
if ($d->aud != 'YOUR-CLIENT-ID') {
// the access token does not belong to us
header('HTTP/1.1 404 Not Found');
echo 'Page not found';
exit;
}
// exchange the access token for user profile
$c = curl_init('https://api.sandbox.amazon.com/user/profile');
curl_setopt($c, CURLOPT_HTTPHEADER, array('Authorization: bearer '
. $_REQUEST['access_token']));
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
$r = curl_exec($c);
curl_close($c);
$d = json_decode($r);
echo sprintf('%s %s %s', $d->name, $d->email, $d->user_id);
Javaサンプル
このサンプルコードを利用するためにはJacksonとHttpComponentsライブラリをダウンロードしなければなりません。
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import java.net.URLEncoder;
import java.util.Map;
...
// verify that the access token belongs to us
Content c = Request.Get(
"https://api.amazon.com/auth/o2/tokeninfo?access_token=" +
URLEncoder.encode(access_token, "UTF-8"))
.execute()
.returnContent();
Map m = new ObjectMapper().readValue(
c.toString(), new TypeReference<map>(){});
if (!"YOUR-CLIENT-ID".equals(m.get("aud"))) {
// the access token does not belong to us
throw new RuntimeException("Invalid token");
}
// exchange the access token for user profile
c = Request.Get("https://api.amazon.com/user/profile")
.addHeader("Authorization", "bearer " + access_token)
.execute()
.returnContent();
m = new ObjectMapper().readValue(
c.toString(), new TypeReference<map>(){});
System.out.println(
String.format("%s %s %s", m.get("name"),
m.get("email"), m.get("user_id")));</map</map