Hi Folks,
I'm trying to generate an authenticated URL using Consumer Key and Consumer Secret and signature method is HMAC-SHA256 However getting 401 though I've tested in Postman with consumer key and secret, and it is working fine there.
This code is generating the signed URL to request WooCommerce, but somehow WooCommerce return the 401 and says your signature doesn't match
while creating HMAC using crypto.createHmac i'm passing the consumer secret from Netsuite API Secret.
using crypto.createSecretKey method
const WOO_API_URL = config.WOOCOMMERCE.API_URL;const SIGNATURE_METHOD = config.WOOCOMMERCE.SIGNATURE_METHOD;const VERSION = config.WOOCOMMERCE.VERSION || '1.0';const CONSUMER_KEY = config.WOOCOMMERCE.CONSUMER_KEY;const CONSUMER_SECRET = config.WOOCOMMERCE.CONSUMER_SECRET;
// ==== HELPERS ====// === OPTIONAL: centralize your Secrets Manager IDs here ===const SECRET_ID_CONSUMER_KEY = config.WOOCOMMERCE.API_SECRET_CONSUMER_KEY_ID;const SECRET_ID_CONSUMER_SECRET = config.WOOCOMMERCE.API_SECRET_CONSUMER_SECRET_ID;
/*** Make API call to WooCommerce with OAuth 1.0a authentication* @param {string} method - HTTP method (GET, POST, PUT, DELETE)* @param {string} endpoint - API endpoint* @param {Object} data - Request data (optional)* @returns {Object} - Response object*/makeApiCall: function (method, endpoint, data) { try {
// Validate WOO_API_URL is set if (!WOO_API_URL || WOO_API_URL.trim() === '') { const errorMsg = 'WOO_API_URL is not configured'; common.logExecution('ERROR', 'ir_wc_api', 'makeApiCall', errorMsg); return { success: false, code: 0, data: null, error: errorMsg }; }
// Validate method and endpoint if (!method || !endpoint || typeof endpoint !== 'string' || endpoint.trim() === '') { const errorMsg = 'method or endpoint is not configured'; common.logExecution('ERROR', 'ir_wc_api', 'makeApiCall', errorMsg); return { success: false, code: 0, data: null, error: errorMsg }; }
// Extract query parameters from endpoint if present let cleanEndpoint = endpoint; let queryParams = {}; const endpointParts = endpoint.split('?'); if (endpointParts.length > 1) { cleanEndpoint = endpointParts[0]; const queryString = endpointParts[1]; const pairs = queryString.split('&'); for (let i = 0; i < pairs.length; i++) { const pair = pairs[i].split('='); if (pair.length === 2) { queryParams[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]); } } }
// Build full URL with base URL const fullUrl = WOO_API_URL + cleanEndpoint;
log.debug('makeApiCall => fullUrl', fullUrl);
// Generate OAuth-signed URL const oauthResult = buildWooOAuth1(method, fullUrl, queryParams); const oauthUrl = oauthResult.signedUrl;
if (!oauthUrl || typeof oauthUrl !== 'string' || oauthUrl.trim() === '') { const errorMsg = 'Failed to build OAuth URL'; common.logExecution('ERROR', 'ir_wc_api', 'makeApiCall', errorMsg, { endpoint: endpoint, method: method }); return { success: false, code: 0, data: null, error: errorMsg }; }
common.logExecution('DEBUG', 'ir_wc_api', 'makeApiCall', 'OAuth URL generated', { method: method, endpoint: cleanEndpoint, oauthUrl: oauthUrl.substring(0, 200) + '...' // Log truncated URL });
const requestOptions = { url: oauthUrl, method: method, headers: { 'Content-Type': 'application/json' } };
if (data && (method === 'POST' || method === 'PUT')) { requestOptions.body = JSON.stringify(data); }
log.debug('requestOptions', requestOptions);
// Make the appropriate HTTP request based on method let response; if (method === 'GET') { response = http.get(requestOptions); } else if (method === 'POST') { response = http.post(requestOptions); } else if (method === 'PUT') { response = http.put(requestOptions); } else if (method === 'DELETE') { response = http.delete(requestOptions); } else { response = http.post(requestOptions); }
let responseData = { success: response.code >= 200 && response.code < 300, code: response.code, data: null, error: null };
if (responseData.success) { try { responseData.data = JSON.parse(response.body); } catch (parseError) { responseData.data = response.body; common.logExecution('DEBUG', 'ir_wc_api', 'makeApiCall', 'Response not JSON, using raw body', parseError.message); } } else { responseData.error = response.body; common.logExecution('ERROR', 'ir_wc_api', 'makeApiCall', 'API call failed', { code: responseData.code, error: responseData.error, endpoint: cleanEndpoint }); }
return responseData; } catch (e) { common.logExecution('ERROR', 'ir_wc_api', 'makeApiCall', 'Error making API call', e.message); return { success: false, code: 0, data: null, error: e.message }; }}, /** * Build OAuth 1.0a query params and signature for WooCommerce (HTTP), * then optionally return a full signed URL. * * @returns object */ function buildWooOAuth1(method, url, extraQuery) { if (!method || !url) { throw new Error('buildWooOAuth1 requires method and url'); }
try { const s = getWooSecrets(); const consumerKey = s.consumerKey; const consumerSecret = s.consumerSecret;
// Core OAuth params const oauthParams = { oauth_consumer_key: consumerKey, oauth_signature_method: SIGNATURE_METHOD, oauth_timestamp: String(Math.floor(Date.now() / 1000)), oauth_nonce: makeNonce(), oauth_version: '1.0' };
// Only query-string params participate in signature for WooCommerce HTTP calls const allParams = Object.assign({}, extraQuery || {}, oauthParams); const normalizedParamString = buildNormalizedParamString(allParams); // Build base string const baseString = [ rfc3986Encode(method.toUpperCase()), rfc3986Encode(normalizeUrl(url)), rfc3986Encode(normalizedParamString) ].join('&');
log.debug('normalizedParamString', normalizedParamString); log.debug('normalizeUrl', rfc3986Encode(normalizeUrl(url))); log.debug('baseString', baseString);
// Signing key = consumerSecret + '&' const signingKey = consumerSecret + '&'; const signature = hmacSha256Base64(baseString, signingKey);
const queryWithSig = normalizedParamString + '&oauth_signature=' + signature; log.debug('oAuth Params', queryWithSig); const signedUrl = url + '?' + queryWithSig; log.debug('** signedUrl **', signedUrl);
return { oauthParams: oauthParams, queryString: normalizedParamString, signedUrl: signedUrl }; } catch (error) { log.error('buildWooOAuth1 => error', error.message); return null; } }
function hmacSha256Base64(input, key) { try {
const secretKey = crypto.createSecretKey({ secret: SECRET_ID_CONSUMER_SECRET, encoding: encode.Encoding.UTF_8, });
log.debug('*** secretKey ****', secretKey);
const hmac = crypto.createHmac({ algorithm: crypto.HashAlg.SHA256, key: secretKey });
hmac.update({ input: input, inputEncoding: encode.Encoding.UTF_8 });
// Get Base64-encoded HMAC digest const base64Signature = hmac.digest({ outputEncoding: encode.Encoding.BASE_64 });
// URL-encode the Base64 signature (RFC3986 encoding) for OAuth 1.0a return rfc3986Encode(base64Signature); } catch (e) { log.error('hmacSha256Base64 => error', e.message); return null; } }
// RFC3986 percent-encoding (with explicit encoding of ~) function rfc3986Encode(str) { // First, encode the string using encodeURIComponent (standard encoding) let encoded = encodeURIComponent(str); // Additionally, replace other characters that require RFC3986 encoding return encoded.replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16).toUpperCase()); } // Normalize URL (scheme://host[:port]/path), removing query and default ports function normalizeUrl(u) { const m = u.match(/^(https?):\/\/([^\/:]+)(?::(\d+))?(\/.*)?$/i); if (!m) return u; const scheme = m[1].toLowerCase(); const host = m[2].toLowerCase(); const port = m[3]; const path = (m[4] || '/').split('?')[0];
const defaultPort = (scheme === 'http' ? '80' : '443'); const hostPort = port && port !== defaultPort ? `${host}:${port}` : host; return `${scheme}://${hostPort}${path}`; }
// Make nonce function makeNonce(length = 11) { const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; let out = ''; for (let i = 0; i < length; i++) out += chars.charAt(Math.floor(Math.random() * chars.length)); return out; }
// Key-sorted RFC3986-encoded param string function buildNormalizedParamString(paramsObj) { const pairs = []; Object.keys(paramsObj).forEach((k) => { const v = String(paramsObj[k]); pairs.push([rfc3986Encode(k