401 error for netsuite REST when searching by 'q' parameter in NEST.JS, works in postman OAuth1.0

191 Views Asked by At

I am working with the NetSuite API and I am trying to retrieve employees using query parameters, specifically the 'q' parameter, following the documentation aqui. I am using the following endpoint: GET https://demo123.suitetalk.api.netsuite.com/services/rest/record/v1/customer?q=email START_WITH barbara. When I make the request in Postman pointing to the endpoint, everything works correctly, as shown in this screenshot shown in this screenshot postman. However, when I try to make the request with the 'q' parameter in my code, I get the following error:'o:errorCode': 'INVALID_LOGIN'.

Here is my code

   async conectNetSuiteTests(): Promise<any> {
     

     const baseUrl = `${NETSUITEURL}}/services/rest/record/v1/employee?q=custentity_bit_lt_entitydocument+CONTAIN+${documentEmployee}'`;

      const oauthNonce = crypto.randomBytes(5).toString('hex');
      const oauthTimestamp = Math.floor(Date.now() / 1000);
      const oauthSignatureMethod = 'HMAC-SHA256';
      const oauthVersion = '1.0';
      const realm = `5900181_SB1`;

      const oauthParameters = {
          oauth_consumer_key: process.env.CONSUMER_KEY,
          oauth_token: process.env.ACCESS_TOKEN,
          oauth_nonce: oauthNonce,
          oauth_timestamp: oauthTimestamp,
          oauth_signature_method: oauthSignatureMethod,
          oauth_version: oauthVersion,
      };


      //   // Ordenar los parámetros de OAuth alfabéticamente por clave
      const sortedParameters = Object.keys(oauthParameters)
          .sort()
          .map((key) => `${key}=${encodeURIComponent(oauthParameters[key])}`)
          .join('&');

      console.log('sor', sortedParameters)
      //   // Crear la cadena base para la firma
      const signatureBaseString = `GET&${encodeURIComponent(baseUrl)}&${encodeURIComponent(sortedParameters)}`;

      //   // Crear la clave de firma
      const signingKey = `${process.env.CONSUMER_SECRET}&${process.env.ACCESS_TOKEN_SECRET}`;

      //   // Calcular la firma HMAC-SHA256
      const hmac = crypto.createHmac('sha256', signingKey);
      hmac.update(signatureBaseString);
      const oauthSignature = hmac.digest('base64');

      //   // Construir la cabecera de autorización

      const authorizationHeader = `OAuth realm="${realm}", oauth_consumer_key="${process.env.CONSUMER_KEY}", oauth_token="${process.env.ACCESS_TOKEN}", oauth_nonce="${oauthNonce}", oauth_timestamp="${oauthTimestamp}", oauth_signature="${oauthSignature}", oauth_signature_method="${oauthSignatureMethod}", oauth_version="${oauthVersion}"`;

      //   // Configuración de la solicitud Axios
      console.log('authorizationHeader', authorizationHeader)
      const axiosConfig: AxiosRequestConfig = {
          method: 'get',
          url: baseUrl, 
          headers: {
              'Prefer': 'transient',
              'Content-Type': 'application/json',
              'Authorization': authorizationHeader,
          },
      };

      try {
          const response = await axios(axiosConfig);

          return {
              "PRO":response.data.custentity_ks_empleado_proveedor_employe.refName.split(' ')[0].split('-')[1],
              "CLI":response.data.custentitycustentity_ks_empleado_cliente.refName.split(' ')[0].split('-')[1],


              };
      } catch (error) {
          console.error('error', error);
          console.error('error', error['response']['data']['o:errorDetails']);

          throw error;
      }
    }

I think this issue may be related to OAuth 1.0 authentication or how I generate the signature. Any suggestions for resolving this problem? I can make a request to an endpoint without parameters and it works, but I need to filter the results.

2

There are 2 best solutions below

1
On

Check your base url, you have an extra curly bracket

0
On

I also encountered the same problem as you, and finally solved it after constant attempts. The official website document says to use spaces to display here. So you need to replace the spaces in your encrypted query parameters with %20, which will be encrypted again and enter auth. This will successfully filter, which is disgusting because there are so few prompts.