So I have to authenticate then, any example of Aut...
# suitescript
a
So I have to authenticate then, any example of Auth? Token? or something?
s
here's one approach
Copy code
/**
 Utility library for making TBA (token based authentication) requests from
 server-side scripts to other server side scripts (e.g. Suitelet calling RESTlet via TBA)

 This file depends upon library files oauth-1.0a.js and crypto-js.js
 **/

declare var OAuth:any
declare var CryptoJS:any

namespace EC {

  const log = LogManager.getLogger('TBA')

  /**
   * Invokes a NetSuite endpoint using TBA, returning the nlobjResponse object
   * @param url Netsuite endpoint - e.g. RESTlet or Suitelet endpoint to call
   * @param token application token id (key) and token secret as assigned by NS
   * @param consumer consumer id (key) and consumer secret as assigned by NS
   * @param [postdata] optional js object payload, is JSON.stringified before sending to url.
   * If a value is provided, the request is HTTP POSTed, otherwise HTTP GET is used.
   *
   * @return {nlobjResponse} the response as returned from nlapiRequestURL
   * Note: Content-Type is hardcoded to 'application/json'
   */
  export function invokeTba(url, token: { key, secret }, consumer: { key, secret }, postdata?: object | null) {
    const oauth = OAuth({
      consumer: consumer,
      signature_method: 'HMAC-SHA1',
      hash_function: (b, k) => CryptoJS.HmacSHA1(b, k).toString(CryptoJS.enc.Base64),
      realm: nlapiGetContext().getCompany()
    })

    const authHeader = oauth.toHeader(oauth.authorize({
      method: postdata ? 'POST' : "GET",
      url: url,
      data: {}
    }, token)).Authorization

    log.debug('OAuth Header', authHeader)
    log.debug('calling endpoint', url)
    const resp = nlapiRequestURL(url, postdata ? JSON.stringify(postdata) : null, {
      Authorization: authHeader,
      "Content-Type": "application/json"
    })

    return resp
  }
}
I hate slack code formatting, or I don't know how to coax it into pretty mode
j
@stalbert you make me feel like a newbie. While I understand what your code is doing how does the code even run on the server side. I didn't think on the server side they were supporting above EcmaScript 5 right now. When I see const I'm think ES6 but then I see declare and think typescript please help this old dog see the light.
s
sorry, yes we do all our SuiteScript code in TypeScript. I'm so used to it I didn't think to mention that! ... so the file we actually deploy is ES5
a
@stalbert This script is same as or from https://github.com/mark-keaton/
?
h
@alien4u do you want a piece of code that I am using to call a restlet with TBA ?
a
Sure, it would not hurt... I'm trying to do it in a different way first using a workflow...
h
Copy code
var headers = oauth.getHeaders({
	        url: config.SEND_DATA_FOR_LABELS_RESTLET,
	        method: 'POST',
	        tokenKey: config.TBA_TOKENS['kelly']['tokenid'],
	        tokenSecret: config.TBA_TOKENS['kelly']['tokensecret']
	    });
        //passing RAW Groupon csv file id     	    
        var body = { grouponcsvrawfileid : csvGrouponFileId };
			
		headers['Content-Type'] = 'application/json';
		var restResponse = <http://https.post|https.post>({
			url: config.SEND_DATA_FOR_LABELS_RESTLET,
			headers: headers,
			body: JSON.stringify(body)
		});
		log.debug('response', JSON.stringify(restResponse));
Copy code
define(['N/https', 'N/ui/serverWidget', '../lib/oauth', '../lib/cryptojs', '../config/GrouponProcessingConfigurationModule'],
Copy code
function(https, serverWidget, oauth, cryptojs, config) {
and you need to have oauth and cryptojs but probably you already have them in your file cabinet
a
Thank you so much...
👍 1
h
I hope that it helps
so config is just a separate module where I keep all configuration related to that process
let me know if you need oauth and cryptojs
s
@alien4u the example I provided was just something I whipped up, good to know there's a public repo with similar
👍 1
h
so this is a suitelet that on GET part allows to load csv file and submits a form and on POST request call RESTlet using TBA passing that csv file id
Copy code
/**
 * @NApiVersion 2.x
 * @NScriptType Suitelet
 * @NModuleScope SameAccount
 */
define(['N/https', 'N/ui/serverWidget', '../lib/oauth', '../lib/cryptojs', '../config/GrouponProcessingConfigurationModule'],
/**
 * @param {https} https
 */
function(https, serverWidget, oauth, cryptojs, config) {
   
    /**
     * Definition of the Suitelet script trigger point.
     *
     * @param {Object} context
     * @param {ServerRequest} context.request - Encapsulation of the incoming request
     * @param {ServerResponse} context.response - Encapsulation of the Suitelet response
     * @Since 2015.2
     */
    function onRequest(context) {
    	try {
		if(context.request.method === 'GET' ){
			
			log.debug(context.request.method + " - START");
			
			var form = serverWidget.createForm({ title: 'Send data for Labels and Pick Ticket(s)' });
			var field = form.addField({ id: 'custpage_csvfilefromgroupon', type: serverWidget.FieldType.TEXT, label: 'CSV file id from Groupon US' });
			field.layoutType = serverWidget.FieldLayoutType.NORMAL;    	    
			form.addSubmitButton({ label: 'Send' });
			context.response.writePage(form);

			log.debug(context.request.method+" - END");
			
		} else if( context.request.method === 'POST' ){
			
			log.debug(context.request.method+" - START");

			var csvGrouponFileId = context.request['parameters']['custpage_csvfilefromgroupon'];
			log.debug("request: ","CSV Groupon File id: "+csvGrouponFileId);
			
			
			//Hubert's
//			var headers = oauth.getHeaders({
//				url: config.SEND_DATA_FOR_LABELS_RESTLET,
//				method: 'POST',
//    	        tokenKey: config.TBA_TOKENS['hubert']['tokenid'],
//    	        tokenSecret: config.TBA_TOKENS['hubert']['tokensecret']
//			});
			
			//Kelly's
	    var headers = oauth.getHeaders({
	        url: config.SEND_DATA_FOR_LABELS_RESTLET,
	        method: 'POST',
	        tokenKey: config.TBA_TOKENS['kelly']['tokenid'],
	        tokenSecret: config.TBA_TOKENS['kelly']['tokensecret']
	    });
			
			//passing RAW Groupon csv file id     	    
			var body = { grouponcsvrawfileid : csvGrouponFileId };
			
			headers['Content-Type'] = 'application/json';
			var restResponse = <http://https.post|https.post>({
				url: config.SEND_DATA_FOR_LABELS_RESTLET,
				headers: headers,
				body: JSON.stringify(body)
			});
			log.debug('response', JSON.stringify(restResponse));
			
			log.debug(context.request.method+" - END");
		}; //POST
		
	} catch (e) {
		log.error('error',e.message);
	};
		

    }

    return {
        onRequest: onRequest
    };
    
});
I am not sure if that's a proper way to do it but it works 😉
👍 1