Ti ringraziamo per la visita. Questa pagina è per il momento disponibile solo in inglese.

Obtain Customer Profile Information

After the user grants your website access to their Amazon customer profile, you will receive an access token. If you're using server-side scripting to request an access token via the Authorization Code Grant, the access token is returned in the access token response.

If you're on a Browser-Based app, and need the access token on the client side, you can set options.pkce = true and call the retrieveToken API with the authorization code to get the access token. For the API to work, the client needs to have cookies enabled and the authorize call must be on the same domain as the retrieveToken call. To access the authorized customer data, you submit that access token to Login with Amazon using HTTPS.

In response, Login with Amazon will return the appropriate customer profile data. The profile data you receive is determined by the scope you specified when requesting access. The access token reflects access permission for that scope.

Use the Login with Amazon SDK for JavaScript

If you are using the Login with Amazon SDK for JavaScript, use amazon.Login.retrieveProfile to exchange an access token for a profile. For example:

<script type="text/javascript">
    document.getElementById('LoginWithAmazon').onclick = function() {
       setTimeout(window.doLogin, l);
       return false;
    };
    window.doLogin = function() {
        options = {};
        options.scope = 'profile';
        options.pkce = true;
        amazon.Login.authorize(options, function(response) {
            if ( response.error ) {
                alert('oauth error ' + response.error);
            return;
            }
            amazon.Login.retrieveToken(response.code, function(response) {
                if ( response.error ) {
                    alert('oauth error ' + response.error);
                return;
                }
                amazon.Login.retrieveProfile(response.access_token, function(response) {
                    alert('Hello, ' + response.profile.Name);
                    alert('Your e-mail address is ' + response.profile.PrimaryEmail);
                    alert('Your unique ID is ' + response.profile.CustomerId);
                    if ( window.console && window.console.log )
                       window.console.log(response);
                });
            });
        });
   };
 </script>

The amazon.Login.retrieveProfile function returns three parameters: success, error, and profile. success indicates whether the call was successful. error contains an error message if an error occurred. If there was no error, profile contains the user's profile. For more information on this method and its parameters, see the Login with Amazon SDK for JavaScript Reference.

Call the profile Endpoint Server-side

If you are calling the profile endpoint directly, you can specify the access token in one of three ways: as a query parameter, as a bearer token, or using x-amz-access-token in the HTTP header. For example:

https://api.amazon.com/user/profile?access_token=AtzaIIQEBLjAsAhRmHjNgHpi0UDme37rR6CuUpSR...
GET /user/profile HTTP/1.1
Host: api.amazon.com
Date: Wed, 0l Jun 20ll l2:00:00 GMT
Authorization: Bearer Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...
GET /user/profile HTTP/1.1
Host: api.amazon.com
Date: Wed, 0l Jun 20ll l2:00:00 GMT
x-amz-access-token: Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...

Login with Amazon only supports application/json as a content type and en-us as a content language. Login with Amazon uses this content type and language by default, even if they are not specified.

GET /user/profile HTTP/1.1
Host: api.amazon.com
Date: Wed, 0l Jun 20ll l2:00:00 GMT
x-amz-access-token: Atza|IQEBLjAsAhRmHjNgHpi0U-Dme37rR6CuUpSR...
Accept: application/json
Accept-Language: en-US

Detailed code samples are available in the following languages:

PHP Sample

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. If you use the following code sample, replace YOUR-CLIENT-ID with the Client ID you obtained when you registered your application.

// verify that the access token belongs to us
$c = curl_init('https://api.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.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);
Ruby sample

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. If you use the following code sample, replace YOUR-CLIENT-ID with the Client ID you obtained when you registered your application.

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']
Java sample

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. If you use the following code sample, replace YOUR-CLIENT-ID with the Client ID you obtained when you registered your application.

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>(){});

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>(){});

System.out.println(String.format("%s %s %s", m.get("name"), m.get("email"), m.get("user_id")));
Python sample

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. If you use the following code sample, replace YOUR-CLIENT-ID with the Client ID you obtained when you registered your application.

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'])

Customer Profile Response

If your access token is valid, you will receive the customer's profile data as an HTTP response in JSON. For example:

HTTP/1.1 200 OK
 x-amzn-RequestId: 0f6bef6d-705c-lle2-aacb-93e6bf26930l
 Content-Type: application/json
 Content-Language: en-US
 Content-Length: 85
 {
    "user_id": "amznl.account.K2LI23KL2LK2",
    "email":"mhashimoto-04@plaxo.com",
    "name" :"Mork Hashimoto",
    "postal_code": "98052"
 }

The Request-Id is for logging and can be ignored. If you are troubleshooting an issue with the Login with Amazon team you may be asked to supply the Request-Id.

If there is a problem fulfilling your profile request, you will receive an HTTP error. The error codes for an access request include:

Status Error code Description
200 Success The request was successful.
400 invalid_request The request is missing a required parameter or otherwise malformed.
400 invalid_token The access token provided is expired, revoked, malformed, or invalid for other reasons.
401 insufficient_scope The access token provided does not have access to the required scope.
500 ServerError The server encountered a runtime error.

In addition to the error code, you may receive a JSON payload with more information. For example:

HTTP/1.1 400 Bad Request
Content-Type: application/json;charset=UTF-8
Content-Length: 74
{
"error": "machine-readable error code",
"error_description": "human-readable error description",
"request_id": "bef0c2f8-e292-4l96-8c95-8833fbd559df"
}

Get Customer Information to your Server

You can get customer profile information obtained from Amazon on your backend server to identify the signed-in user on your server, or to create a more personalized account for the user. To do so securely, send the access token from your client to your server using HTTPS. Then, from server-side, call the profile endpoint using that access token. See Call the profile endpoint server-side for details and code samples in multiple languages. Login with Amazon will return a customer profile response with values (such as user_id, email, name, and/or postal_code) you can keep on your server.

Taking this step will ensure the profile data you save to your server belongs to the customer who is signed into your client. See our guide on Integrating with your Existing Account System for more information on combining and managing user accounts in your backend.