1

I am trying to call sp-api put item request and below is my code

var amz_url = "https://api.amazon.com/auth/o2/token",
                grant_type = "refresh_token",
                refresh_token = "{refreshtoken}",
                client_id = "amzn1.application-oa2-client.e87c20f1bc464aad8652******",
                client_secret = "46b8fbaef6285e8245b3a99d5a15ac8773e9d775bca44cb2220738a5f1*****";

authorization code

            let headers = ({
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': '*/*',
                'Accept-Encoding': 'gzip, deflate, br',
                'Connection': 'keep-alive',
                'Cache-Control': 'no-cache',
                'Host': 'api.amazon.com'
            });

            let response = https.post({
                url: amz_url,
                body: { grant_type: '' + grant_type + '', refresh_token: '' + refresh_token + '', client_id: '' + client_id + '', client_secret: '' + client_secret + '' },
                headers: headers
            });

            log.debug("resp-code", response.code);
            log.debug("resp-body", JSON.parse(response.body).refresh_token);

            var accessToken = JSON.parse(response.body).access_token;

            //log.debug('Response is ', accessToken); //token retrieved successfully

All good till here

            // Getting access token - END

            // Getting STS token
            var awsMainAccessKey = "AKIA4OOZPXxxxxxxx",
                awsMainSecretKey = "QbcC9g9ylrEGoy4aEUJ0uMkyq6xxxxxxx";

            var stsResponse = stsRequest(awsMainAccessKey,awsMainSecretKey);

            //Calculating timestamp in ISO 8601  format
            var today = new Date();

            var ISO8601Date = getXAmzDate();
            log.debug('ISO 8601 date format ', ISO8601Date);

            var bodyObj = {},
                condArray = [],
                itemArray = [],
                attributesObj = {},
                marketPlaceId = "A1F83G8C2ARO7P",
                sellerId = "A3F8NJ8FFYFH4O",
                productSKU = "TKR45UVDS";

body hash for this being generated differently than what amazon is expecting

            var bodyObj_final = {
                "productType": "LUGGAGE",
                "requirements": "LISTING",
                "attributes": {
                  "condition_type": [
                    {
                      "value": "new_new",
                      "marketplace_id": marketPlaceId
                    }
                  ],
                  "item_name": [
                    {
                      "value": "AmazonBasics 16 Underseat Spinner Carry-On",
                      "language_tag": "en_US",
                      "marketplace_id": marketPlaceId
                    }
                  ]
                }
            }

            bodyObj.productType = "LUGGAGE";
            //bodyObj.productType = "LUGGAGE";

            condArray.push({
                "value": "new_new",
                "marketplace_id": marketPlaceId
            });

            itemArray.push({
                "value": "DC Basics 16 Inches rterdfertr",
                "language_tag": "en_UK",
                "marketplace_id": marketPlaceId
            });

            attributesObj.condition_type = condArray;

            attributesObj.item_name = itemArray;

            bodyObj.attributes = attributesObj;

            var secToken = stsResponse.Credentials.SessionToken;

            method = 'PUT';

            var contenthash = "beaead3198f7da1e70d03ab969765e0821b24fc913697e929e726aeaebf0eba3";

Canonical uri and query string

            canonical_uri = encodeURI('/listings/2021-08-01/items/' + sellerId +'/'+productSKU);

            //canonical_uri = '';

            canonical_querystring = encodeURI('marketplaceIds')+'='+encodeURI('A1F83G8C2ARO7P');
            //canonical_querystring = '';

            var hmacsha256Data = CryptoJS.SHA256(JSON.stringify(bodyObj_final));
            var payload_hash = CryptoJS.enc.Hex.stringify(hmacsha256Data);

            //canonical_headers = 'host:' + 'sellingpartnerapi-eu.amazon.com' + '\n' + 'x-amz-access-token:' + accessToken + '\n' + 'x-amz-date:' + ISO8601Date + '\n';

            canonical_headers = 'host:' + 'sellingpartnerapi-eu.amazon.com' + '\n' + 'x-amz-content-sha256:' + contenthash + '\n'+ 'x-amz-date:' + ISO8601Date + '\n'+ 'x-amz-security-token:' + secToken + '\n';


            signed_headers = "host;x-amz-content-sha256;x-amz-date;x-amz-security-token";

            //log.debug('Payload hash data ', hmacsha256Data);
            log.debug('Payload payload_hash ', payload_hash);

            var paylhash = "31ff10db41d2c210f7beb1adcd5b71c5ab2ec7ed13ad3972be88ff06db177aed";

            //var paylhash = "209c90ceefe76183a6d038fd4474a0d2bc326bfea21b72722474f8e8f395c263";

            //var paylhash = "1782d2d6f688ed659a8a0b511d97525843bc9d727c4d792b37c29e67df57fc8f";

            canonical_request = method + '\n' + canonical_uri + '\n' + canonical_querystring + '\n' + canonical_headers + '\n' + signed_headers + '\n' + paylhash;

            log.debug('URI String ', canonical_request);

            /*************** TASK 2: CREATE THE STRING TO SIGN************* */

            var monthStr = (today.getUTCMonth()+1),
                dayStr = today.getUTCDate();

            var datestamp = today.getUTCFullYear() + '' + (monthStr>9?monthStr:('0'+monthStr)) + '' + (dayStr>9?dayStr:('0'+dayStr));

            region = 'eu-west-1';
            service = 'execute-api';
            algorithm = 'AWS4-HMAC-SHA256';

            var canonicalsha256Data = CryptoJS.SHA256(canonical_request);
            var canonical_hash = CryptoJS.enc.Hex.stringify(canonicalsha256Data);

            //log.debug('canonicalsha256Data is ', canonicalsha256Data);

            log.debug('canonical_hash is ', canonical_hash);

            credential_scope = datestamp + '/' + region + '/' + 'execute-api' + '/' + 'aws4_request';
            string_to_sign = algorithm + '\n' + ISO8601Date + '\n' + credential_scope + '\n' + canonical_hash;

            log.debug('String to Sign ', string_to_sign);

            /************* TASK 3: CALCULATE THE SIGNATURE *************/

            //stsResponse

            secret_key = stsResponse.Credentials.SecretAccessKey; //secret key for iam user 
            access_key = stsResponse.Credentials.AccessKeyId; // access key for iam user

            signing_key = getSignatureKey(secret_key, datestamp, region, service);

            var signingsha256Data = CryptoJS.HmacSHA256(string_to_sign, signing_key);

            var signature = CryptoJS.enc.Hex.stringify(signingsha256Data);

            log.debug('Final signature is ', signature);

            /************* TASK 4: ADD SIGNING INFORMATION TO THE REQUEST *************/
            authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature;

            

            log.debug('authorization_header is ', authorization_header);

            headers = { 
                'host': 'sellingpartnerapi-eu.amazon.com', 
                'x-amz-access-token': accessToken,
                'X-Amz-Security-Token': secToken,
                'x-Amz-Content-Sha256': contenthash,
                'x-amz-date': ISO8601Date, 
                'Authorization': authorization_header, 
                'Content-Type': 'application/json',
                'ACCEPT': '*/*'
            }

            /************** SEND THE REQUEST **************/
            request_url = 'https://sellingpartnerapi-eu.amazon.com'+canonical_uri+'?' + canonical_querystring;

            //request_url = 'https://sellingpartnerapi-eu.amazon.com/listings/2021-08-01/items/A3F8NJ8FFYFH4O/ABC123'+'?' + canonical_querystring;

            log.debug('Request URL is ', request_url);

            var response_end = https.put({
                url: request_url,
                headers: headers,
                body : bodyObj
            });

            log.debug('Response Code is ', response_end.code); 
            log.debug('Response is ', response_end.body); 

I am getting response as 400 :{ "errors": [ { "code": "InvalidInput", "message": "Invalid Input", "details": "" } ] }

Other questions I have, I am trying to generate payload hash but amazon is expecting different thing, when I replace amazon expected payload it works(hard coded as paylhash in this script) otherwise 403 error

Did anyone came across same issue or if someone can identify what I am doing wrong will be a great help.

2ps
  • 15,099
  • 2
  • 27
  • 47

0 Answers0