I am getting the following error in response while trying to perform the Nestuite upsert operation (https://docs.oracle.com/en/cloud/saas/netsuite/ns-online-help/section_156335203191.html#Using-the-Upsert-Operation) in Node JS :-
Response:
{"type":"https://www.rfc-editor.org/rfc/rfc9110.html#section-15.5.2","title":"Unauthorized","status":401,"o:errorDetails":[{"detail":"Invalid login attempt. For more details, see the Login Audit Trail in the NetSuite UI at Setup > Users/Roles > User Management > View Login Audit Trail.","o:errorCode":"INVALID_LOGIN"}]}
Note: The credentials are correct because it is working perfectly in Postman with TBA and returns 204 response code. Not sure what's going wrong when I try to do the same using Node JS.
Node JS code:
const fetch = require('node-fetch');
const crypto = require('crypto');
function upsertOperation(externalId, body) {
const baseUrl = `https://${NETSUITE_ACCOUNT_ID}.suitetalk.api.netsuite.com/services/rest/record/v1/${RESOURCE}`;
const oauthNonce = crypto.randomBytes(32).toString('hex');
const oauthTimestamp = Math.floor(Date.now() / 1000);
const oauthSignatureMethod = 'HMAC-SHA256';
const oauthVersion = '1.0';
const realm = `${REALM}` // Note: Replaced space with underscore and lower case letters with upper case letters in netsuite account id. Not provided exatct value here.
const oauthParameters = {
oauth_consumer_key: CONSUMER_KEY,
oauth_token: ACCESS_TOKEN,
oauth_nonce: oauthNonce,
oauth_timestamp: oauthTimestamp,
oauth_signature_method: oauthSignatureMethod,
oauth_version: '1.0'
};
const sortedParameters = Object.keys(oauthParameters)
.sort()
.map((key) => `${key}=${oauthParameters[key]}`)
.join('&');
const signatureBaseString = `PUT&${encodeURIComponent(baseUrl)}&${encodeURIComponent(sortedParameters)}`;
const signingKey = `${CONSUMER_SECRET}&${ACCESS_TOKEN_SECRET}`;
const hmac = crypto.createHmac('sha256', signingKey);
hmac.update(signatureBaseString);
const oauthSignature = hmac.digest('base64');
const headers = {
'Prefer': 'transient',
'Content-Type': 'application/json',
'Authorization': `OAuth realm="${realm}",oauth_signature="${oauthSignature}",oauth_nonce="${oauthNonce}",oauth_signature_method="${oauthSignatureMethod}",oauth_consumer_key="${CONSUMER_KEY}",oauth_token="${ACCESS_TOKEN}",oauth_timestamp="${oauthTimestamp}",oauth_version="${oauthVersion}"`
};
fetch(baseUrl+'/eid:' + externalId, {
method: 'PUT',
headers: headers,
body: JSON.stringify(body),
redirect: 'follow'
})
.then((response) => response.json())
.then((data) => {
console.log('data: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Error upsertOperation:', error);
});
}
The entire URL needs to be included in the URI encoding, and the HMAC signing request. However, you're leaving out the '/eid:' + externalId
which forms part of the final URL you're accessing. Try it with that included in baseUrl
.