Merge and Deliver via Webhook

Purpose

To send or post the merged document to the given webhook URL.

HTTP Request URL

https://{api.office-integrator_domain}/writer/officeapi/v1/document/merge/webhook

Request Parameters

ParameterValueDescription
Mandatory Parameters
apikey423s******Uniquely identifies the web application in which the Writer editor is integrated.

Body Parameters

ParameterData TypeDescription
Mandatory Parameters
output_formatStringSupported formats are pdf or docx. Specify a format in which you would like to download the merged document.

file_content

or

file_url

File

or

String

Below are the methods to provide the input file that needs to merged with the data depending on its location.

file_content - if the input file is from your local drive or desktop.

file_url - if the input file is from a publicly accessible Web URL.
webhook

{

"invoke_url" : <url>,

"invoke_period": "oneveryrecord/oncomplete"

}

Pass the values for invoke_url and invoke_period via this parameter as JSON.

Provide the webhook url in which the merged documents needs to be posted in invoke_url and when the merged documents needs to be posted in invoke_period.

merge_toString

Supported merge types are separatedoc and singledoc. Specify in which type you would like to merge the document.

separatedoc - If you would like to merge each record as a separate document.

singledoc- If you would like to merge all the records as a single document.

You can provide the data in any one of the below formats
merge_dataJSONObjectPass a String value through 'data' key as JSON Array.
merge_data_csv_contentFileProvide the required csv content in your API request body.
merge_data_json_contentFileProvide the required json content in your API request body.
merge_data_csv_urlurlProvide the required csv url in your API request body.
merge_data_json_url urlProvide the required json url in your API request body.
Optional Parameters
passwordStringSpecify a password if you would like to protect the merged document.

webhook

ParameterTypePossible ValuesDefault Value
invoke_urlstringURLURL
invoke_periodstring

oncomplete and oneveryrecord.

oncomplete - If you would like to post the merged documents after merging all the records.

oneveryrecord - If you would like to post the merged document of each record once done.

oncomplete

Sample Request

Copiedcurl --location --request POST "https://api.office-integrator.com/writer/officeapi/v1/document/merge/webhook" \
  --form "apikey=423s*****" \
  --form "output_format=pdf" \
  --form "password=***" \
  --form "webhook={\"invoke_period\":\"oncomplete\",\"invoke_url\":\"https://domain.com/xyz.php\"}" \
  --form "merge_to=separatedoc" \
  --form "file_content=@" \
  --form "merge_data={\"data\":[{\"name\":\"Amelia\",\"email\":\"amelia@zylker.com\"}]}"
Copiedconst Levels = require("zoi-nodejs-sdk/routes/logger/logger").Levels;
const Constants = require("zoi-nodejs-sdk/utils/util/constants").Constants;
const APIKey = require("zoi-nodejs-sdk/models/authenticator/apikey").APIKey;
const Environment = require("zoi-nodejs-sdk/routes/dc/environment").Environment;
const LogBuilder = require("zoi-nodejs-sdk/routes/logger/log_builder").LogBuilder;
const UserSignature = require("zoi-nodejs-sdk/routes/user_signature").UserSignature;
const InitializeBuilder = require("zoi-nodejs-sdk/routes/initialize_builder").InitializeBuilder;

const fs = require("fs");
const StreamWrapper = require("zoi-nodejs-sdk/utils/util/stream_wrapper").StreamWrapper;
const MailMergeWebhookSettings = require("zoi-nodejs-sdk/core/com/zoho//officeintegrator/office_integrator_sdk/mail_merge_webhook_settings").MailMergeWebhookSettings;
const InvaildConfigurationException = require("zoi-nodejs-sdk/core/com/zoho//officeintegrator/office_integrator_sdk/invaild_configuration_exception").InvaildConfigurationException;
const OfficeIntegratorSDKOperations = require("zoi-nodejs-sdk/core/com/zoho//officeintegrator/office_integrator_sdk/office_integrator_sdk_operations").OfficeIntegratorSDKOperations;
const MergeAndDeliverViaWebhookParameters = require("zoi-nodejs-sdk/core/com/zoho//officeintegrator/office_integrator_sdk/merge_and_deliver_via_webhook_parameters").MergeAndDeliverViaWebhookParameters;
const MergeAndDeliverViaWebhookSuccessResponse = require("zoi-nodejs-sdk/core/com/zoho//officeintegrator/office_integrator_sdk/merge_and_deliver_via_webhook_success_response").MergeAndDeliverViaWebhookSuccessResponse;

class MergeAndDeliver {

    //Include zoi-nodejs-sdk package in your package json and the execute this code.

