Skip to main content

Authorize via OAuth and send export data to an external service

The following script performs authentication using a token obtained via Resource Owner Password Flow and then sends the export data to an external service:
// This sample Custom export script shows how to send an authorization request for OAuth 2.0 Resource Owner Password Flow, receive the token,
// and then send export results to the external system in JSON format

// Prepare the key-value body for the authorization request (parameters and their values may be different). The corresponding environment variable should be created beforehand.
var authDataContent = {};
authDataContent.grant_type = Context.GetSecret("password_secretName");
authDataContent.scope = "openid permissions";

// Pass sensitive data using environment variables. The corresponding variables should be created beforehand.
authDataContent.client_id = Context.GetSecret("client_id_secretName");
authDataContent.client_secret = Context.GetSecret("client_secret_secretName");
authDataContent.password = Context.GetSecret("password_secretName");
authDataContent.username = Context.GetSecret("username_secretName");

// create the request and send the data
var request = Context.CreateHttpRequest();
request.Url = "https://my_auth_service.com/auth2/connect/token"
request.Method = "POST";

// create content data for the authorization request
request.SetUrlFormEncodedContent(authDataContent);
request.Send();
var authResponseObject = JSON.parse(request.ResponseText);

// get all exports from the document
var exports = Context.Transaction.Documents[0].Exports;

// select the JSON export result
var extractedDataExportResult = exports.find(element => element.ExportFormat === ExportFormat.Json);
var pdfExportResult = exports.find(element => element.ExportFormat === ExportFormat.Pdf);

// Create content data for the request
var multiPartRequest = Context.CreateMultipartFormDataRequest();
multiPartRequest.Url = "https://my_service.com/api/v1.0/process_method"
multiPartRequest.Method = "POST";
multiPartRequest.AuthToken = authResponseObject.access_token;
multiPartRequest.AuthScheme = "Bearer";

// add extracted data to the export result
multiPartRequest.AppendStringContent(extractedDataExportResult.ToJson(), "jsonData");

// add the exported PDF
multiPartRequest.AppendFileContent(pdfExportResult, "binaryData");

// send a request to the service
multiPartRequest.Send();

// Get a deserialised response result
var responseObject = JSON.parse(multiPartRequest.ResponseText);

Send export data to an external service

The following script names the exported file using the invoice number and then sends export data to an external service (Dropbox in this case):
// This sample Custom export script shows how to send a file to Dropbox
// and set the file name using value of extracted data field.

// Get the document export result
var exports = Context.Transaction.Documents[0].Exports;
var extractedDataExportResult = exports.find(element => element.ExportFormat === ExportFormat.Json);

// Get the access token to the DropBox API (https://developers.dropbox.com/en-us/oauth-guide). The corresponding environment variable should be created beforehand.
var token = Context.GetSecret("access_token_secretName");

// Get "Invoice Number" from the extracted data
var invoiceNumberField = Context.Transaction.Documents[0].GetField("Invoice Number");
var invoiceNumber = invoiceNumberField.Value;

// Create the result file name
var jsonFileName = `ExtractedData_${invoiceNumber}.json`;

// Send the JSON file with the extracted data to DropBox
var httpRequest = Context.CreateHttpRequest();
httpRequest.Url = "https://content.dropboxapi.com/2/files/upload"
httpRequest.Method = "POST";
httpRequest.AuthScheme = "Bearer";
httpRequest.AuthToken = token;
httpRequest.SetHeader("Dropbox-API-Arg", `{"path": "/Files/${jsonFileName}", "mode": "add", "autorename": true, "mute": false, "strict_conflict": false}`);
httpRequest.SetFileContent(extractedDataExportResult, "application/octet-stream");
httpRequest.Send();

Modify extracted data

The following script modifies the value of an existing field and adds new values for a repeating field using information contained in a response from an external service:
// This sample Custom activity script shows how to modify an existing field 
// and create a new field value based on the results of an external call.

// Get all exports from the document
var exports = Context.Transaction.Documents[0].Exports;

