This Sample Solution provides all required resources to deploy to the AWS cloud a fully functional SP-API application that implements the B2B repricing use case end-to-end. Use this application to test the proposed solution, do changes and/or integrate it to your own product.
The Selling Partner API for Pricing helps you programmatically retrieve product pricing and offer pricing information for Amazon Marketplace products.
If you haven't already, we recommend you to navigate the following resources:
- Product Pricing API v2022-05-01 reference
- Product Pricing API Use Case Guide
- Listings Items API v2021-08-01 Reference
- Listings API Use Case Guide
- Listings API - Manage Advanced Multiple-Offer and Multiple-Fulfillment Use Cases
This Sample Solution implements a re-pricing workflow that reacts to incoming B2B_ANY_OFFER_CHANGED notifications and calculates a new competitive price for the related selling partner's SKUs in order to achieve B2B featured offer eligibility. If the new calculated price is above the minimum threshold defined by the selling partner, the solution executes a price change using the Feeds API workflow.
The solution consists of the following components:
- A Step Functions state machine with a fully functional re-pricing workflow
- Lambda functions that support each of the steps of the state machine
- An SQS queue to receive B2B_ANY_OFFER_CHANGED notifications
- A DynamoDB table to store re-pricing rules for the selling partner's SKUs
- A Secrets Manager secret to securely store SP-API app credentials
The application waits for incoming SP-API B2B_ANY_OFFER_CHANGED notifications. These events are processed by the SPAPIProcessNotificationLambdaFunction, which starts a Step Functions state machine execution with the re-pricing logic.
The state machine retrieves from the database all the selling partner's SKUs associated to the ASIN of the notification. Next, each SKU is processed individually. If not present in the notification payload, the SPAPIFetchPriceLambdaFunction retrieves additional pricing information for the SKU using the Product Pricing API. The SPAPICalculateNewPriceLambdaFunction calculates a new competitive price using the price change rule specified for the SKU in the database. The supported rules are "fixed" for a fixed deduction to the featured offer price (e.g. featured offer price - $0.01), and "percentage" for a percentage deduction to the featured offer price (e.g. featured offer price - 5%). Finally, if the new calculated price is above the specified minimum threshold set in the database, the SPAPISubmitPriceLambdaFunction submits the price change using the Feeds API.
The pre-requisites for deploying the Sample Solution App to the AWS cloud are:
- Registering as a developer for SP-API, and registering an SP-API application
- An IAM user with permissions to create a new user, a policy, and attach it to the user
- If you don't have one, you can create it following the steps under Usage - 2. Configure Sample Solution App's IAM user
- The AWS CLI
- If not present, it will be installed as part of the deployment script
- NodeJS 14.15.0 or later
- Required by AWS CDK stack for the sample solution deployment.
- If not present, it will be installed as part of the deployment script.
- GitBash
- in case you use Windows in order to run the deployment script.
To allow the Sample Solution App to connect to SP-API, the config file has to be updated to match the set-up of your SP-API application.
- Open app.config file and replace all occurrences of
<dev_value>
following the instructions below: - Update
ClientId
andClientSecret
attribute values with Client Id and Client Secret of the SP-API application respectively - Update
RefreshToken
attribute value with the refresh token of the selling partner you will be using for testing - Update
RegionCode
attribute value with the region of the selling partner you will be using for testing. Valid values areNA
,EU
,FE
for production usage orNA_SANDBOX
,EU_SANDBOX
andFE_SANDBOX
for Sandbox testing.
Note: While updating the config file, don't leave blank spaces before and after
=
, and don't use quotation marks
ClientId=amzn1.application-oa2-client.abc123def456xyz789
ClientSecret=amzn1.oa2-cs.v1.abc123def456xyz789
RefreshToken=Atzr|Abc123def456xyz789
RegionCode=NA_SANDBOX
In order to execute the deployment script, an IAM user with the appropriate permissions is needed. To create a new IAM policy with the required permissions, follow the steps below.
- Open the AWS console
- Navigate to IAM Policies console
- Click Create policy
- Next to Policy editor, select JSON and replace the default policy with the JSON below
- replace with your account id as needed.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "SPAPISampleAppIAMPolicy",
"Effect": "Allow",
"Action": [
"iam:CreateUser",
"iam:DeleteUser",
"iam:CreatePolicy",
"iam:DeletePolicy",
"iam:AttachUserPolicy",
"iam:DetachUserPolicy",
"iam:CreateAccessKey",
"iam:DeleteAccessKey",
"iam:GetRole",
"iam:CreateRole",
"iam:TagRole",
"iam:AttachRolePolicy",
"iam:PutRolePolicy",
"iam:DeleteRole",
"iam:DeleteRolePolicy",
"iam:DetachRolePolicy",
"iam:PassRole"
],
"Resource": [
"arn:aws:iam::<aws_account_id_number>:user/*",
"arn:aws:iam::<aws_account_id_number>:policy/*",
"arn:aws:iam::<aws_account_id_number>:role/*"
]
},
{
"Sid": "SPAPISampleAppCloudFormationPolicy",
"Effect": "Allow",
"Action": [
"cloudformation:*",
"ecr:*",
"ssm:*"
],
"Resource": [
"arn:aws:cloudformation:us-east-1:<aws_account_id_number>:stack/CDKToolkit/*",
"arn:aws:ecr:us-east-1:<aws_account_id_number>:repository/cdk*",
"arn:aws:ssm:us-east-1:<aws_account_id_number>:parameter/cdk-bootstrap/*",
"arn:aws:cloudformation:us-east-1:<aws_account_id_number>:stack/sp-api-app*"
]
},
{
"Sid": "SPAPISampleAppCloudFormationS3Policy",
"Effect": "Allow",
"Action": [
"s3:*"
],
"Resource": [
"arn:aws:s3:::cdk*",
"arn:aws:s3:::sp-api-app-bucket*"
]
}
]
}
- Click Next
- Select a name for your policy. Take note of this value as you will need it in the next section.
- Review the changes and click Create policy
To create a new IAM user with the required permissions, follow the steps below.
- Open the AWS console
- Navigate to IAM Users console
- Click Create user
- Select a name for your user
- In the Set permissions page, select Attach policies directly
- In the Permissions policies, search for the policy created in I. Create IAM policy section. Select the policy, and click Next
- Review the changes and click Create user
Security credentials for the IAM user will be requested during the deployment script execution. To create a new access key pair, follow the steps below. If you already have valid access key and secret access key, you can skip this section.
- Open the AWS console
- Navigate to IAM Users console
- Select your IAM user, which has
IAMFullAccess
permissions - Go to Security credentials tab
- Under Access keys, click Create access key
- In Access key best practices & alternatives page, select Command Line Interface (CLI)
- Acknowledge the recommendations, and click Next
- Click Create access key
- Copy
Access key
andSecret access key
. This is the only time that these keys can be viewed or downloaded, and you will need them while executing the deployment script - Click Done
The deployment script will create a Sample Solution App in the AWS cloud. To execute the deployment script, follow the steps below.
- Identify the deployment script for the programming language you want for your Sample Solution App.
- For example, for the java application the file is app/scripts/java/java-app.sh
- Execute the script from your terminal or Git Bash
- For example, to execute the Java deployment script in a Unix-based system or using Git Bash, run
bash java-app.sh
- For example, to execute the Java deployment script in a Unix-based system or using Git Bash, run
- Wait for the CloudFormation stack creation to finish
- Navigate to CloudFormation console
- Wait for the stack named sp-api-app-<language>-random_suffix to show status
CREATE_COMPLETE
The deployment script creates a Sample Solution App in the AWS cloud. The solution consists of a Step Functions state machine with a fully functional workflow. To test the sample solution, follow the steps below.
- Open the AWS console
- Navigate to DynamoDB console
- Under Tables, click on Explore items
- Select the table created by the deployment script, named SPAPISellerItemsTable-random_suffix
- Select Create new item and add the following attributes with the corresponding value:
- ASIN (Type
String
): The ASIN that you will use for testing - SKU (Type
String
): The SKU that you will use for testing - SellerId (Type
String
): The id of the seller that you will use for testing - MarketplaceId (Type
String
): The id of the marketplace that you will use for testing - Condition (Type
String
): The condition of the item that you will use for testing. Valid values:New
,Used
- IsFulfilledByAmazon (Type
Boolean
):true
if the item that you will use for testing is fulfilled by Amazon,false
otherwise - PriceRule (Type
List of Map
): List of map that contains multiple price rules for this SKU- PriceChangeRule (Type
String
): The price change rule of the SKU. Valid values:FIXED
,PERCENTAGE
- PriceChangeRuleAmount (Type
Number
): The price change rule amount. This amount will be related to the price change rule chosen in step 7. For example, if thePriceChangeRuleAmount
is set to10
, it could be interpreted as10 USD
or10%
depending on the value of thePriceChangeRule
. - MinThreshold (Type
Number
): The minimum list price for the SKU. Example: 10 (= 10 USD/EUR) - OfferType (Type
String
): The offerType of this rule . Valid values:B2B
- QuantityTier (Type
Number
): The Quantity Tier of this rule . Use1
for B2B price.
- PriceChangeRule (Type
- In the Create Item page select JSON view on the right side, copy and paste the item below and click in create item.
- ASIN (Type
{"ASIN":{"S":"B08R3V9XXX"},"SKU":{"S":"SKU1"},"Condition":{"S":"New"},"IsFulfilledByAmazon":{"BOOL":false},"MarketplaceId":{"S":"ATVPDKIKX0DER"},"PriceRule":{"L":[{"M":{"OfferType":{"S":"B2B"},"QuantityTier":{"N":"1"},"MinThreshold":{"N":"9"},"PriceChangeRule":{"S":"PERCENTAGE"},"PriceChangeRuleAmount":{"N":"1"}}},{"M":{"OfferType":{"S":"B2B"},"QuantityTier":{"N":"2"},"MinThreshold":{"N":"7"},"PriceChangeRule":{"S":"FIXED"},"PriceChangeRuleAmount":{"N":"1"}}}]},"SellerId":{"S":"AMY6FXXABCD"}}
- Navigate to SQS console
- Select the SQS queue created by the deployment script, named sp-api-notifications-queue-random_suffix
- Select Send and receive messages
- Under Message body, insert the following simplified notification body. Replace all attributes with the correct values of the ASIN and SKU that you will use for testing
{ "notificationType": "B2B_ANY_OFFER_CHANGED", "payload": { "b2bAnyOfferChangedNotification": { "sellerId": "ABCDEFGH", "offerChangeTrigger": { "marketplaceId": "ATVPDKIKX0DER", "asin": "ASIN1234", "itemCondition": "New", "timeOfOfferChange": "2020-09-23T21:30:13.409Z" }, "summary": { "numberOfOffers": [ { "condition": "New", "fulfillmentChannel": "Merchant", "offerCount": 3 } ], "buyBoxEligibleOffers": [ { "condition": "New", "fulfillmentChannel": "Merchant", "offerCount": 3 } ], "buyBoxPrices": [ { "condition": "New", "fulfillmentChannel": "Merchant", "offerType": "B2B", "quantityTier": 1, "listingPrice": { "amount": 334.23, "currencyCode": "USD" }, "shipping": { "amount": 4.49, "currencyCode": "USD" }, "landedPrice": { "amount": 338.72, "currencyCode": "USD" } }, { "condition": "New", "fulfillmentChannel": "Merchant", "offerType": "B2B", "quantityTier": 2, "listingPrice": { "amount": 332.99, "currencyCode": "USD" }, "shipping": { "amount": 4.49, "currencyCode": "USD" } }, { "condition": "New", "fulfillmentChannel": "Merchant", "offerType": "B2B", "quantityTier": 5, "discountType": "QUANTITY_DISCOUNT", "listingPrice": { "amount": 330.99, "currencyCode": "USD" }, "shipping": { "amount": 4.49, "currencyCode": "USD" } } ] }, "offers": [ { "sellerId": "ABCDEFGH", "subCondition": "New", "sellerFeedbackRating": { "feedbackCount": 1, "sellerPositiveFeedbackRating": 0 }, "shippingTime": { "minimumHours": 24, "maximumHours": 48, "availabilityType": "available", "availableDate": "2020-07-13T19:42:04.284Z" }, "listingPrice": { "amount": 550.99, "currencyCode": "USD" }, "shipping": { "amount": 4.49, "currencyCode": "USD" }, "shipsFrom": { "country": "US" }, "isFulfilledByAmazon": false, "isBuyBoxWinner": false, "conditionNotes": "New in box", "primeInformation": { "isPrime": true, "isNationalPrime": true }, "isFeaturedMerchant": true } ] } }}
- Click Send message
- Navigate to Step Functions console
- Select the state machine created by the deployment script, named SPAPIStateMachine-random_suffix
- Under Executions, you will see a workflow for the notification submitted through SQS
- To check the workflow status and navigate into the individual steps, select the workflow and use the Graph view and Step Detail panels
The deployment script also creates a Lambda function that subscribes selling partners to notifications. You can integrate this function to your product to easily onboard to the notifications feature. To test the function, follow the steps below.
- Open the AWS console
- Navigate to Lambda console
- Select the notification subscriber function, named SPAPISubscribeNotifications-random_suffix
- Select Test tab
- Under Event JSON, insert the following payload. Replace
RefreshToken
,RegionCode
andNotificationType
with the corresponding values of the selling partner and notification type you want to subscribe to.{ "NotificationType": "ORDER_CHANGE", "RegionCode": "NA|EU|FE", "RefreshToken": "Atzr|Iw..." }
- Click Test
- The function will return
destination Id
andsubscription Id
The deployment script creates a number of resources in the AWS cloud which you might want to delete after testing the solution. To clean up these resources, follow the steps below.
- Identify the clean-up script for the programming language of the Sample Solution App deployed to the AWS cloud.
- For example, for the Java application the file is app/scripts/java/java-app-clean.sh
- Execute the script from your terminal or Git Bash
- For example, to execute the Java clean-up script in a Unix-based system or using Git Bash, run
bash java-app-clean.sh
- For example, to execute the Java clean-up script in a Unix-based system or using Git Bash, run
If the state machine execution fails, follow the steps below to identify the root-cause and retry the workflow
- Navigate to Step Functions console
- Select the state machine created by the deployment script, named SPAPIStateMachine-random_suffix
- Under Executions, you can use the Status column to identify failed executions
- To troubleshoot errors, select the corresponding workflow execution and use the Graph view and Step Detail panels
- After fixing the issues that caused the error, retry the workflow by clicking on New execution. The original input parameters will be automatically populated
- Click Start execution, and validate the results