N/https Module Script Samples
The following script samples demonstrate how to use the features of the N/https module:
Generate a Secure Token and a Secret Key
The following sample shows how to use a GUID to generate a secure token and a secret key. To run this sample in the debugger, you must replace the GUID with one specific to your account.
This sample script uses the require
function so that you can copy it into the SuiteScript Debugger and test it. You must use the define
function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
*/
// This script uses a GUID to generate a secure token and a secret key.
require(['N/https', 'N/runtime'], (https, runtime) => {
function createSecureString() {
const passwordGuid = '{284CFB2D225B1D76FB94D150207E49DF}';
let secureToken = https.createSecureString({
input: passwordGuid
});
let secretKey = https.createSecretKey({
input: passwordGuid
});
secureToken = secureToken.hmac({
algorithm: https.HashAlg.SHA256,
key: secretKey
});
}
createSecureString();
});
Create a Form with a Credential Field
The following sample shows how to use a Suitelet to create a form with a credential field. For more information about credential fields, see Form.addCredentialField(options).
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
The default maximum length for a credential field is 32 characters. If needed, use the Field.maxLength property to change this value.
The values for restrictToDomains
, restrictToScriptIds
, and baseUrl
in this sample are placeholders. You must replace them with valid values from your NetSuite account.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
// This script creates a form with a credential field.
define(['N/ui/serverWidget', 'N/https', 'N/url'], (serverWidget, https, url) => {
function onRequest(context) {
if (context.request.method === 'GET') {
const form = serverWidget.createForm({
title: 'Password Form'
});
const credField = form.addCredentialField({
id: 'password',
label: 'Password',
restrictToDomains: ['<accountID>.app.netsuite.com'],
restrictToCurrentUser: false,
restrictToScriptIds: 'customscript_my_script'
});
credField.maxLength = 32;
form.addSubmitButton();
context.response.writePage({
pageObject: form
});
}
else {
// Request to an existing Suitelet with credentials
let passwordGuid = context.request.parameters.password;
// Replace SCRIPTID and DEPLOYMENTID with the internal ID of the suitelet script and deployment in your account
let baseUrl = url.resolveScript({
scriptId: SCRIPTID,
deploymentId: DEPLOYMENTID,
returnExternalURL: true
});
let authUrl = baseUrl + '&pwd={' + passwordGuid + '}';
let secureStringUrl = https.createSecureString({
input: authUrl
});
let headers = ({
'pwd': passwordGuid
});
let response = https.post({
credentials: [passwordGuid],
url: secureStringUrl,
body: {authorization:' '+ passwordGuid + '', data:'anything can be here'},
headers: headers
});
}
}
return {
onRequest: onRequest
};
});
Create an Authentication Header Using a Secure String
The following sample shows how to use a Suitelet to create an authentication header and send the request to a service (which requires an authentication header) using an https.SecureString. For more information about SecureString, see https.SecureString.
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
// This script creates an authentication header using an https.SecureString.
define(['N/https', 'N/encode'], (https, encode) => {
function onRequest(context) {
// Secrets with these two Script IDs must be existing and allowed for this script
const nameToken = "custsecret_myName";
const passwordToken = "custsecret_mypPassword";
// Create BASE-64 encoded name:password pair
const secStringKeyInBase64 = https.createSecureString({
input: "{" + nameToken + "}:{" + passwordToken + "}"
});
secStringKeyInBase64.convertEncoding({
toEncoding: encode.Encoding.BASE_64,
fromEncoding: encode.Encoding.UTF_8
});
// Construct the Authorization header
const secStringBasicAuthHeader = https.createSecureString({
input: "Basic "
});
secStringBasicAuthHeader.appendSecureString({
secureString: secStringKeyInBase64,
keepEncoding: true
});
// Send the request to third party with the Authorization header
const resp = https.get({
url: "myUrl",
headers: {
"Authorization": secStringBasicAuthHeader
}
});
};
return {
onRequest: onRequest
};
});
Concatenate API Secrets with Strings
The following sample shows how to concatenate a string value to use as an API secret. API Secrets are string values that cannot be concatenated directly. In some cases, a code-generated string (for example, date stamp, account ID, sequence numbers) needs to be merged with the API secret. To merge the values, the N/https
module must be imported on the script file and use the createSecureString()
API to initialize both secret API values and ordinary string.
This sample script uses the require
function so that you can copy it into the SuiteScript Debugger and test it. You must use the define
function in an entry point script (the script you attach to a script record and deploy). For more information, see SuiteScript 2.x Script Basics and SuiteScript 2.x Script Types.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
*/
// This script uses appendSecureString to concatenate strings to use as an API secret.
require(['N/https', 'N/runtime'], (https, runtime) => {
function concatToCreateSecureString() {
let baseUrl = https.createSecureString({
input: 'www.someurl.com/add?apikey='
});
let apiKey = https.createSecureString({
input: '{CUSTSECRET_SOME_INTEGRATION}'
});
let url = baseUrl.appendSecureString({
secureString: apiKey
});
}
concatToCreateSecureString();
});
Create a JWT Token Using a SecureString
The following sample shows how to use a JWT token using https.SecureString. For more information about SecureString, see https.SecureString.
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
// This script creates a JWT token using https.SecureString.
define(['N/https', 'N/encode'], (https, encode) => {
function onRequest(context) {
let nameToken = "custsecret_myName";
let passwordToken = "custsecret_myPassword";
let headerObj = {
"alg": "HS256",
"typ": "JWT"
}
let payloadObj = {
"sub": "1234567890",
"name": "John Doe",
"iat": 1516239002
}
let headerJSON = JSON.stringify(headerObj);
let payloadJSON = JSON.stringify(payloadObj);
let headerBASE64 = encode.convert({
string: headerJSON,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64_URL_SAFE
});
let payloadBASE64 = encode.convert({
string: payloadJSON,
inputEncoding: encode.Encoding.UTF_8,
outputEncoding: encode.Encoding.BASE_64_URL_SAFE
});
headerBASE64 = headerBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
payloadBASE64 = payloadBASE64.replace(/=/g, ""); // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
let secStringJwtSignature = https .createSecureString({
input: headerBASE64 + "." + payloadBASE64
})
.hmac({
algorithm: https.HashAlg.SHA256,
key: https.createSecretKey({
secret: passwordToken,
encoding: encode.Encoding.UTF_8
}),
resultEncoding: encode.Encoding.BASE_64_URL_SAFE
})
.replaceString({ // remove = padding as per JWT spec 'base64UrlEncode' - URL-safe BASE-64 without padding
pattern: "=",
replacement: ""
})
let secStringJwtAuthHeader = https .createSecureString({
input: "Bearer " + headerBASE64 + "." + payloadBASE64 + "."
})
.appendSecureString({
secureString: secStringJwtSignature,
keepEncoding: true
})
// Reflect the response using a echo-request suitelet
let resp = https.get({
url: "myURL",
headers: {
"Authorization": secStringJwtAuthHeader
}
});
{
log.debug("resp-code", resp.code);
log.debug("resp-body", resp.body);
let respAuth = JSON.parse(resp.body)["headers"]["Authorization"];
log.debug("reps-head-auth", respAuth);
log.debug("reps-head-auth-expected",
"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.uel3RLILSJ9Q9W2Gomh8vAJQAgdbnd6TS4b7plyFOtA" ); // see https://jwt.io/#debugger-io
}
}
return {
onRequest: onRequest
};
});
Retrieve Employee Information Using a Suitelet and a RESTlet Script with a Defined Content-Type Header
This sample consists of a Suitelet script calling a RESTlet script. The RESTlet result dictates the output of the Suitelet.
Call a RESTlet and Display Results
The following sample is a Suitelet script calling a RESTlet script through https.requestRestlet()
. The RESTlet returns an application/json
value with the employee name. For more information about https.requestRestlet()
, see https.requestRestlet(options).
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
define(['N/https'],
(https) => {
/**
* Defines the Suitelet script trigger point.
* @param {Object} scriptContext
* @param {ServerRequest} scriptContext.request - Incoming request
* @param {ServerResponse} scriptContext.response - Suitelet response
* @since 2015.2
*/
const onRequest = (scriptContext) => {
// Get the employee ID from the parameters
const employeeId = scriptContext.request.parameters.employeeId || '0';
// Define output variable
let output = '';
// Retrieve the employee name
const restletResponse = https.requestRestlet({
body: JSON.stringify({ employeeId }),
deploymentId: 'customdeploy_samples_rs_requestrestlet',
scriptId: 'customscript_samples_rs_requestrestlet',
headers: { 'Content-Type': 'application/json' },
method: 'POST'
});
// Check if the RESTlet call is successful
if (restletResponse.code === 200) {
if (restletResponse.body !== '') {
// Parse the RESTlet response
const restletBody = JSON.parse(restletResponse.body);
// Write the suitelet output
output = `Employee Name is: ${restletBody.name}`;
} else {
// Write error message.
output = 'No employee found.';
}
} else {
// Write error message.
output = 'Unexpected error. Please check script logs.';
}
// Write output to response object.
scriptContext.response.write(output);
}
return {onRequest}
});
Query Employee Name and Return Data in JSON Format
The following RESTlet queries employee information based on the employee ID from the RESTlet request body. This RESTlet script expects the request to be have a Content-Type Header of application/json
. The RESTlet response is also expected to have the same Content-Type Header.
This sample script uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript Debugger.
/*
* Copyright (c) 2022, Oracle and/or its affiliates.
*/
/**
* @NApiVersion 2.1
* @NScriptType Restlet
*/
define(['N/scriptTypes/restlet', 'N/query'], function (restlet, query) {
// Restlet entry point
const post = function (requestBody) {
// Define the output variable
let returnValue = '';
// Create the Employee Query
const qObj = query.create({
type: query.Type.EMPLOYEE
});
// Check if the requestBody and the employeeId field is defined
if (!!requestBody && !!requestBody.employeeId) {
// Define the query condition for employee ID field in Employee record
qObj.condition = qObj.createCondition({
fieldId: 'id',
operator: query.Operator.EQUAL,
values: requestBody.employeeId
});
// Add the desired columns in the Query
qObj.columns = [
qObj.createColumn({
fieldId: 'firstname'
}),
qObj.createColumn({
fieldId: 'lastname'
})
];
// Retrieve the results
const results = qObj.run().asMappedResults();
for (let i = 0; i < results.length; i++) {
const result = results[i];
returnValue = {
name: result.firstname + ' ' + (result.lastname || '')
};
}
}
return returnValue;
}
return { post };
});
Call a Suitelet from a Client Script
This sample shows how to use the https.requestSuitelet(options) method to call a Suitelet from a client-side script.
This sample consists of three scripts that perform the following actions:
-
Add a Button that Calls a Custom Function – A user event script that adds a custom button on a form. When the button is clicked, it calls a custom function that is defined in a client script.
-
Create a Custom Function to Call a Suitelet – A client script that defines a custom function that calls a Suitelet and displays the Suitelet response in a dialog.
-
Create a Simple Suitelet– A simple Suitelet that shows the text "Hello World!".
Take note of the following when using the scripts in this sample:
-
Ensure that you replace path to the client script referenced in the user event script.
-
Ensure that you replace the script and deployment IDs of the Suitelet referenced in the client script.
-
The client script and user event script must be deployed to the same form.
Add a Button that Calls a Custom Function
The following user event script adds a button to a form. When the button is clicked, it calls the callSuitelet
function that is defined in the referenced client script. The Form.clientScriptModulePath property is used to specify the path to the client script where the custom function is defined. Ensure that you replace the value with the path to your client script.
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
// This script adds a button to a form and calls a custom function defined in a client script.
define(['N/ui/serverWidget'],
function (serverWidget) {
function beforeLoad(scriptContext) {
// Add a button that calls the callSuitelet function
scriptContext.form.addButton({
id: 'custpage_call_suitelet_button',
label: 'Click to Open Suitelet',
functionName: 'callSuitelet'
})
// Specify the path to the client script where the callSuitelet function is defined
scriptContext.form.clientScriptModulePath = './cs_request_suitelet.js' // Replace with the path to your client script
}
return {beforeLoad}
});
Create a Custom Function to Call a Suitelet
The following client script defines a callSuitelet
function that sends a request to a Suitelet using the https.requestSuitelet(options) method. The response from the Suitelet is then shown in an alert dialog using the dialog.alert(options) method. To use this script, replace the Suitelet script and deployment IDs with your own values.
/**
* @NApiVersion 2.x
* @NScriptType ClientScript
* @NModuleScope SameAccount
*/
// This script defines a custom function to call a Suitelet.
define(['N/https', 'N/ui/dialog'],
function(https, dialog) {
function pageInit(scriptContext) {}
// Create a custom function that calls a Suitelet and displays the response in a dialog
function callSuitelet() {
const response = https.requestSuitelet({
scriptId: 'customscript_sl_plf_requestsuitelet', // Replace with your Suitelet script ID
deploymentId: 'customdeploy_sl_plf_requestsuitelet', // Replace with your Suitelet deployment ID
});
dialog.alert({
title: 'Suitelet Response',
message: response.body
});
}
return {
pageInit: pageInit,
callSuitelet: callSuitelet
};
});
Create a Simple Suitelet
The following Suitelet returns a plain text response with the "Hello World!" message.
This script sample uses the define
function, which is required for an entry point script (a script you attach to a script record and deploy). You must use the require
function if you want to copy the script into the SuiteScript Debugger and test it. For more information, see SuiteScript 2.x Global Objects.
This sample uses SuiteScript 2.1. For more information, see SuiteScript 2.1.
/**
* @NApiVersion 2.1
* @NScriptType Suitelet
*/
// This Suitelet shows the text 'Hello World!' in plain text.
define([],
function() {
function onRequest(context) {
context.response.setHeader({name: 'Content-Type', value: 'text/plain'});
context.response.write('Hello World!');
}
return {onRequest};
});