Important: This SDK has been deprecated and no longer maintained. No further updates or security patches will be provided. New integrations should use Amazon Pay API SDK (Java) & refer this documentation for more details.
- Amazon Pay - Register here
- Java 1.6 or higher (including JCE Java Cryptography Extension)
- Apache Commons Logging 1.2 (or JCL-over-SLF4J drop in replacement)
- Apache Commons Codec 1.10
- Google Gson 2.8.9 or higher (for GetUserInfo and IPN handling only)
Amazon Pay API Integration
importcom.amazon.pay.Client;
importcom.amazon.pay.Config;
importcom.amazon.pay.impl.PayClient;
importcom.amazon.pay.impl.PayConfig;Your Amazon Pay keys are available in your Seller Central account
StringmerchantId = "YOUR_MERCHANT_ID";
StringaccessKey = "YOUR_ACCESS_KEY";
char[] secretKey = getSecretKey() // Replace with your implementationConfigconfig = newPayConfig()
.withSellerId(merchantId)
.withAccessKey(accessKey)
.withSecretKey(secretKey)
.withCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE)
.withSandboxMode(sandboxMode)
.withRegion(Region.YOUR_REGION_CODE);
//Default currencyCode is what is set in config file. To override, use below//config.withCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE);//Default region is what is set in config file. To override, use below//config.withRegion(Region.YOUR_REGION_CODE);//Default environment is what is set in config file. For testing in Sandbox mode, use//config.withSandboxMode(true);Clientclient = newPayClient(config);Below is an example on how to make the GetOrderReferenceDetails API call:
importcom.amazon.pay.Client;
importcom.amazon.pay.request.GetOrderReferenceDetailsRequest;
importcom.amazon.pay.response.parser.GetOrderReferenceDetailsResponseData;
// These values are grabbed from the Amazon Pay Address and Wallet widgetsGetOrderReferenceDetailsRequestgetOrderReferenceDetailsRequest = newGetOrderReferenceDetailsRequest("AMAZON_ORDER_REFERENCE_ID");
//optional parametersgetOrderReferenceDetailsRequest.setAddressConsentToken("ADDRESS_CONSENT_TOKEN");
GetOrderReferenceDetailsResponseDataresponse = client.getOrderReferenceDetails(getOrderReferenceDetailsRequest);// This will return the original response body as a Stringresponse.toXML();
// RequestIdresponse.getRequestId();
// AmazonOrderReferenceIdresponse.getDetails().getAmazonOrderReferenceId();
// BuyerNameresponse.getDetails().getBuyer().getBuyerName();
OtherdataavailablearebuyerEmail, buyerPhone, DestinationAddress// For testing/debugging purposes, see all response fields using belowresponse.toString();// To get the buyers full address if shipping/tax// calculations are needed you can use the following// API call to obtain the order reference details.GetOrderReferenceDetailsRequestreq = newGetOrderReferenceDetailsRequest("AMAZON_ORDER_REFERENCE_ID");
req.setAddressConsentToken("ADDRESS_CONSENT_TOKEN");
client.getOrderReferenceDetails(req);
// Make the SetOrderReferenceDetails API call to// configure the Amazon Order Reference Id.// There are additional optional parameters that// are not used below.//construct requestSetOrderReferenceDetailsRequestsetOrderReferenceDetailsRequest = newSetOrderReferenceDetailsRequest("AMAZON_ORDER_REFERENCE_ID" , "ORDER_AMOUNT");
//set optional parameterssetOrderReferenceDetailsRequest.setOrderCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE);
setOrderReferenceDetailsRequest.setSellerNote("YOUR_SELLER_NOTE");
setOrderReferenceDetailsRequest.setSellerOrderId("YOUR_SELLER_ORDER_ID");
setOrderReferenceDetailsRequest.setStoreName("YOUR_STORE_NAME");
//call APIclient.setOrderReferenceDetails(setOrderReferenceDetailsRequest);
// Make the ConfirmOrderReference API call to// confirm the details set in the API call// above.client.confirmOrderReference("AMAZON_ORDER_REFERENCE_ID");
// Set a unique id for your current authorization// of this payment.// Make the Authorize API call to authorize the// transaction. You can also capture the amount// in this API call or make the Capture API call// separately. There are additional optional// parameters not used below.//Construct RequestAuthorizeRequestauthorizeRequest = newAuthorizeRequest("AMAZON_ORDER_REFERENCE_ID" , "YOUR_UNIQUE_ID" , "ORDER_AMOUNT");
//Set Optional parametersauthorizeRequest.setAuthorizationCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE); //Overrides currency code set in ClientauthorizeRequest.setSellerAuthorizationNote("Your Authorization Note");
authorizeRequest.setTransactionTimeout("0"); //Set to 0 for synchronous modeauthorizeRequest.setCaptureNow(true); // Set this to true if you want to capture the amount in the same API call//Call Authorize APIAuthorizeResponseDataresponse = client.authorize(authorizeRequest);
// Make the Capture API call if you did not set the// 'capture_now' parameter to 'true'. There are// additional optional parameters that are not used below.//Construct requestCaptureRequestrequest = newCaptureRequest("AMAZON_AUTHORIZATION_ID" , "YOUR_UNIQUE_ID" , "ORDER_AMOUNT");
//Set optional parametersrequest.setCaptureCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE); //Overrides currency code set in Clientrequest.setSellerCaptureNote("YOUR_CAPTURE_NOTE");
CaptureResponseDataresponse = client.capture(request);
// Close the order reference once your one time// transaction is complete.client.closeOrderReference(newCloseOrderReferenceRequest("AMAZON_ORDER_REFERENCE_ID"));
StringmerchantId = "YOUR_MERCHANT_ID";
StringaccessKey = "YOUR_ACCESS_KEY";
StringsecretKey = "YOUR_SECRET_KEY";
Configconfig = newPayConfig()
.withSellerId(merchantId)
.withAccessKey(accessKey)
.withSecretKey(secretKey);
DefaultcurrencyCodeiswhatissetinconfigfile. Tooverridethis, useconfig.withCurrencyCode(CurrencyCode.YOUR_CURRENCY_CODE);
Defaultregioniswhatissetinconfigfile. Foroverridethis, useconfig.withRegion(Region.YOUR_REGION);
Defaultenvironmentiswhatissetinconfigfile. FortestinginSandboxmode, useconfig.withSandboxMode(true);
Clientclient = newPayClient(config);
// These values are grabbed from the Amazon Pay// Address and Wallet widgetsStringbillingAgreementId = "AMAZON_BILLING_AGREEMENT_ID";
StringaddressConsentToken = "ADDRESS_CONSENT_TOKEN";
GetBillingAgreementDetailsRequestgetBillingAgreementDetailsRequest = newGetBillingAgreementDetailsRequest(billingAgreementId).setAddressConsentToken(addressConsentToken);
// Next you will need to set the various details// for this subscription with the following API call.// There are additional optional parameters that// are not used below.StringbillingAgreementId = "AMAZON_BILLING_AGREEMENT_ID";
SetBillingAgreementDetailsRequestsetBillingAgreementDetailsRequest = newSetBillingAgreementDetailsRequest(billingAgreementId).setSellerNote("testing");
client.setBillingAgreementDetails(setBillingAgreementDetailsRequest);
// Make the ConfirmBillingAgreement API call to confirm// the Amazon Billing Agreement Id with the details set above.// Be sure that everything is set correctly above before// confirming.ConfirmBillingAgreementRequestconfirmBillingAgreementRequest = newConfirmBillingAgreementRequest(billingAgreementId);
client.confirmBillingAgreement(confirmBillingAgreementRequest);
// The following API call is not needed at this point, but// can be used in the future when you need to validate that// the payment method is still valid with the associated billing// agreement id.ValidateBillingAgreementRequestvalidateBillingAgreementRequest = newValidateBillingAgreementRequest(billingAgreementId);
client.validateBillingAgreement(validateBillingAgreementRequest);
// Set the amount for your first authorization.Stringamount = "10.00";
// Set a unique authorization reference id for your// first transaction on the billing agreement.StringauthorizationReferenceId = "YOUR_UNIQUE_Id";
// Now you can authorize your first transaction on the// billing agreement id. Every month you can make the// same API call to continue charging your buyer// with the 'capture_now' parameter set to true. You can// also make the Capture API call separately. There are// additional optional parameters that are not used// below.AuthorizeOnBillingAgreementRequestauthOnBillingRequest = newAuthorizeOnBillingAgreementRequest(billingAgreementId , authorizationReferenceId , amount);
AuthorizeOnBillingAgreementResponseDataresponse = client.authorizeOnBillingAgreement(authOnBillingRequest);
// You will need the Amazon Authorization Id from the// AuthorizeOnBillingAgreement API response if you decide// to make the Capture API call separately.StringamazonAuthorizationId = response.getDetails().getAmazonAuthorizationId();
// Set a unique id for your current capture of// this transaction.StringcaptureReferenceId = "YOUR_UNIQUE_ID";
// Make the Capture API call if you did not set the// 'capture_now' parameter to 'true'. There are// additional optional parameters that are not used// below.// The following API call should not be made until you// are ready to terminate the billing agreement.CloseBillingAgreementRequestrequest = newCloseBillingAgreementRequest(billingAgreementId).setMWSAuthToken(mwsAuthToken);
client.closeBillingAgreement(request);ThisAPIcallallowsyoutoobtainuserprofileinformationonceauserhasloggedintoyourapplicationusingtheirAmazoncredentials. // Your client id is located in your Seller Central account.StringclientId = "YOUR_CLIENT_ID";
// The access token is available in the return URL parameters after a user has logged in.StringaccessToken = "USER_ACCESS_TOKEN";
Useruser = client.getUserInfo(accessToken, clientId);
BelowprofileinformationcanberetrievedfromUserobject.
user.getName();
user.getEmail();
user.getUserId();/** * This can be placed in your java application for a method * that is configured to receive a "POST" IPN from Amazon. **/Map<String,String> headers = IPN_MESSAGE_HEADERStringbody = IPN_MESSAGE_BODYNotificationnotification = NotificationFactory.parseNotification(headers, body);
//To view received notification JSON bodynotification.toJSON(); //We recommend to log this value for debugging purposes//Determine the notification typeNotificationTypetype = notification.getNotificationType();
//Retrieve notification object based on typeswitch (type) {
caseCaptureNotification:
CaptureNotificationcn = (CaptureNotification)notification;
//To access capture details like captureId, captureAmount etc. cn.getCaptureDetails().getAmazonCaptureId();
break;
caseAuthorizationNotification:
AuthorizationNotificationan = (AuthorizationNotification)notification;
//To access authorizationDetails like authorizationReferenceId, authorizationAmount etc..an.getAuthorizationDetails().getAmazonAuthorizationId();
break;
caseBillingAgreementNotification:
BillingAgreementNotificationbn = (BillingAgreementNotification)notification;
break;
caseOrderReferenceNotification:
OrderReferenceNotificationon = (OrderReferenceNotification)notification;
break;
caseProviderCreditNotification:
ProviderCreditNotificationpc = (ProviderCreditNotification)notification;
break;
caseProviderCreditReversalNotification:
ProviderCreditReversalNotificationpcrn = (ProviderCreditReversalNotification)notification;
break;
caseRefundNotification:
RefundNotificationrefundNotification = (RefundNotification)notification;
break;
caseSolutionProviderMerchantNotification:
SolutionProviderMerchantNotificationsp = (SolutionProviderMerchantNotification)notification;
break;
}
//To access metadata notification.getNotificationMetadata();
//To view original notification bodynotification.toJSON(); ornotification.toMap();Below are the steps to turn on the logging feature for your project.
- Select a logging framework to use for your project.
- Set the Logger instance 'log' in PayLogUtil to the value of the logging framework.
privatestaticLoggerlog = Logger.getLogger(PayLogUtil.class);- logMessage is called from 3 different places
- NotificationFactory.java that logs Headers and Notification Body
- RequestHelper.java logs Client Parameters
- ResponseData.java logs all the response data (GetOrderReferenceDetails,GetAuthorizationDetails, etc.)
- Add log4j.properties file containing the below properties. (You may change as per your requirements)
// Root logger optionlog4j.rootLogger=DEBUG, stdout, file// Redirect log messages to consolelog4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=System.outlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%n// Redirect log messages to a log file, support file rolling.log4j.appender.file=org.apache.log4j.RollingFileAppenderlog4j.appender.file.File=C:\\log4j-application.loglog4j.appender.file.MaxFileSize=5MBlog4j.appender.file.MaxBackupIndex=10log4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-ddHH:mm:ss} %-5p %c{1}:%L - %m%nThis API allows you to make one API call 'getPaymentDetails' to retrieve OrderReference, Authorize, Capture and Refund Details.
//Call GetPaymentDetails APIGetPaymentDetailsresponse = client.getPaymentDetails("AMAZON_ORDER_REFERENCE_ID");
//Order Reference Detailsresponse.getOrderReferenceDetails().getBillingAddress();
response.getOrderReferenceDetails().getRequestPaymentAuthorization();
//Authorize Detailsresponse.getAuthorizationDetails().get("AMAZON_AUTHORIZATION_ID").getCapturedAmount();
response.getAuthorizationDetails().get("AMAZON_AUTHORIZATION_ID").getAuthorizationStatus();
//Capture Detailsresponse.getCaptureDetails().get("AMAZON_CAPTURE_ID").getCaptureAmount();
response.getCaptureDetails().get("AMAZON_CAPTURE_ID").getCaptureStatus();
//Refund Detailsresponse.getRefundDetails().get("AMAZON_REFUND_ID").getFeeRefunded();
response.getRefundDetails().get("AMAZON_REFUND_ID").getRefundStatus();This feature allows you to retrieve Payment Descriptor in the GetOrderReferenceDetails call. Steps to follow to retrieve payment Descriptor as are below -
- Your Amazon Pay Client ID (amzn1.xxxxxxx) needs to be whitelisted with the “payments:instrument_descriptor” scope. Please contact Amazon Pay Support for whitelisting your Client ID.
- Add the “payments:instrument_descriptor” scope to your (test) site button.
- Pass the obtained “access_token” and Order Reference ID’s to the GetOrderReferenceDetails request.
GetOrderReferenceDetailsRequestgetOrderReferenceDetailsRequest = newGetOrderReferenceDetailsRequest("AMAZON_ORDER_REFERENCE_ID");
getOrderReferenceDetailsRequest.setAccessToken(ACCESS_TOKEN);
GetOrderReferenceDetailsResponseDataresponse = client.getOrderReferenceDetails(getOrderReferenceDetailsRequest);
log.info("OrderReferenceID = " + response.getDetails().getAmazonOrderReferenceId());
log.info("Buyer = " + response.getDetails().getBuyer());
PaymentDescriptorpaymentDescriptor = response.getDetails().getPaymentDescriptor();
if (paymentDescriptor != null) {
log.info("Full Descriptor = " + paymentDescriptor.getFullDescriptor());
log.info("Use Amazon Balance First = " + paymentDescriptor.isUseAmazonBalanceFirst());
}- ListOrderReference This API provides a list of orders corresponding to a particular seller order id.
EnumSet<OrderReferenceStatus> filter = EnumSet.of(OrderReferenceStatus.OPEN, OrderReferenceStatus.CANCELED);
XMLGregorianCalendarstartTime =
DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-09-27T07:00:00Z");
XMLGregorianCalendarendTime =
DatatypeFactory.newInstance().newXMLGregorianCalendar("2017-09-30T07:00:00Z");
ListOrderReferenceRequestlistOrderReferenceRequest =
newListOrderReferenceRequest("YOUR_SELLER_ORDER_ID", "SellerOrderId");
// optional parameterslistOrderReferenceRequest.setMWSAuthToken("YOUR_MWS_AUTH_TOKEN");
listOrderReferenceRequest.setStartTime(startTime);
listOrderReferenceRequest.setEndTime(endTime);
listOrderReferenceRequest.setPageSize(5);
listOrderReferenceRequest.setOrderReferenceStatusListFilter(filter);
listOrderReferenceRequest.setSortOrder(SortOrder.Ascending); //sort order can be ascending or descendingListOrderReferenceResponseDataresponse = client.listOrderReference(listOrderReferenceRequest);
StringnextPageToken = response.getNextPageToken(); //to be used in the ListOrderReferenceByNextToken call- ListOrderReferenceByNextToken This API returns a list of the continued orders from the previous call (ListOrderReference) using a NextPageToken value to render the next page of data, if a page size was used to split the list of orders into multiple pages.
ListOrderReferenceByNextTokenRequestlistOrderReferenceByNextTokenRequest = newListOrderReferenceByNextTokenRequest(nextPageToken); //nextPageToken is derived from the ListOrderReference response explained above//optional parameterslistOrderReferenceByNextTokenRequest.setMWSAuthToken("YOUR_MWS_AUTH_TOKEN");
ListOrderReferenceByNextTokenResponseDataresponse =
client.listOrderReferenceByNextToken(listOrderReferenceByNextTokenRequest);The GetMerchantAccountStatus operation is used to query the status of a particular merchant account and to retrieve information if the account is active or inactive.
importcom.amazon.pay.response.model.AccountStatus;
importcom.amazon.pay.response.parser.GetMerchantAccountStatusResponseData;
importcom.amazon.pay.request.GetMerchantAccountStatusRequest;
...
// To check the status of your merchant accountfinalGetMerchantAccountStatusResponseDataresponse = client.getMerchantAccountStatus();
finalAccountStatusaccountStatus = response.getAccountStatus();
if (accountStatus.equals(AccountStatus.ACTIVE)) {
System.out.println("Merchant account is enabled");
} elseif (accountStatus.equals(AccountStatus.INACTIVE)) {
System.out.println("Merchant account is disabled");
}
// Or using MWS delegation to check on the status of another merchant accountfinalGetMerchantAccountStatusRequestrequest = newGetMerchantAccountStatusRequest();
request.setSellerId("REPLACE_WITH_OTHER_MERCHANT_ID");
request.setMWSAuthToken("REPLACE_WITH_MWS_AUTH_TOKEN");
finalGetMerchantAccountStatusResponseDataresp = client.getMerchantAccountStatus(request);
finalAccountStatusstatus = resp.getAccountStatus();
if (status.equals(AccountStatus.ACTIVE)) {
System.out.println("Child merchant account is enabled");
} elseif (status.equals(AccountStatus.INACTIVE)) {
System.out.println("Child merchant account is disabled");
}