// Get the JSON export result from the exports
var extractedDataExportResult = exports.find(element => element.ExportFormat === ExportFormat.Json);

// Get the PDF export result from the exports
var pdfExportResult = exports.find(element => element.ExportFormat === ExportFormat.Pdf);

// Create an HTTP request and specify required request properties
var multipartFormDataRequest = Context.CreateMultipartFormDataRequest();
multipartFormDataRequest.Url = "http://my_service/api/v1.0/apimethod/"
multipartFormDataRequest.Method = "POST";

// Add extracted data from the JSON export result to the request
multipartFormDataRequest.AppendStringContent(extractedDataExportResult.ToJson(), "jsonData");
// Add the PDF from the export results to the request
multipartFormDataRequest.AppendFileContent(pdfExportResult, "binaryData");

// Set the timeout for the HTTP request to be completed (in minutes).
// By default, the timeout is set to 1 minute.
multipartFormDataRequest.Timeout = 1;

// Send a request to the service
multipartFormDataRequest.Send();

// Get a response result
var newJsonDataObject = JSON.parse(multipartFormDataRequest.ResponseText);

// Assuming such a JSON was obtained in the response result:
/* {
    "DocumentData": {
        "Fields": {
            "InvoiceNumber": "706-222-3151",
            "InvoiceDate": "15.05.2020",
            "PurchaseOrder": [
                {
                    "OrderNumber": "25646788",
                    "Total": "540.54"
                },
                {
                    "OrderNumber": "24516684",
                    "Total": "138.43"
                }
            ]
        }
    }
}*/

// Change the value of an existing Vantage document field based on data received from an external call
var document = Context.Transaction.Documents[0];
var invoiceNumber = document.GetField("Invoice Number");
if (invoiceNumber.InstanceId === undefined || invoiceNumber.InstanceId === null)
    invoiceNumber.AddInstance();
invoiceNumber.Value = newJsonDataObject.DocumentData.Fields.InvoiceNumber;

// Add new Vantage document field values based on data received from an external call
var poOrder = Context.Transaction.Documents[0].GetField("Purchase Order");
let orderNumberFieldId = document.GetField("Purchase Order/Order Number").Id;
let totalFieldId = document.GetField("Purchase Order/Total").Id;
newJsonDataObject.DocumentData.Fields.PurchaseOrder.forEach(function (elem) {
    var newOrder = poOrder.AddInstance();
    var orderNumber = newOrder.Children.find(x => x.Id === orderNumberFieldId);
    orderNumber.Value = elem.OrderNumber;
    var total = newOrder.Children.find(x => x.Id === totalFieldId);
    total.Value = elem.Total;
});

Retrieve data from a specific table column

The following script writes all values (rows) of the Description table column to the transaction event log:
// Get the first document in a transaction
var document = Context.Transaction.Documents[0];
var descriptionFieldId = document.GetField("Line Items/Description").Id;

// Get the table object
var table = document.GetField("Line Items");

for (var i = 0; i < table.Instances.length; i++) {
  // Get the 'Description' column object for each table row and write its values to the transaction event log
  var columnDescription = table.Instances[i].Children.find(x => x.Id === descriptionFieldId);
  Context.LogMessage("Description. Row " + i + ": " + columnDescription.Value);
}

Retrieve data from all table columns

The following script writes all values (rows) of all table columns to the transaction event log:
// Get the first document in a transaction
var document = Context.Transaction.Documents[0];

// Get the table object
var table = document.GetField("Line Items");

// Write all table data to the transaction event log
for (var i = 0; i < table.Instances.length; i++) {
    for (var j = 0; j < table.Instances[i].Children.length; j++) {
        Context.LogMessage("Table row "+i+". Column "+table.Instances[i].Children[j].Name+": "+table.Instances[i].Children[j].Value);
    }
}

Add rows to a table

The following script adds new table rows and sets values for the Description and Quantity table columns:
// Get the first document in a transaction
var document = Context.Transaction.Documents[0];

