Call Restlet from external suitelet with authentications - netsuite

Can We call Restlet From External Suitelet with NLAuth or any auth.Kindly post some sample please.

Here's the simplest way to do a GET to a RESTlet:
var headers = {};
headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
headers["contentType"] = 'application/json';
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=xxxx&deploy=xxx';
var response = nlapiRequestURL(url, null, headers);

Related

How to retrieve rest let data from suitelet and print in execution logs

How to retrieve rest let data from suitelet and print in execution logs. I have wrote a restlet script i'm able to see the output in postman. I need those output in suitelet script.
below is the suitelet script which i have tried.
function callRestletData(request,response)
{
try
{
url = 'https://tstdrxxxxxx.restlets.api.netsuite.com/app/site/hosting/restlet.nl?script=xxx&deploy=1';
//orderId = 741;
var hearders = {};
hearders['Authorization'] = 'NLAuth nlauth_account=TSTDRVxxxx, nlauth_email=abc#abc.com, nlauth_signature=xxxxxx, nlauth_role=3';
hearders['contentType'] = 'application/json';
//var myResponse = https.post(myRequest);
var myResopnse = nlapiRequestURL(url,null,hearders,null,'GET');
//var responseText = myResopnse.getBody();
var data = JSON.stringify(myResopnse);
nlapiLogExecution('DEBUG','Response Is:',data);
}
catch(error)
{
nlapiLogExecution('ERROR','In Catch Block',error.message);
}
}

How to configure client for access with authsecret?

I'm using the client and I need to call a service using authsecret parameter.
If I ad this param to the base url it give me a serialization error.
String baseUrl = AppConfig.GetAppApiUrl();
var client = new JsonServiceClient(baseUrl.AddQueryParam("authsecret","secretz123!"));
var c = client.Send(new ComuneRequest { Id = "A001" });
Using Fiddler I discovered that the request that the client generate is incorrect:
POST
http://192.168.0.63:820/?authsecret=secretz123%21/json/reply/ComuneRequest
So, what I have to do to make the client create a request in a correct format?
It needs to be sent as a Request Parameter (i.e. QueryString or FormData) which you can do using HTTP Utils with:
var url = baseUrl.CombineWith(requestDto.ToUrl()).AddQueryParam("authsecret", secret);
var res = url.GetJsonFromUrl().FromJson<MyResponse>();
Otherwise since AuthSecret is not a property on your Request DTO you wont be able to send it as a Request Parameter in the Request Body, but you should be able to send the param in the Request Headers with:
var client = new JsonServiceClient(baseUrl) {
RequestFilter = req => req.Headers[HttpHeaders.XParamOverridePrefix+"authsecret"] = secret
};

NetSuite RestLet call from SuiteLet Client

I am trying to call a RestLet webservice/URL from another SuiteScript. As i understand I need to use the http/https module to do so. But I am not able to find some example or steps to do so.
Planning to use this code in SS2.0-
var response = http.post({
url: 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1',
body: myDataObj, // json object
headers: headerObj // json obj
});
The below code works for me.
var nameValue = "arin";
var myDataObj = {
"name" : nameValue
};
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRV158xxxx,nlauth_email=XXXX,nlauth_signature=XXXX,nlauth_role=3';
myRequest.headers["Content-Type"] = 'application/json';
myRequest.headers["Accept"] = '*/*';
myRequest.url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=601&deploy=1'; // RESTlet
// URL
myRequest.method = "POST";
myRequest.body = JSON.stringify(myDataObj);
// myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
And reading the response data for JSON return ...
log.debug("Resonse", myResponse.body);
log.debug("Resonse", myResponse.code);
var data = myResponse.body;
var retObj = JSON.parse(data);
log.debug("Resonse Ret city - ", retObj.city);
Here's a basic example of how to do it:
var myRequest = {};
myRequest.headers = {};
myRequest.headers["Authorization"] = 'NLAuth nlauth_account=TSTDRVXXXXX, nlauth_email=xxx#xxx.com, nlauth_signature=XXXXXXX, nlauth_role=3';
myRequest.headers["contentType"] = 'application/json';
myRequest.url = 'https://XXXXXXXXX'; //RESTlet URL
myRequest.body = myDataObj;
var myResponse = https.post(myRequest);
Be careful exposing this on clientside scripts. You don't want to expose your credentials.

Use nlapiRequestURL to make a request to a Service

How do you use nlapiRequestURL to make a request to a service? My attempt below is failing with the error: UNEXPECTED_ERROR (output from NetSuites script execution log).
My service is set to run without login and works correctly when I directly access it through a browser using its url. Its just the request through nlapiRequestURL thats failing.
Any idea what could be going wrong?
// This code executes in Account.Model.js (register function)
// I am using my own netsuite user credential here
var cred = {
email: "MY_NETSUITE_EMAIL"
, account: "EXXXXX" // My account id
, role: "3" // Administrator
, password: "MY_NETSUITE_PASSWORD"
};
var headers = {"User-Agent-x": "SuiteScript-Call",
"Authorization": "NLAuth nlauth_account=" + cred.account + ", nlauth_email=" + cred.email +
", nlauth_signature= " + cred.password + ", nlauth_role=" + cred.role,
"Content-Type": "application/json"};
var payload = {
type: 'is_email_valid'
, email: 'spt015#foo.com'
};
// A raw request to the service works fine:
// http://mywebsite.com/services/foo.ss?type=is_email_valid&email=spt015#foo.com
// Error occurs on next line
var response = nlapiRequestURL(url, payload, headers);
You are attempting to call a non-Netsuite url with Netsuite authentication headers. You do not need that unless for some reason of your own you have implemented NS-style authorization on your service.
nlapiRequestURL does not automatically format a payload into a query string. If your service takes a posted JSON body then you need to call JSON.stringify(payload) e.g
var response = nlapiRequestURL(url, JSON.stringify(payload), headers);
If your service needs a query string like in your example then you need to construct a query string and append it to your service url. e.g.
var qs = '';
for(var k in payload) qs += k +'='+ uriEncodeComponent(payload[k]) +'&';
var response = nlapRequestURL(url +'?'+ qs.slice(0,-1), null, headers);
I would suggest changing your nlapiRequestURL to a GET instead of POST, and add the parameters to the url instead. Your function call will look like this instead.
nlapiRequestURL(url, null, headers, "GET")

HTTP Request from plugin - One or more erros occured

I have been trying to make a HTTP POST request from plugin without lucky.
I have the same code working fine in my console appication however in plugin I get the following error: "One or more erros occured". I tried to run it asynchronously but it did not work as well.
I really appreciate any idea, thank you!
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "KEY");
// Request parameters
queryString["chave"] = "key2";
queryString["codigo_obra"] = codigoObra;
queryString["codigo_bloco"] = codigoBloco;
queryString["codigo_unidade"] = codigoUnidade;
queryString["codigo_planta"] = codigoPlanta;
var uri = "http://test?" + queryString;
HttpResponseMessage response;
// Request body
byte[] byteData = Encoding.UTF8.GetBytes("");
using (var content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
//This line gives me the error.
response = client.PostAsync(uri, content).Result;
}

Resources