Skip to content

Instantly share code, notes, and snippets.

@MendyBerger
Created December 15, 2020 17:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MendyBerger/11ba33861cbc3a3fa9268c673841e403 to your computer and use it in GitHub Desktop.
Save MendyBerger/11ba33861cbc3a3fa9268c673841e403 to your computer and use it in GitHub Desktop.
Messy code but working, connect to Amazon SP-API
/*
This code is full of antipatterns and bad practices!
It's not intended to be used as is but rather as inspiration on how to connect to SP-API,
the only reason I publish this is because I couldn't find anything better online, NOT because its well written code!
*/
// make sure to fill out all the following:
// info from seller central developer page
const refreshToken = "";
const clientId = "";
const clientSecret = "";
// info from the IAM user
const AccessKey = "";
const SecretKey = "";
// info from the IAM role
const RoleArn = '';
const fetch = require("node-fetch");
const URLSearchParams = require("url").URLSearchParams;
const aws4 = require("aws4");
const https = require("https");
const aws = require("aws-sdk");
aws.config = new aws.Config();
aws.config.credentials = new aws.Credentials(AccessKey, SecretKey);
aws.config.getCredentials(function (err) {
if (err) {
console.log(err);
throw new Error("can't login to AWS");
} else {
console.log("Connected to AWS");
}
});
const sts = new aws.STS();
async function getCrossAccountCredentials () {
return new Promise((resolve, reject) => {
const params = {
RoleArn,
RoleSessionName: `postmanSpApi`
};
sts.assumeRole(params, (err, data) => {
if (err) reject(err);
else {
resolve({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
});
}
});
});
}
function getAccessToken2() {
let formData = new URLSearchParams();
formData.append("grant_type", "refresh_token");
formData.append("refresh_token", refreshToken);
formData.append("client_id", clientId);
formData.append("client_secret", clientSecret);
return fetch("https://api.amazon.com/auth/o2/token", {
method: "POST",
body: formData,
})
.then(res => res.json())
.then(res => {
return res.access_token;
});
}
function getOrders3(accessKeyId, secretAccessKey, sessionToken, accessToken) {
return new Promise((resolve, reject) => {
const xAmzDate = new Date().toISOString().replace(/-|:/g, "").substring(0, 15) + "Z";
var opts = {
host: 'sellingpartnerapi-na.amazon.com',
path: '/orders/v0/orders?MarketplaceIds=ATVPDKIKX0DER&CreatedAfter=2010-01-01T05%3A00%3A00.000Z',
service: 'execute-api',
region: 'us-east-1',
signQuery: false,
headers: {
'x-amz-access-token': accessToken,
"x-amz-date": xAmzDate,
"x-amz-security-token": sessionToken,
},
}
aws4.sign(opts, { accessKeyId, secretAccessKey })
const req = https.request(opts, (res) => {
var body = '';
res.on('data', function(chunk) {
body += chunk;
});
res.on('end', function() {
resolve(JSON.parse(body));
});
});
console.log(req);
req.on('error', (e) => {
console.error(e);
});
req.end()
});
}
(async () => {
let info = {
accessKeyId: undefined,
secretAccessKey: undefined,
sessionToken: undefined,
accessToken: undefined,
}
info = await getCrossAccountCredentials();
info.accessToken = await getAccessToken2();
let orders = await getOrders3(info.accessKeyId, info.secretAccessKey, info.sessionToken, info.accessToken);
console.log(orders);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment