Skip to content

Instantly share code, notes, and snippets.

@candelatech
Last active September 2, 2021 00:53
Show Gist options
  • Save candelatech/5b275034400a4d8f78390f27d6cbf0e5 to your computer and use it in GitHub Desktop.
Save candelatech/5b275034400a4d8f78390f27d6cbf0e5 to your computer and use it in GitHub Desktop.
Authenticating with the Walmart.io API in Node.js
make_wm_request: async function({method,url,http_body,vendor_id,consumer_id,consumer_pk,channel_type} = {}){
return new Promise(async function(resolve,reject){
//if you don't have a PEM-formatted private key (we didn't), generate one real quick
var pk_chunked = chunkSubstr(consumer_pk, 64).join("\n")
pk_chunked = "-----BEGIN PRIVATE KEY-----\n" + pk_chunked + "\n-----END PRIVATE KEY-----\n"
var epoch_timestamp = Date.now()
//generate the payload to be signed
var input = consumer_id + "\n" + url + "\n" + method + "\n" + epoch_timestamp + "\n"
//you'll need to require crypto somewhere along the way
const sign = crypto.createSign('SHA256');
sign.write(input);
sign.end();
const sig = sign.sign(pk_chunked, 'base64');
var headers = {
"Accept":"application/json",
"WM_SVC.NAME":"Warehouse Supplier Services",
"WM_QOS.CORRELATION_ID":"0000001",
"WM_SEC.TIMESTAMP":epoch_timestamp,
"WM_SEC.AUTH_SIGNATURE":sig,
"WM_CONSUMER.ID":consumer_id,
"WM_CONSUMER.CHANNEL.TYPE":channel_type,
"Content-Type":"application/json"
}
var options = {
method: method,
url: url,
headers: headers
body: http_body
}
//use your favorite request package here (axios, request, etc)
request(options,function(e,r,body){
if (e)
resolve({error:e,message:"Request failed"})
else
resolve({success:true,result:body})
})
//breaks up a string into chunks of a certain size. Returns array of strings
function chunkSubstr(str, size) {
const numChunks = Math.ceil(str.length / size)
const chunks = new Array(numChunks)
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size)
}
return chunks
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment