Amazon Pay and Login with Amazon integration guide

Obtaining profile information

To create a local account for your buyer, you can obtain the buyer's profile information from their Amazon account by submitting an access token and a method for handling the profile information that is returned.

The procedure is language-dependent. For details, see the code samples below.

You must download the Jackson and HttpComponents libraries to use this sample code.


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.sandbox.amazon.com/auth/o2/
  tokeninfo?access_token=" + URLEncoder.encode(access_token, "UTF-8"))
  .execute()
  .returnContent();
  Map <string><string> m = new ObjectMapper().readValue(
  c.toString(), new TypeReference<map <string><string>>(){});
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.sandbox.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")));

In your server-side application, handle the request made to /handle_login.php, and obtain profile information using the access token and the Profile REST API.


$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);

import pycurl
import urllib
import json
import StringIO
 
...
 
b = StringIO.StringIO()
 
# verify that the access token belongs to us
c = pycurl.Curl()
c.setopt(pycurl.URL, "https://api.amazon.com/auth/o2/tokeninfo?access_token=" + urllib.quote_plus(access_token))
c.setopt(pycurl.SSL_VERIFYPEER, 1)
c.setopt(pycurl.WRITEFUNCTION, b.write)
 
c.perform()
d = json.loads(b.getvalue())
 
if d['aud'] != 'YOUR-CLIENT-ID' :
    # the access token does not belong to us
    raise BaseException("Invalid Token")
 
# exchange the access token for user profile
b = StringIO.StringIO()
 
c = pycurl.Curl()
c.setopt(pycurl.URL, "https://api.amazon.com/user/profile")
c.setopt(pycurl.HTTPHEADER, ["Authorization: bearer " + access_token])
c.setopt(pycurl.SSL_VERIFYPEER, 1)
c.setopt(pycurl.WRITEFUNCTION, b.write)
 
c.perform()
d = json.loads(b.getvalue())
 
print "%s %s %s"%(d['name'], d['email'], d['user_id'])

require "rubygems"
require "net/https"
require "json"
require "uri"
 
...
 
# verify that the access token belongs to us
uri = URI.parse("https://api.amazon.com/auth/o2/tokeninfo?access_token=" + URI.encode(access_token))
req = Net::HTTP::Get.new(uri.request_uri)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
 
response = http.request(req)
decode = JSON.parse(response.body)
 
if decode['aud'] != 'YOUR-CLIENT-ID'
  # the access token does not belong to us
  raise "Invalid token"
end
 
# exchange the access token for user profile
uri = URI.parse("https://api.amazon.com/user/profile")
req = Net::HTTP::Get.new(uri.request_uri)
req['Authorization'] = "bearer " + access_token
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_PEER
 
response = http.request(req)
decode = JSON.parse(response.body)
 
puts sprintf "%s %s %s", decode['name'], decode['email'], decode['user_id']

JavaScript Code Sample

Use the access token and a callback function to make a retrieveProfile API call. For more information, see the "Login with Amazon SDK for JavaScript Reference".

The following code sample shows how to request the Amazon customer’s profile using the JavaScript Login with Amazon SDK:


amazon.Login.retrieveProfile(response.access_token,function (profileResponse) {
  // this callback is executed Asynchronously!!
  // check if the profile request was successful
  if(profileResponse.success) {
    // request was successful
    console.log("Buyer Name  = " + profileResponse.profile.Name);
    console.log("Buyer Email = " + profileResponse.profile.PrimaryEmail);
    console.log("Buyer Zip   = " + profileResponse.profile.PostalCode);
    console.log("Amzn Customer ID = " + profileResponse.profile.CustomerId);
    }
});

(from LWA website http://login.amazon.com/website)

Place this code after the LwA button in the <body> tag.

Replace www.example.com with the domain of your website.

After the buyer has signed in and consented to share their profile information, the current window is redirected to the given URI and the authorization response is added to the query string. The URI must use HTTPS protocol in production, and be on the same domain as the current window.


<script type="text/javascript">

  document.getElementById('LoginWithAmazon').onclick = function() {
    options = { scope : 'profile' };
    amazon.Login.authorize(options,
      'https://www.example.com/handle_login.php');
    return false;
  };

</script>

Handle the response from Amazon with the /handle_login.php on your website. You can change this path to one of your choosing later.

The amazon.Login.retrieveProfile function returns three parameters: success, error, and profile. Success indicates whether the call was successful. The error parameter returns an error message if an error occurred. If there was no error, profile contains the buyer's profile.

See also


Copyright © 2009-2017 Amazon.com, Inc. or its affiliates. Amazon and Amazon.com are registered trademarks of Amazon.com, Inc. or its affiliates. All other trademarks are the property of their respective owners.