Created
November 13, 2016 23:28
-
-
Save cyberwombat/bc22fcd44037b7f8c1920432636f9cd5 to your computer and use it in GitHub Desktop.
Walmart API authentication in Node
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { createSign, randomBytes } from 'crypto' | |
import axios from 'axios' | |
import { resolve } from 'url' | |
const PK_HEADER = '\n-----BEGIN PRIVATE KEY-----\n' | |
const PK_FOOTER = '\n-----END PRIVATE KEY-----\n' | |
const BASE_URL = 'https://marketplace.walmartapis.com/' | |
const WALMART_CONSUMER = "b68d2a72...."; | |
const WALMART_SECRET = "MIICeAIBADANBgkqhkiG9w0BAQEFAA......" | |
const WALMART_CHANNEL = '0f7274e4-0514-4346-b39d-af100936d' | |
function generateCorrelationId () { | |
return randomBytes(16).toString('hex') | |
} | |
function generateSignature (url, method, timestamp) { | |
const privateKey = `${PK_HEADER}${WALMART_SECRET}${PK_FOOTER}` | |
const stringToSign = WALMART_CONSUMER + '\n' + | |
url + '\n' + | |
method.toUpperCase() + '\n' + | |
timestamp + '\n' | |
const sign = createSign('RSA-SHA256') | |
sign.update(stringToSign) | |
return sign.sign(privateKey, 'base64') | |
} | |
export function doRequest (endpoint, method) { | |
const url = resolve(BASE_URL, endpoint) | |
const timestamp = Date.now() | |
const signature = generateSignature(url, method, timestamp) | |
const headers = { | |
'WM_SVC.NAME': 'Walmart Marketplace', | |
'WM_CONSUMER.ID': config.walmart.consumer, | |
'WM_SEC.TIMESTAMP': timestamp, | |
'WM_SEC.AUTH_SIGNATURE': signature, | |
'WM_QOS.CORRELATION_ID': generateCorrelationId(), | |
'WM_CONSUMER.CHANNEL.TYPE': WALMART_CHANNEL | |
} | |
return axios({ | |
method: method, | |
url: url, | |
timeout: 1000, | |
headers: headers | |
}) | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { doRequest } from 'api' | |
doRequest('/v2/feeds', 'get') | |
.then(function (response) { | |
console.log(response) | |
}) | |
.catch(function (error) { | |
console.log(error) | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It save my life. Thank you!