Skip to content

Repository files navigation

Maven Central

Amazon Pay API SDK (Java)

Amazon Pay Integration

Requirements

SDK Installation

To use the SDK in a Maven project, add a reference in your pom.xml file's section:

<dependencies>
<dependency>
<groupId>software.amazon.pay</groupId>
<artifactId>amazon-pay-api-sdk-java</artifactId>
<version>2.6.0</version>
</dependency>
</dependencies>

To use the SDK in a Gradle project, add the following line to your build.gradle file::

implementation 'software.amazon.pay:amazon-pay-api-sdk-java:2.6.0'

For legacy projects, you can just grab the binary jar file from the GitHub Releases page.

Public and Private Keys

MWS access keys, MWS secret keys, and MWS authorization tokens from previous MWS-based integrations cannot be used with this SDK.

You will need to generate your own public/private key pair to make API calls with this SDK.

In Windows 10 this can be done with ssh-keygen commands:

ssh-keygen -t rsa -b 2048 -f private.pem
ssh-keygen -f private.pem -e -m PKCS8 > public.pub

In Linux or macOS this can be done using openssl commands:

openssl genrsa -out private.txt 2048
openssl rsa -in private.txt -pubout > public.pub

The first command above generates a private key and the second line uses the private key to generate a public key.

To associate the key with your account, follow the instructions here to Get your Public Key ID.

Namespace

Namespace for this package is com.amazon.pay.api to differentiate this SDK from the original Amazon Pay MWS SDK that uses just the com.amazon.pay namespace.

Here are some common imports you may need depending on your situation:

importcom.amazon.pay.api.AmazonPayClient;
importcom.amazon.pay.api.AmazonPayResponse;
importcom.amazon.pay.api.InstoreClient; // not needed if using WebstoreClientimportcom.amazon.pay.api.PayConfiguration;
importcom.amazon.pay.api.RequestSigner; // not needed if using WebstoreClientimportcom.amazon.pay.api.WebstoreClient;
importcom.amazon.pay.api.exceptions.AmazonPayClientException;
importcom.amazon.pay.api.types.Environment;
importcom.amazon.pay.api.types.Region;
// to construct/parse arbitrary JSON objectsimportorg.json.JSONArray;
importorg.json.JSONObject;
// for generating an idempotency keyimportjava.util.HashMap;
importjava.util.Map;
importjava.util.UUID;
// for loading your private keyimportjava.io.IOException;
importjava.nio.file.Files;
importjava.nio.file.Paths;

Versioning

The pay-api.amazon.com|eu|jp endpoint uses versioning to allow future updates. The major version of this SDK will stay aligned with the API version of the endpoint.

If you are using version 1.x.y of this SDK, $version in below examples would be "v1". 2.x.y would be "v2", etc.

Configuration

You will need your public key id and the file path to your private key.

You will need to specify either Environment.SANDBOX for Sandbox mode, or Environment.LIVE for Production mode.

PayConfigurationpayConfiguration = null;
try {
payConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID")
.setRegion(Region.YOUR_REGION_CODE)
.setPrivateKey("YOUR_PRIVATE_KEY_STRING".toCharArray())
.setEnvironment(Environment.SANDBOX)
.setAlgorithm("AMZN-PAY-RSASSA-PSS-V2"); // Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
// If you have created envrionment specific keys (i.e Public Key Starts with LIVE or SANDBOX) in seller central, then use those PublicKeyId & PrivateKey. In this case, no need to set EnvironmentPayConfigurationpayConfiguration = null;
try {
payConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID") // LIVE-XXXXX or SANDBOX-XXXXX
.setRegion(Region.YOUR_REGION_CODE)
.setPrivateKey("YOUR_PRIVATE_KEY_STRING".toCharArray())
.setAlgorithm('AMZN-PAY-RSASSA-PSS-V2'); // Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
// If you have your private key in a file, you can set it in the payConfiguration in the following way:try {
payConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID")
.setRegion(Region.YOUR_REGION_CODE)
.setPrivateKey(newString(Files.readAllBytes(Paths.get("private.pem"))).toCharArray())
.setEnvironment(Environment.SANDBOX)
.setAlgorithm('AMZN-PAY-RSASSA-PSS-V2'); // Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
// You can also set your private key as a java.security.PrivateKey objectPrivateKeyprivateKey = ...
try {
payConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID")
.setRegion(Region.YOUR_REGION_CODE)
.setPrivateKey(privateKey)
.setEnvironment(Environment.SANDBOX)
.setAlgorithm('AMZN-PAY-RSASSA-PSS-V2'); // Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
// If you have want to enable proxy support, you can set it in the payConfiguration in the following way:try {
ProxySettingsproxySettings = newProxySettings()
.setProxyHost("localhost")
.setProxyPort(8080)
.setProxyUser("user")
.setProxyPassword("password".toCharArray());
payConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID")
.setRegion(Region.YOUR_REGION_CODE)
.setPrivateKey("YOUR_PRIVATE_KEY_STRING".toCharArray())
.setEnvironment(Environment.SANDBOX)
.setAlgorithm('AMZN-PAY-RSASSA-PSS-V2'); // Amazon Signing Algorithm, Optional: uses AMZN-PAY-RSASSA-PSS if not specified
.setProxySettings(proxySettings);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
// If you want to enable the Custom Connection Pool, you can set it in the payConfiguration in the following way:try {
intMAX_CLIENT_CONNECTIONS = 30; // This value should be decided according to your requirementpayConfiguration = newPayConfiguration()
.setPublicKeyId("YOUR_PUBLIC_KEY_ID")
.setRegion(Region.YOUR_REGION_CODE) .setPrivateKey("YOUR_PRIVATE_KEY_STRING".toCharArray())
.setEnvironment(Environment.SANDBOX)
.setClientConnections(MAX_CLIENT_CONNECTIONS); // Default is set to 20
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Convenience Functions (Overview)

Make use of the built-in convenience functions to easily make API calls. Scroll down further to see example code snippets.

When using the convenience functions, the request payload will be signed using the provided private key, and a HTTPS request is made to the correct regional endpoint. In the event of request throttling, the HTTPS call will be attempted up to three times using an exponential backoff approach.

Alexa Delivery Trackers API

Amazon Pay Delivery Notifications Integration Guide.

  • AmazonPayClient: deliveryTracker(JSONObject payload[, Map<String, String> header]) → POST to "$version/deliveryTrackers"

Amazon Checkout v2 API

Amazon Pay Checkout v2 Integration Guide

Amazon Checkout v2 Buyer object

  • WebstoreClient: getBuyer(String buyerToken[, Map<String, String> header]) → GET to "$version/buyers/$buyerToken"

Amazon Checkout v2 CheckoutSession object

  • WebstoreClient: createCheckoutSession(JSONObject payload, Map<String, String> header) → POST to "$version/checkoutSessions"
  • WebstoreClient: getCheckoutSession(String checkoutSessionId[, Map<String, String> header]) → GET to "$version/checkoutSessions/$checkoutSessionId"
  • WebstoreClient: updateCheckoutSession(String checkoutSessionId, JSONObject payload[, Map<String, String> header]) → PATCH to "$version/checkoutSessions/$checkoutSessionId"
  • WebstoreClient: completeCheckoutSession(String checkoutSessionId, JSONObject payload[, Map<String, String> header]) → POST to "$version/checkoutSessions/$checkoutSessionId/complete"

Amazon Checkout v2 ChargePermission object

  • WebstoreClient: getChargePermission(String chargePermissionId[, Map<String, String> header]) → GET to "$version/chargePermissions/$chargePermissionId"
  • WebstoreClient: updateChargePermission(String chargePermissionId, JSONObject payload[, Map<String, String> header]) → PATCH to "$version/chargePermissions/$chargePermissionId"
  • WebstoreClient: closeChargePermission(String chargePermissionId, JSONObject payload[, Map<String, String> header]) → DELETE to "$version/chargePermissions/$chargePermissionId/close"

Amazon Checkout v2 Charge object

  • WebstoreClient: createCharge(payload, Map<String, String> header) → POST to "$version/charges"
  • WebstoreClient: getCharge(String chargeId[, Map<String, String> header]) → GET to "$version/charges/$chargeId"
  • WebstoreClient: captureCharge(String chargeId, JSONObject payload[, Map<String, String> header]) → POST to "$version/charges/$chargeId/capture"
  • WebstoreClient: cancelCharge(String chargeId, JSONObject payload[, Map<String, String> header]) → DELETE to "$version/charges/$chargeId/cancel"

Amazon Checkout v2 Refund object

  • WebstoreClient: createRefund(payload, Map<String, String> header) → POST to "$version/refunds"
  • WebstoreClient: getRefund(String refundId[, Map<String, String> header]) → GET to "$version/refunds/$refundId"

In-Store API

Please contact your Amazon Pay Account Manager before using the In-Store API calls in a Production environment to obtain a copy of the In-Store Integration Guide.

  • InstoreClient: merchantScan(JSONObject scanRequest[, Map<String, String> header]) → POST to "$version/in-store/merchantScan"
  • InstoreClient: charge(JSONObject chargeRequest[, Map<String, String> header]) → POST to "$version/in-store/charge"
  • InstoreClient: refund(JSONObject refundRequest[, Map<String, String> header]) → POST to "$version/in-store/refund"

Authorization Tokens API

Please note that your solution provider account must have a pre-existing relationship (valid and active MWS authorization token) with the merchant account in order to use this function.

  • AmazonPayClient: getAuthorizationToken(String mwsAuthToken, String merchantId[, Map<String, String> header]) → GET to "$version/authorizationTokens/$mwsAuthToken?merchantId=$merchantId"

Using Convenience Functions

Four quick steps are needed to make an API call:

Step 1. Construct a AmazonPayClient (using the previously defined PayConfiguration object).

AmazonPayClientclient = newAmazonPayClient(payConfiguration);
// -or-WebstoreClientwebstoreClient = newWebstoreClient(payConfiguration);
// -or-InstoreClientinstoreClient = newInstoreClient(payConfiguration);

Step 2. Generate the payload.

JSONObjectpayload = newJSONObject();
payload.put("scanData", "UKhrmatMeKdlfY6b");
payload.put("scanReferenceId", "0b8fb271-2ae2-49a5-b35d890");
payload.put("merchantCOE", "DE");
payload.put("ledgerCurrency", "EUR");

Step 3. Execute the call.

AmazonPayResponseresponse = instoreClient.merchantScan(payload);

Step 4. Check the result.

response will be an object with the following getters:

  • 'getStatus()' - int HTTP status code (200, 201, etc.)
  • '**getResponse()*' - the response serialized into a JSONObject
  • 'getRawResponse()' - the raw JSON String response body received from Amazon Pay
  • 'getRequestId()' - the Request ID from Amazon API gateway
  • 'getUrl()' - the URL for the REST call the SDK calls, for troubleshooting purposes
  • 'getMethod() - POST, GET, PATCH, or DELETE
  • 'getHeaders()' - an Map<String, String> containing the various headers generated by the SDK, for troubleshooting purposes
  • 'getRawRequest()' - the JSON request body String sent to Amazon Pay
  • 'getRetries()' - usually 0, but reflects the number of times a request was retried due to throttling or other server-side issue
  • 'getDuration()' - duration in milliseconds of SDK function call
  • 'isSuccess()' - returns true for a 200, 201, or 202 HTTP status; false otherwise

The first two items (status, response) are critical. The remaining items are useful in troubleshooting situations.

If you are a Solution Provider and need to make an API call on behalf of a different merchant account, you will need to pass along an extra authentication token parameter into the API call.

Convenience Functions Code Samples

Amazon Pay Alexa Delivery Notifications

Delivery Notifications Integration Guide.

The deliveryTracker API is only avialable in live environment (not sandbox).

This method is available in the base client ("AmazonPayClient").

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectdeliveryDetails = newJSONObject();
JSONArraydeliveryDetailsArray = newJSONArray();
deliveryDetails.put("trackingNumber", "0430955041235");
deliveryDetails.put("carrierCode", "FEDEX");
deliveryDetailsArray.put(deliveryDetails);
payload.put("amazonOrderReferenceId", "P01-8845762-6072995");
payload.put("deliveryDetails", deliveryDetailsArray);
try {
response = client.deliveryTracker(payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Pay Checkout v2 API

Checkout v2 Integration Guide

These methods are available in Webstore Client.

The headers field is not optional for create/POST calls because it requires, at a minimum, the x-amz-pay-idempotency-key header:

Map<String,String> header = newHashMap<String,String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));

Making a createCheckoutSession request

JSONObjectpayload = newJSONObject();
JSONObjectwebCheckoutDetails = newJSONObject();
webCheckoutDetails.put("checkoutReviewReturnUrl", "https://localhost/store/checkout_review");
payload.put("webCheckoutDetails", webCheckoutDetails);
payload.put("storeId", "amzn1.application-oa2-client.4c46698afa4d4b23b645d05762fc78fa");
AmazonPayResponseresponse = null;
StringcheckoutSessionId = null;
Map<String,String> header = newHashMap<String,String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
try {
response = webstoreClient.createCheckoutSession(payload, header);
checkoutSessionId = response.getResponse().getString("checkoutSessionId");
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a getCheckoutSession request

AmazonPayResponseresponse = null;
try {
response = webstoreClient.getCheckoutSession(checkoutSessionId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making an updateCheckoutSession request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectupdateWebCheckoutDetails = newJSONObject();
updateWebCheckoutDetails.put("checkoutResultReturnUrl", "https://localhost/store/checkout_return");
payload.put("webCheckoutDetails", updateWebCheckoutDetails);
JSONObjectpaymentDetails = newJSONObject();
paymentDetails.put("paymentIntent" , "Authorize");
paymentDetails.put("canHandlePendingAuthorization", false);
JSONObjectchargeAmount = newJSONObject();
chargeAmount.put("amount", "12.34");
chargeAmount.put("currencyCode", "USD");
paymentDetails.put("chargeAmount", chargeAmount);
payload.put("paymentDetails", paymentDetails);
JSONObjectmerchantMetadata = newJSONObject();
merchantMetadata.put("merchantReferenceId", "2019-0001");
merchantMetadata.put("merchantStoreName", "AmazonTestStoreFront");
merchantMetadata.put("noteToBuyer", "noteToBuyer");
merchantMetadata.put("customInformation", "custom information goes here");
payload.put("merchantMetadata", merchantMetadata);
try {
response = webstoreClient.updateCheckoutSession(checkoutSessionId, payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a completeCheckoutSession request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectpaymentDetails = newJSONObject();
JSONObjectchargeAmount = newJSONObject();
chargeAmount.put("amount", "12.34");
chargeAmount.put("currencyCode", "USD");
paymentDetails.put("chargeAmount", chargeAmount);
payload.put("paymentDetails", paymentDetails);
try {
response = webstoreClient.completeCheckoutSession(checkoutSessionId, payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making an getChargePermissions request

AmazonPayResponseresponse = null;
try {
response = webstoreClient.getChargePermissions(chargePermissionId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a updateChargePermission request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectmerchantMetadata = newJSONObject();
merchantMetadata.put("merchantReferenceId", "32-41-323141");
merchantMetadata.put("merchantStoreName", "AmazonTestStoreName");
merchantMetadata.put("noteToBuyer", "Some note to buyer");
merchantMetadata.put("customInformation", "This is custom info");
payload.put("merchantMetadata", merchantMetadata);
try {
response = webstoreClient.updateChargePermission(chargePermissionId, payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a closeChargePermission request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
payload.put("closureReason", "Specify the reason here");
payload.put("cancelPendingCharges", "false");
try {
response = webstoreClient.closeChargePermission(chargePermissionId, payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a getCharge request

AmazonPayResponseresponse = null;
try {
response = webstoreClient.getCharge(chargesId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a createCharge request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectchargeAmount = newJSONObject();
chargeAmount.put("amount", "1.23");
chargeAmount.put("currencyCode", "USD");
payload.put("chargePermissionId", "S01-3152594-4330637");
payload.put("chargeAmount", chargeAmount);
payload.put("captureNow", false);
// if payload.put("captureNow", true);// then provide// payload.put("softDescriptor", "My Soft Descriptor");payload.put("canHandlePendingAuthorization", true);
StringchargeId = null;
Map<String, String> header = newHashMap<String, String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
try {
response = webstoreClient.createCharge(payload, header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
chargeId = response.getResponse().getString("chargeId");

Making a captureCharge request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectcaptureAmount = newJSONObject();
captureAmount.put("amount", "1.23");
captureAmount.put("currencyCode", "USD");
payload.put("captureAmount", captureAmount);
payload.put("softDescriptor", "My Soft Descriptor");
Map<String, String> header = newHashMap<String, String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
try {
response = webstoreClient.captureCharge(chargesId, payload, header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a cancelCharge request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
payload.put("cancellationReason", "Buyer changed their mind");
try {
response = webstoreClient.cancelCharge(chargeId, payload);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Making a createRefund request

AmazonPayResponseresponse = null;
JSONObjectpayload = newJSONObject();
JSONObjectrefundAmount = newJSONObject();
refundAmount.put("amount", "0.01");
refundAmount.put("currencyCode", "USD");
payload.put("chargeId", chargeId);
payload.put("refundAmount", refundAmount);
payload.put("softDescriptor", "AMZ*soft");
Map<String,String> header = newHashMap<String,String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
StringrefundId = null;
try {
response = webstoreClient.createRefund(payload,header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
refundId = response.getResponse().getString("refundId");

Making a getRefund request

AmazonPayResponseresponse = null;
try {
response = webstoreClient.getRefund(refundId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Generate Button Signature (helper function)

This method is available in the base client ("AmazonPayClient"). This method does not invoke an API call, it is a helper function only.

The signatures generated by this helper function are only valid for the Checkout v2 front-end buttons. Unlike API signing, no timestamps are involved, so the result of this function can be considered a static signature that can safely be placed in your website JS source files and used repeatedly (as long as your payload does not change).

Stringpayload = "{\"storeId\":\"amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\",\"webCheckoutDetails\":{\"checkoutReviewReturnUrl\":\"https://localhost/test/CheckoutReview.php\",\"checkoutResultReturnUrl\":\"https://localhost/test/CheckoutResult.php\"}}";
Stringsignature = client.generateButtonSignature(payload);

Or, if you want to use a JSONObject:

JSONObjectpayload = newJSONObject();
payload.put("storeId", "amzn1.application-oa2-client.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
JSONObjectwebCheckoutDetails = newJSONObject();
webCheckoutDetails.put("checkoutReviewReturnUrl", "https://localhost/test/CheckoutReview.php");
webCheckoutDetails.put("checkoutResultReturnUrl", "https://localhost/test/CheckoutResult.php");
payload.put("webCheckoutDetails", webCheckoutDetails);
Stringsignature = client.generateButtonSignature(payload);

In-Store API

Please contact your Amazon Pay Account Manager before using the In-Store API calls in a Production environment to obtain a copy of the In-Store Integration Guide.

Making a merchantScan request

JSONObjectscanPayload = newJSONObject();
scanPayload.put("scanData", "UKhrmatMeKdlfY6b");
scanPayload.put("scanReferenceId", "0b8fb271-2ae2-49a5-b35d890");
scanPayload.put("merchantCOE", "DE");
scanPayload.put("ledgerCurrency", "EUR");
AmazonPayResponseresponse = null;
JSONObjectscanResponse = null;
try {
InstoreClientclient = newInstoreClient(payConfiguration);
response = instoreClient.merchantScan(scanPayload);
scanResponse = response.getResponse();
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
StringchargePermissionId = scanResponse.getString("chargePermissionId");

Making a charge request

JSONObjectchargePayload = newJSONObject();
JSONObjectchargeTotal = newJSONObject();
chargeTotal.put("currencyCode", "EUR");
chargeTotal.put("amount", 2);
chargePayload.put("chargeTotal", chargeTotal);
chargePayload.put("chargePermissionId", "S02-8295796-8107357");
chargePayload.put("chargeReferenceId", "chargeReferenceId-2");
chargePayload.put("softDescriptor", "amzn-store");
JSONObjectchargeResponse = null;
try {
chargeResponse = instoreClient.charge(scanPayload).getResponse();
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
StringchargeId = chargeResponse.getString("chargeId");

Making a merchantScan request with the auth token

JSONObjectscanPayload = newJSONObject();
scanPayload.put("scanData", "UKhrmatMeKdlfY6b");
scanPayload.put("scanReferenceId", "0b8fb271-2ae2-49a5-b35d890");
scanPayload.put("merchantCOE", "DE");
scanPayload.put("ledgerCurrency", "EUR");
JSONObjectscanResponse = null;
try {
scanResponse = instoreClient.merchantScan(scanPayload).getResponse();
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
StringchargePermissionId = scanResponse.getString("chargePermissionId");

Authorization Tokens API (Advanced Use-Cases Only)

Please note that your Solution Provider account must have a pre-existing relationship (valid and active API V1-style MWS authorization token) with the merchant account in order to use this function.

AmazonPayClientclient;
PayConfigurationpayConfiguration;
AmazonPayResponseresponse;
StringmwsAuthToken = /* the third part mws auth token */;
StringmerchantId = /* the third party merchant id */; StringprivateKey = /* your private key */;
StringpublicKeyId = /* your public key id */;
try {
payConfiguration = newPayConfiguration();
payConfiguration.setRegion(Region.EU). // select your regionsetEnvironment(Environment.LIVE). // must be livesetPrivateKey(privateKey).
setPublicKeyId(publicKeyId);
client = newAmazonPayClient(payConfiguration);
response = client.getAuthorizationToken(mwsAuthToken, merchantId, null);
// If OK response.getStatus() shall be 200// If OK response.getResponse() provides the mwsAuthToken
} catch (Exceptione) {
// System.out.println(e.getMessage());/* handle Exception here */
}

Manual Signing (Advanced Use-Cases Only)

This SDK provides the ability to help you manually sign your API requests if you want to use your own code for sending the HTTPS request over the Internet.

JSONObjectscanPayload = newJSONObject();
scanPayload.put("scanData", "UKhrmatMeKdlfY6b");
scanPayload.put("scanReferenceId", "0b8fb271-2ae2-49a5-b35d890");
scanPayload.put("merchantCOE", "DE");
scanPayload.put("ledgerCurrency", "EUR");
AmazonPayResponseresponse = null;
JSONObjectscanResponse = null;
RequestSignerrequestSigner = null;
try {
requestSigner = newRequestSigner(payConfiguration);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
URIscanUri = newURI("https://pay-api.amazon.com/sandbox/in-store/v1/merchantScan");
Map<String, List<String>> queryParametersMap = newHashMap<>();
Map<String, String> header = newHashMap<String, String>();
Map<String, String> postSignedHeaders = null;
try {
postSignedHeaders = requestSigner.signRequest(scanUri, "POST", queryParametersMap, scanPayload.toString(), header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}
HttpURLConnectionconn = (HttpURLConnection)scanUri.toURL().openConnection();
for (Map.Entry<String, String> entry : postSignedHeaders.entrySet()) {
conn.setRequestProperty(entry.getKey(), entry.getValue());
}
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStreamWriterout = newOutputStreamWriter(conn.getOutputStream());
out.write(scanPayload.toString());
out.close();
intresponseCode = conn.getResponseCode();
BufferedReaderin;
if (responseCode < HttpURLConnection.HTTP_BAD_REQUEST) {
in = newBufferedReader(newInputStreamReader(conn.getErrorStream()));
} else {
in = newBufferedReader(newInputStreamReader(conn.getInputStream()));
}
StringinputLine;
StringBufferresponse = newStringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine).append("\n");
}
StringchargePermissionId = JSONObject.fromObject(response.toString()).getString("chargePermissionId");

Reporting APIs code samples

Amazon Checkout v2 Reporting APIs - GetReports API

AmazonPayResponseresponse = null;
Map<String, List<String>> queryParameters = newHashMap<>();
List<String> reportTypes = newArrayList<>();
reportTypes.add("_GET_FLAT_FILE_OFFAMAZONPAYMENTS_SETTLEMENT_DATA_");
List<String> processingStatuses = newArrayList<>();
processingStatuses.add("COMPLETED");
queryParameters.put("reportTypes", reportTypes);
queryParameters.put("reportTypes", processingStatuses);
try {
response = webstoreClient.getReports(queryParameters);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - GetReportById API

AmazonPayResponseresponse = null;
StringreportId = "1234567890";
try {
response = webstoreClient.getReportById(reportId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - GetReportDocument API

AmazonPayResponseresponse = null;
StringreportDocumentId = "1234567890";
try {
response = webstoreClient.getReportDocument(reportDocumentId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - GetReportSchedules API

AmazonPayResponseresponse = null;
StringreportTypes = "_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_,_GET_FLAT_FILE_OFFAMAZONPAYMENTS_BILLING_AGREEMENT_DATA_";
try {
response = webstoreClient.getReportSchedules(reportTypes);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - GetReportScheduleById API

AmazonPayResponseresponse = null;
StringreportScheduleId = "1234567890";
try {
response = webstoreClient.getReportScheduleById(reportScheduleId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - CreateReport API

AmazonPayResponseresponse = null;
JSONObjectrequestPayload = newJSONObject();
requestPayload.put("reportType", "_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_");
requestPayload.put("startTime", "20221114T074550Z");
requestPayload.put("endTime", "20221202T150350Z");
Map<String, String> header = newHashMap<String, String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
try {
response = webstoreClient.createReport(requestPayload, header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - CreateReportSchedule API

AmazonPayResponseresponse = null;
JSONObjectrequestPayload = newJSONObject();
requestPayload.put("reportType", "_GET_FLAT_FILE_OFFAMAZONPAYMENTS_ORDER_REFERENCE_DATA_");
requestPayload.put("scheduleFrequency", "P14D");
requestPayload.put("nextReportCreationTime", "20221202T150350Z");
requestPayload.put("deleteExistingSchedule", "false");
Map<String, String> header = newHashMap<String, String>();
header.put("x-amz-pay-idempotency-key", UUID.randomUUID().toString().replace("-", ""));
try {
response = webstoreClient.createReportSchedule(requestPayload, header);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

Amazon Checkout v2 Reporting APIs - CancelReportSchedule API

AmazonPayResponseresponse = null;
StringreportScheduleId = "1234567890";
try {
response = webstoreClient.cancelReportSchedule(reportScheduleId);
} catch (AmazonPayClientExceptione) {
e.printStackTrace();
}

About

Amazon Pay API SDK (Java)

Resources

Code of conduct

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages