3

Hi I need to interact with an external device to transfer data over http. I know there are limitations on SuiteScript 1, but what about SuiteScript 2? Is there a way to make an HTTP request with payload and call back in 2.0 thanks for your help in advance

jk121960
  • 843
  • 14
  • 45

2 Answers2

6

Here is a pretty basic one that I have (minus a lot of extra fields in the payload), that I use to send NetSuite items to Salesforce, and then update the NetSuite item with the Salesforce ID, from the response. Is this what you are looking for?

define(['N/record','N/https'],function(record,https){
  function sendProductData(context){
    var prodNewRecord=context.newRecord;
    var internalID=prodNewRecord.id;
    var productCode=prodNewRecord.getValue('itemid');
    var postData={"internalID":internalID,"productCode":productCode};
    postData=JSON.stringify(postData);
    var header=[];
    header['Content-Type']='application/json';
    var apiURL='https://OurAPIURL';
    try{
      var response=https.post({
        url:apiURL,
        headers:header,
        body:postData
      });
      var newSFID=response.body;
      newSFID=newSFID.replace('\n','');
    }catch(er02){
      log.error('ERROR',JSON.stringify(er02));
    }

    if(newSFID!=''){
      try{
        var prodRec=record.submitFields({
          type:recordType,
          id:internalID,
          values:{'custitem_sf_id':newSFID,'externalid':newSFID},
        });
      }catch(er03){
        log.error('ERROR[er03]',JSON.stringify(er03));
      }
    }
  }

  return{
    afterSubmit:sendProductData
  }
});

*Note: a promise, as @erictgrubaugh mentions, would be a more scalable solution. This is just an example of a quick one that works for us.

w3bguy
  • 2,215
  • 1
  • 19
  • 34
  • 1
    I apologize I should have asked this right away, but is this server or client side? Becuase I would have to run this regularly from a scheduled script, thanks – jk121960 Aug 31 '16 at 14:53
  • That code is server side. I have that one running in a User Event script. Same basic functionality can be used for scheduled script. You would just loop through the calls, or build an array of data and send that. Then loop through the results. – w3bguy Aug 31 '16 at 14:59
5

You will want to look in to the N/http or N/https modules. Each provides methods for the typical HTTP request types, and each request type has an API that returns promises for your callback implementations.

Very trivial example from NS Help:

http.get.promise({
    url: 'http://www.google.com'
})
.then(function(response){
    log.debug({
        title: 'Response',
        details: response
    });
})
.catch(function onRejected(reason) {
    log.debug({
        title: 'Invalid Get Request: ',
        details: reason
    });
})
erictgrubaugh
  • 8,519
  • 1
  • 20
  • 28