Grato por sua visita. Neste momento esta página está apenas disponível em inglês.

Login with Amazon SDK for JavaScript Reference Guide

This is the Login with Amazon SDK for JavaScript Reference. This documents contains reference information for the Login with Amazon SDK for JavaScript, as well as information about how to load the SDK. Login with Amazon is a web service that enables Amazon customers to login to your web or mobile app using their Amazon credentials. After they have logged in, your app can access some information from their Amazon profile.

amazon.Login Methods

All of the functions in login.js are found in the amazon.Login namespace. These functions allow you to identify your client application, request an access token, and exchange an access token for customer profile information.

authorize

AuthorizeRequest authorize(options, next);

Requests authorization according to options then redirects or calls next. Depending on the options set, a popup window will open to allow the user to login, or the window will redirect to the login page. You must call setClientId prior to calling authorize. You must call authorize prior to calling retrieveProfile.

This method returns an AuthorizeRequest object. Call onComplete on that object to register a callback function or redirect URI, similar to the next parameter. After the request is complete, the object will contain properties detailing the response (such as an access token or authorization code).

Parameters:

  • options - required - (Object).
    options can contain the following properties:
    • interactive - (String) Specifies when to show a login screen to the user. auto will attempt to use a cached token. If the cached token fails or does not exist, the user will be presented with a login screen. always does not use the cached token and always presents a login screen. never will used the cached token; if the token does not work, authorize will return invalid_grant. Defaults to auto.
    • popup - (Boolean) true to use a popup window for login, false to redirect the current browser window to the authorization dialog. Defaults to true. If false, the next parameter MUST be a redirect URL . Popup windows are not supported in native iOS apps.
    • response_type - (String) The grant type requested. Specify token to request an Implicit grant or code to request an Authorization Code grant. Defaults to token.
    • scope - required - (String or Array[String]) The access scope requested. Must be profile, profile:user_id, postal_code, or some combination.
    • state - (String) A state parameter. An opaque value used by the client to maintain state between this request and the response. The Login with Amazon authorization service will include this value when redirecting the user back to the client. It is also used to prevent cross-site request forgery. For more information see Cross-site Request Forgery.
  • next (Function or String) A URI to redirect the browser response, or a JavaScript function to call with the authorization response.

About the next parameter

If next is a URI, once the user logs in the current window will be redirected to the URI and the authorization response will be added to the query string. The URI must use the HTTPS protocol and belong to the same domain as the current window.

options = { scope: 'profile' };
amazon.Login.authorize(options, 'https://example.org/redirect_here')
// on success the current window will redirect to:
// https://example.org/redirect_here?access_token=XYZ&token_type=bearer&…

// on failure the current window will redirect to:
// https://example.org/redirect_here?error=access_denied&…

If next is a callback function, it will be invoked with a response object containing the fields of the authorization response.

options = { scope: 'profile' };
amazon.Login.authorize(options, function(response) {
  if ( response.error ) {
      alert('oauth error ' + response.error);
     return;
  }
alert('success: ' + response.access_token);
});

Response Caching

When authorize receives a valid access token response, it automatically caches the token and associated metadata for reuse. This cache persists across page reloads and browser sessions. If a subsequent authorize call can be fulfilled by the cached token response, the SDK will reuse that token instead of requesting a new authorization. Use options.interactive to override this behavior.

Interactivity Modes

The options.interactive setting allows you to choose between three interactivity modes. They are:

  • auto: Attempt to authorize the user using the cached token. If that fails, initiate a new authorization, showing the login and consent screen if necessary.
  • always: Initiate a new authorization, showing the login screen and ignoring any cached token.
  • never: Attempt to authorize the user using the cached token. If that fails, return an invalid_grant error.

Returns

An AuthorizeRequest object. AuthorizeRequest allows callers to register a callback function or redirect URL to use when the login request is complete. It also allows callers to get the current status of the request. When the request is complete, new properties are added to AuthorizeRequest based on the type of authorization request. If the request fails, error properties are added to the object.

getClientID

getClientId();

Gets the client identifier that will be used to request authorization. You must call setClientId before calling this function.

Parameters

None.

Returns

clientId - (String). The client ID assigned to your application. Maximum size of 100 bytes.

See Also

logout

logout();

Logs out the current user after a call to authorize.

Parameters

None.

Returns

None.

Examples:

<script type="text/javascript">
  document.getElementById('logout').onclick = function() {
     amazon.Login.logout();
  };
</script>

See Also

retrieveProfile

retrieveProfile(accessToken, callback);

Retrieves the customer profile and passes it to a callback function. Uses an access token provided by authorize.

Parameters

  • accessToken - optional - (String) An access token. If this parameter is omitted, retrieveProfile will call authorize, requesting the profile scope.

Callback (callback)

function(response);

Called with the profile data or an error string.

Callback Parameters

  • response - (Object)
    • success - (Boolean) true if the request was successful, otherwise false.
    • error - (String) Included if the request failed, and contains an error message.
    • profile - (Object) Included if the request was successful, and contains profile information.
      • CustomerId - (String) An identifier that uniquely identifies the logged-in user for this caller. Only present if the profile or profile:user_id scopes are requested andgranted.
      • Name - (String) The customer's name. Only present if the profile scope is requested and granted.
      • PostalCode - (String) The postal code of the customer's primary address. Only present if the postal_code scope is requested and granted.
      • PrimaryEmail - (String) The primary email address for the customer. Only present if the profile scope is requested and granted.