    static async initializeSdk() {
        let user = new UserSignature("john@zylker.com");
        let environment = new Environment("https://api.office-integrator.com", null, null);
        let apikey = new APIKey("2ae438cf864488657cc9754a27daa480", Constants.PARAMS);
        let logger = new LogBuilder()
            .level(Levels.INFO)
            .filePath("./app.log")
            .build();
        let initialize = await new InitializeBuilder();

        await initialize.user(user).environment(environment).token(apikey).logger(logger).initialize();

        console.log("\nSDK initialized successfully.");
    }

    static async execute() {
        
        //Initializing SDK once is enough. Calling here since code sample will be tested standalone. 
        //You can place SDK initializer code in your application and call once while your application start-up. 
        await this.initializeSdk();

        try {
            var sdkOperations = new OfficeIntegratorSDKOperations();
            var parameters = new MergeAndDeliverViaWebhookParameters();

            parameters.setFileUrl("https://demo.office-integrator.com/zdocs/OfferLetter.zdoc");
            parameters.setMergeDataJsonUrl("https://demo.office-integrator.com/data/candidates.json");

            // var fileName = "OfferLetter.zdoc";
            // var filePath = __dirname + "/sample_documents/OfferLetter.zdoc";
            // var fileStream = fs.readFileSync(filePath);
            // var streamWrapper = new StreamWrapper(fileName, fileStream, filePath);
            
            // parameters.setFileContent(streamWrapper);

            parameters.setOutputFormat("zdoc");
            parameters.setMergeTo("separatedoc");

            parameters.setPassword("***");

            // var jsonFileName = "candidates.json";
            // var jsonFilePath = __dirname + "/sample_documents/candidates.json";
            // var jsonFileStream = fs.readFileSync(jsonFilePath);
            // var jsonStreamWrapper = new StreamWrapper(jsonFileName, jsonFileStream, jsonFilePath);

            // parameters.setMergeDataJsonContent(jsonStreamWrapper);

            var webhookSettings = new MailMergeWebhookSettings();

            webhookSettings.setInvokeUrl("https://officeintegrator.zoho.com/v1/api/webhook/savecallback/601e12157a25e63fc4dfd4e6e00cc3da2406df2b9a1d84a903c6cfccf92c8286");
            webhookSettings.setInvokePeriod("oncomplete");

            parameters.setWebhook(webhookSettings);
            
            //var mergeData = new Map();
            //parameters.setMergeData(mergeData);

            //var csvFileName = "csv_data_source.csv";
            //var csvFilePath = "/Users/amelia-2086/Desktop/csv_data_source.csv";
            //var csvFileStream = fs.readFileSync(csvFilePath);
            //var csvStreamWrapper = new StreamWrapper(csvFileName, csvFileStream, csvFilePath);

            //parameters.setMergeDataCsvContent(csvStreamWrapper);
            
            //parameters.setMergeDataCsvUrl("https://demo.office-integrator.com/data/csv_data_source.csv");
            //parameters.setMergeDataJsonUrl("https://demo.office-integrator.com/zdocs/json_data_source.json");

            var responseObject = await sdkOperations.mergeAndDeliverViaWebhook(parameters);

            if(responseObject != null) {
                console.log("\nStatus Code: " + responseObject.statusCode);
    
                let writerResponseObject = responseObject.object;
    
                if(writerResponseObject != null) {
                    if(writerResponseObject instanceof MergeAndDeliverViaWebhookSuccessResponse) {
                        console.log("\nRecords - " + JSON.stringify(writerResponseObject.getRecords()));
                        console.log("\nMerge report data url - " + writerResponseObject.getMergeReportDataUrl());
                    } else if (writerResponseObject instanceof InvaildConfigurationException) {
                        console.log("\nInvalid configuration exception. Exception json - ", writerResponseObject);
                    } else {
                        console.log("\nRequest not completed successfullly");
                    }
                }
            }
        } catch (error) {
            console.log("\nException while running sample code", error);
        }
    }
}

MergeAndDeliver.execute();

Sample Response

Copied{
    "merge_report_data_url": "https://api.office-integrator.com/writer/officeapi/v1/document/merge/job/0tq5n465132106580437abe99b6f56f2b0c85/data",
    "records": [
        {
	    "name": "Amelia",
            "email": "amelia@zylker.com",
            "download_link": "{url}",
            "status": "inprogress"
        }
    ],
}

Note:

1. merge_report_data_url -> helps to get or retrieve the status of the report by passing the {apikey} in 'GET' method.

2. download_link -> helps to download the merged document of a particular record by passing the {apikey} in 'GET' method.