// Get the table object
var table = document.GetField("Line Items");
var descriptionFieldId = document.GetField("Line Items/Description").Id;
var quantityFieldId = document.GetField("Line Items/Quantity").Id;
var tableRowCount = table.Instances.length;

// Create function to add one table row and set values for Description and Quantity columns
function addRow(valueDescription, valueQuantity, index) {
    table.AddInstance();
    var columnDescription = table.Instances[index].Children.find(x => x.Id === descriptionFieldId);
    columnDescription.Value = valueDescription;
    var columnQuantity = table.Instances[index].Children.find(x => x.Id === quantityFieldId);
    columnQuantity.Value = valueQuantity;
}

// Add three rows and set values
addRow("49910 - Gloves or mittens, NOI, in boxes", 4, tableRowCount++);
addRow("15560 - Bulk, NOI, inflated", 42, tableRowCount++);
addRow("15520 - Athletic or Sporting Goods, NOI", 24, tableRowCount++);

Delete rows from a table

The following script deletes all rows from a table:
// Get the first document in a transaction
var document = Context.Transaction.Documents[0];

// Get the table object
var table = document.GetField("Line Items");
var indexCount = table.Instances.length - 1;

// Delete all rows by their indexes
for (var i = indexCount; i >= 0 ; i--) {
  table.Instances[i].Remove();
}

// Or you can delete the entire table
table.Remove();

Delete a specific instance of a repeating field

The following script deletes the last instance of a repeating field:
// Get the first document in a transaction
var document = Context.Transaction.Documents[0];

// Get the repeating field object
var rField = document.GetField("First Name");

// Check if this field is repeating
if (rField.IsRepeatable) {
    // Delete the last instance of this field
    if (rField.Instances.length >= 1) {
        rField.Instances[rField.Instances.length-1].Remove();
    }  
}
else {
    Context.LogMessage(rField.Name + " is not repeating.");
}

Generate a JSON file and send it to a third-party system

The following script generates a JSON file in a custom format and sends it to a third-party system:
// This sample Custom export script shows how to create a JSON string
// using extracted Invoice US fields values and send it to an external endpoint.
// Get the first document in the transaction.
var document = Context.Transaction.Documents[0];

// Create a JSON object and set its key/value pairs.
var extractedValues = {};
extractedValues.Total = document.GetField("Total").Value;
extractedValues.Currency = document.GetField("Currency").Value;
extractedValues.Date = document.GetField("Invoice Date").Value;

// Get repeating field values and set them as array JSON values.
extractedValues.PurchaseOrderNumber = [];
var poGroup = document.GetField("Purchase Order");
var orderNumberFieldId = document.getField("Purchase Order/Order Number").Id;
for (var i = 0; i < poGroup.Instances.length; i++) {
  var poNumber = poGroup.Instances[i].Children.find(x => x.Id === orderNumberFieldId);
  extractedValues.PurchaseOrderNumber.push(poNumber.Value);
}

// The received JSON file is of the following format:
/* {
   "Total": 1819.14,
   "Currency": "USD",
   "Date": "2019-05-23T00:00:00.000Z",
   "PurchaseOrderNumber": [
      "012345678",
      "4500123466"
   ]
}*/

// Send a multipart/form-data request with the JSON created previously as the string content of that request.
var httpRequest = Context.CreateMultipartFormDataRequest();
httpRequest.Method = "POST";
httpRequest.Url = "https://external-endpoint.com/api/v1.0/tasks/1495c913-17bb-48d4-8041-a240e05ca9a4/process
httpRequest.AppendStringContent(JSON.stringify(extractedValues), "jsonData");
httpRequest.Send();

Retrieve original file names

The following script puts the original name of a file into the MyField field:
// Get the name of the source file and set it as the value of the specified field ("MyField")
Context.Transaction.Documents.forEach( doc => {
    // For Scanning Station, the source file name is put into a registration parameter
    var param = doc.RegistrationParameters["SourceFileName"]; 
    doc.GetField("MyField").Value = param != null ?
        param.Value : doc.SourceFiles[0].FileName;
});