amazon.Login.authorize({ scope: 'postal_code profile' }, function () {
    amazon.Login.retrieveProfile(function (response) {
        // Display profile information.
    });
});

Example 1:

<script type="text/javascript">
document.getElementById('LoginWithAmazon').onclick = function() {
 setTimeout(window.doLogin, 1);
 return false;
};
window.doLogin = function() {
  options = {};
  options.scope = 'profile';
  amazon.Login.authorize(options, 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>

Example 2:

var access_token = 'Atza|EKdsnskdna…'; // obtained from authorization response

amazon.Login.retrieveProfile(access_token, function(response) {
  if ( response.success ) {
     alert('Hello, ' + response.profile.Name);
     alert('Your e-mail address is ' + response.profile.PrimaryEmail);
     alert('Your unique ID is ' + response.profile.CustomerId);
  }
  else {
     alert('Oh no! An error happened: ' + response.error);
  }
});

See Also

setClientId

setClientId(clientId);

Sets the client identifier that will be used to request authorization. You must call this function before calling authorize.

Parameters

  • clientId - Required - (String). The client ID assigned to your application.

Returns

None.

Example:

window.onAmazonLoginReady = function() {
  amazon.Login.setClientId('YOUR-CLIENT-ID');
};

setSandboxMode

setSandboxMode(sandboxMode);

Determines whether or not Login with Amazon should use the Amazon Pay sandbox for requests. To use the Amazon Pay sandbox, call setSandboxMode(true) before calling authorize.

Parameters

  • sandboxMode - Required - (boolean). true to use the Amazon Pay sandbox to process requests, otherwise false.

Returns

None.

See Also

setSiteDomain

setSiteDomain(siteDomain);

Sets the domain to use for saving cookies.The domain must match the origin of the current page. Defaults to the full domain for the current page.For example, if you have two pages using the Login with Amazon SDK for JavaScript, site1.example.com and site2.example.com, you would set the site domain to example.com in the header of each site. This will ensure that the cookies on both sites have access to the same cached tokens.

Parameters

  • siteDomain - Required - (String). The site to store Login with Amazon cookies. Must share the origin of the current page.

Returns

None.

See Also

setUseCookie

setUseCookie(useCookie);

Determines whether or not Login with Amazon should use access tokens written to the amazon_Login_accessToken cookie. You can use this value to share an access token with another page. Access tokens will still only grant access to the registered account for whom they were created.

When true, the Login with Amazon SDK for JavaScript will check this cookie for cached tokens, and store newly granted tokens in that cookie.

Parameters

  • useCookie - Required - (boolean). true to store the access token from authorizein a cookie, otherwise false.

Returns

None.

See Also

setRegion

setRegion(region);

Login With Amazon has multiple authorization and resource endpoints. This API determines the region of the authorization and resource endpoints Login with Amazon SDK should talk to. This needs to be called before the authorize and retreiveProfile APIs.

When not set, it defaults to “NorthAmerica”

Parameters

region - (amazon.Login.Region) - Required. It can be one of the following

  • amazon.Login.Region.NorthAmerica
  • amazon.Login.Region.Europe
  • amazon.Login.Region.AsiaPacific

Returns

None.

amazon.Login Classes

AuthorizeRequest

The AuthorizeRequest class is used in response to an authorize call. AuthorizeRequestM allows callers to register a callback function or redirect URL to use when the login request is complete. It also allows callers to get the current status of the request. When the request is complete, AuthorizeRequest adds new properties based on the type of authorization request. If the request fails, error properties provide information on the failure.

The following table details which properties are added for each response type:

Response Type Properties
Authorization Response  code and state
Access Token Response access_token, token_type, expires_in, and scope
Error Response error, error_description, and error_uri

onComplete

onComplete(next);

Registers a callback function or sets a redirect URI to call when the authorization request is complete. If this function is called after the request is complete, the function or redirect will happen immediately. If a callback function is used, the AuthorizeRequest will be the first parameter. If a redirect URI is used, the browser will redirect to that URI with the OAuth 2 response parameters included in the query string.

If multiple redirect URLs are set, AuthorizeRequest uses the most recent one.

Parameters

  • next - (Function or String) A URI to redirect the browser response, or a JavaScript function to call with the authorization response.

access_token

access_token - (String) The access token issued by the authorization server.

code

code - (String) An authorization code that can be exchanged for an access token.

error

error - (String) A short error code indicating why the authorization failed. It can be one of the following:

Error Description
access_denied The customer or authorization server denied the request.
invalid_grant The authorization server denied the request due to inability to use a cached token.
invalid_request The request is missing a required parameter, has an invalid value, or is otherwise malformed.
invalid_scope One or more of the requested scopes are invalid.
server_error The authorization server encountered an unexpected error. This is analogous to a 500 HTTP status code.
temporarily_unavailable The authorization server is current unavailable due to a temporary condition. This is analogous to a 503 HTTP status code.
unauthorized_client The client is not authorized to perform this request.

error_description

error_description - (String) A human-readable description of the error.

error_uri

error_uri - (String) A URI for a web page with more information on the error.

expires_in

expires_in - (Number) The number of seconds until the access token expires.

scope

scope - (String) The scope granted by the authorization server for the access token. Must be profile, profile:user_id, postal_code, or some combination.

state

state - (String) The state value provided to authorize using the options object.

status

status - (String) The current status of the request. One of queued, in progress, or complete .

token_type

token_type - (String) The type of token issued. Must be bearer.