Skip to content

Instantly share code, notes, and snippets.

@velizarn
Last active October 16, 2019 14:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save velizarn/64906656446e4b34dd364eb2e86353bd to your computer and use it in GitHub Desktop.
Save velizarn/64906656446e4b34dd364eb2e86353bd to your computer and use it in GitHub Desktop.
Obtain OAuth token in Nodejs for SalesForce Commerce Cloud OCAPI (previously Demandware)
const https = require('https')
const headers = {
'Authorization' : 'Basic YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhOmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==',
'Content-Type' : 'application/x-www-form-urlencoded'
}
const optionsget = {
host : 'account.demandware.com',
port : 443,
path : '/dw/oauth2/access_token?grant_type=client_credentials',
method : 'POST',
headers: headers
}
let reqGet = https.request(optionsget, (res) => {
res.on('data', (d) => {
console.info('POST result:'+d.toString())
console.info('Access token: \n')
process.stdout.write(JSON.parse(d).access_token)
})
})
reqGet.end()
reqGet.on('error', (e) => { console.error(e) })
// https://isolasoftware.it/2012/05/28/call-rest-api-with-node-js/
const optionsget = {
host : 'account.demandware.com',
port : 443,
path : '/dw/oauth2/access_token?grant_type=client_credentials',
method : 'POST',
headers: {
'Authorization' : 'Basic YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhOmFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYQ==',
'Content-Type' : 'application/x-www-form-urlencoded'
}
}
let getToken = () => {
return new Promise((resolve, reject) => {
try {
require('https').get(optionsget, (res) => {
let body = '';
res.on('data', (chunk) => { body += chunk })
res.on('end', () => {
let response = JSON.parse(body)
resolve( response )
})
}).on('error', (e) => { return reject(e + '') })
} catch (e) { return reject(e + '') }
})
}
getToken()
.then((response) => {
console.log('Access token (Expires in ' + response.expires_in + '): \n\n' + response.access_token)
})
.catch((e) => { console.error(e + '') })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment