You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

Requirements

Register for Event Notifications

Before the OneSpan Sign system can notify you of an event, you must first register to be notified in case of an event. You can follow this feature guide on how to register for event notifications. In our example, we will simply do all the registrations from web portal:

Capture

Eclipse IDE for Java EE Developers

For this guide, you will need Eclipse's IDE for Java EE Developers. If you do not already have it, you can download it for free, here.

OneSpan Sign's Java SDK

You will also need OneSpan Sign's Java SDK. You can download it from the following link and you can unzip the SDK to the location of your choice.

Or alternatively, you can import OneSpan Sign Java SDK from Maven Repository by:

<dependency>
	<groupId>com.silanis.esl</groupId>
	<artifactId>sdk</artifactId>
	<version>11.21</version>
</dependency>
Ngrok

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not work. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The Code

In this guide, we'll build a simple Servlet project in Java. And the complete source code can be found here.

Feel free to directly import the source code as an existing maven project, or go ahead and copy paste all necessary files/codes to your existing Servlet project.

We will need a Servlet handling callback requests sent from OneSpan Sign. Below is the code of an action controller to process the event notification.

public class CallbackController extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html");
		resp.setStatus(HttpServletResponse.SC_OK);
		StringBuilder builder = new StringBuilder();
		String aux = "";
		while ((aux = req.getReader().readLine()) != null) {
			builder.append(aux);
		}
		
		String text = builder.toString();
		System.out.println("callback content:" + text);
		String callbackAuthorization = req.getHeader("Authorization");
		System.out.println("callback authorization: " + callbackAuthorization);
		
		//check callback key, if applicable
		//============
		
		try {
			JSONObject json = new JSONObject(text);
			String eventName = json.getString("name");
			final String packageId = json.getString("packageId");
			System.out.println("package ID: "+packageId);
			
			if("PACKAGE_COMPLETE".equals(eventName)) {
				new Thread(new Runnable() {
					public void run() {
						try {
							new DownloadDocumentsService().download(packageId);
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}).start();
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}
}

In the code above, the doPost() method is used to intercept HTTP POST requests. The callback key you registered is passed through the Authorization header as Basic {callbackKey}. You’ve use this to make sure you’re receiving notifications that contain the shared secret, so you know you’re not getting spoof calls and can react accordingly. Once all documents in a package has been signed and the package completed, OneSpan Sign will make a POST request to the registered URL with the following example JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}
Note: The "sessionUser" above refers to signer Id, so it's recommended to set custom Id (in SDK) or signer Id(in REST) when signer creation and store it at your local database. Then, the package id will be used to download the signed documents. We will have a service class handling this business logic, with the code below.
public class DownloadDocumentsService {
	public void download(String packageId) throws IOException{
		
		EslClient eslClient = new EslClient("API_KEY", "https://sandbox.esignlive.com/api");
		
		byte[] documents = eslClient.downloadZippedDocuments(new PackageId(packageId));
		
		FileOutputStream stream = new FileOutputStream("your_file_path\\documents_" + packageId + ".zip");
		
		try {
		    stream.write(documents);
		} finally {
		    stream.close();
		}
	}
}

The code above utilizes the eslClient to download the signed documents. Finally, you will need to edit your web.xml file to make sure you've mapped the servlet controller to the "/callback" route. Here's how your web.xml file should look like:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Callback Listener Demo</display-name>
   <servlet>
    <servlet-name>CallbackController</servlet-name>
    <servlet-class>com.ossDemo.CallbackController</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>CallbackController</servlet-name>
    <url-pattern>/callback</url-pattern>
  </servlet-mapping>
</web-app>

Running Your Code

In your Project Explorer, right-click on your project and select Run As > Run on Server. Hit Finish. Then, open a command prompt and change the directory to the location where you saved your ngrok executable. Enter the following command:

ngrok http [port] -host-header="localhost:[port]"
Below is a screenshot of what you can expect after running the command:

1-2

Then, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. https://4255b9d0.ngrok.io/CallbackListenerDemo/callback), input a callback key and register for the "Transaction completed" event. Finally, create, send, and complete a test package. You should be able to view the signed documents as a zipped file in the location where you chose to save it in the "DownloadDocumentsService.java" class. And the moment OneSpan Sign sent callback notification to your listener, you'll see below content or something similar at your IDE console:

Capture

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

Requirements

Register for Event Notifications

Before the OneSpan Sign system can notify you of an event, you must first register to be notified in case of an event. You can follow this feature guide on how to register for event notifications.

In our example, we will simply do all the registrations from web portal:

Capture

Eclipse IDE for Java EE Developers

For this guide, you will need Eclipse's IDE for Java EE Developers. If you do not already have it, you can download it for free, here.

OneSpan Sign's Java SDK

You will also need OneSpan Sign's Java SDK. You can download it from the following link and you can unzip the SDK to the location of your choice.

Or alternatively, you can import OneSpan Sign Java SDK from Maven Repository by:

<dependency>
	<groupId>com.silanis.esl</groupId>
	<artifactId>sdk</artifactId>
	<version>11.21</version>
</dependency>
Ngrok

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not work. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The Code

In this guide, we'll build a Spring Boot project using Spring Asynchronous Methods. And the complete source code can be found here.

Feel free to directly import the source code as an existing maven project, or go ahead and copy paste all necessary files/codes to your existing project.

Also refer to the official tutorials on Building a RESTful Web Service with Spring Boot and Creating Asynchronous Methods.

We will need a Controller handling callback requests sent from OneSpan Sign. Below is the code of the CallbackController to process the event notification.

@RestController
public class CallbackController {
	@Autowired
	private OssCallbackService ossCallbackService;
	@PostMapping("/callback")
	@ResponseStatus(HttpStatus.OK)
	public void callback(@RequestBody OssCallbackVo ossCallbackVo, @RequestHeader("Authorization") String callbackKey) {
		System.out.println("receive a callback notification!");
		// 1. check callback key
		if (callbackKey != null) {
			System.out.println("callback key: " + callbackKey);
			if (!ossCallbackService.validateCallbackKey(callbackKey)) {
				throw new RuntimeException("Callback key is not valid: " + callbackKey);
			}
		}
		System.out.println("callback body: " + ossCallbackVo);
		// 2. handle callback asynchronously
		try {
			ossCallbackService.handleCallback(ossCallbackVo);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

In the code above, any POST request hitting "/callback" route will be handled by our application. The callback key you registered is passed through the Authorization header as Basic {callbackKey}. You’ve use this to make sure you’re receiving notifications that contain the shared secret, so you know you’re not getting spoof calls and can react accordingly.

Once all documents in a package has been signed and the package completed, OneSpan Sign will make a POST request to the registered URL with the following example JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}
Note: The "sessionUser" above refers to signer Id, so it's recommended to set custom Id (in SDK) or signer Id(in REST) when signer creation and store it at your local database. Then, we will distribute to different service functions depending on the callback event. A service class with asynchronous method was used to handle this business logic.
@Service
public class OssCallbackService {
	@Autowired
	private OssConfiguration ossConfiguration;
	public boolean validateCallbackKey(String callbackKey) {
		if (callbackKey != null) {
			String base64Credentials = callbackKey.substring("Basic".length()).trim();
			return ossConfiguration.CALLBACK_KEY.equals(base64Credentials);
		} else {
			return false;
		}
	}
	@Async("asyncExecutor")
	public void handleCallback(OssCallbackVo ossCallbackVo) {
		switch (OssCallbackEvents.valueOf(ossCallbackVo.getName())) {
		case DOCUMENT_SIGNED:
			break;
		case EMAIL_BOUNCE:
			break;
		case KBA_FAILURE:
			break;
		case PACKAGE_ACTIVATE:
			break;
		case PACKAGE_ARCHIVE:
			break;
		case PACKAGE_ATTACHMENT:
			break;
		case PACKAGE_COMPLETE:
			process_PACKAGE_COMPLETE(ossCallbackVo);
			break;
		case PACKAGE_CREATE:
			break;
		case PACKAGE_DEACTIVATE:
			break;
		case PACKAGE_DECLINE:
			break;
		case PACKAGE_DELETE:
			break;
		case PACKAGE_EXPIRE:
			break;
		case PACKAGE_OPT_OUT:
			break;
		case PACKAGE_READY_FOR_COMPLETION:
			break;
		case PACKAGE_RESTORE:
			break;
		case PACKAGE_TRASH:
			break;
		case ROLE_REASSIGN:
			break;
		case SIGNER_COMPLETE:
			break;
		case SIGNER_LOCKED:
			break;
		case TEMPLATE_CREATE:
			break;
		default:
			break;
		}
	}
	private void process_PACKAGE_COMPLETE(OssCallbackVo ossCallbackVo) {
		EslClient eslClient = new EslClient(ossConfiguration.API_KEY, ossConfiguration.API_URL);
		String packageId = ossCallbackVo.getPackageId();
		byte[] documents = eslClient.downloadZippedDocuments(new PackageId(packageId));
		String filePath = ossConfiguration.FILE_SAVE_PATH + "\\documents_" + packageId + "_"
				+ new SimpleDateFormat("yyyy_MM_dd").format(new Date()) + ".zip";
		Files.saveTo(documents, filePath);
	}
	
	
	private void process_DOCUMENT_SIGNED(OssCallbackVo ossCallbackVo) {
	}
	private void process_SIGNER_COMPLETE(OssCallbackVo ossCallbackVo) {
	}
	private void process_PACKAGE_TRASH(OssCallbackVo ossCallbackVo) {
	}
	private void process_PACKAGE_READY_FOR_COMPLETION(OssCallbackVo ossCallbackVo) {
	}
}

We've left the stub functions handling all available callback events. In this example, "PACKAGE_COMPLETE" event was monitored and triggered the corresponding service function. Then eslClient was utilized to download the signed documents.

Finally, all your OneSpan Sign related configurations are stored in oss.properties file, simply adjust to your own information before running the code:

OSS_API_KEY={api_key}
OSS_API_URL={api_url}
OSS_FILE_SAVE_PATH={file_save_path}
OSS_CALLBACK_KEY={callback_key}

Running Your Code

Run the main function in your Application.java class. Then, open a command prompt and change the directory to the location where you saved your ngrok executable. Enter the following command:

ngrok http [port] -host-header="localhost:[port]"

Below is a screenshot of what you can expect after running the command:

1-2

Then, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. https://b404b60a.ngrok.io/callback), input a callback key and register for the "Transaction completed" event. Finally, create, send, and complete a test package. You should be able to view the signed documents as a zipped file in the location where you chose to save it in the oss.properties file. And the moment OneSpan Sign sent callback notification to your listener, you'll see below content or something similar at your IDE console:

Capture

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

Requirements

Register for Event Notifications

Before the OneSpan Sign system can notify you of an event, you must first register to be notified in case of an event. You can follow this feature guide on how to register for event notifications.

In our example, we will simply do all the registrations from web portal:

Capture

Visual Studio Community 2017

You will need Microsoft’s Visual Studio Community 2017. If you do not already have it, you can download the community version for free, here.

OneSpan Sign's .NET SDK

You will also need OneSpan Sign's .NET SDK. You can download it from the following link. Unzip the SDK to the location of your choice.

Ngrok

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not work. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The Code

Go ahead and create a new ASP.NET Web API Application project. Once your project has been created, add a new controller and name it "CallbackController". Below is the code of the action controller to process the event notification.

    public class CallbackController : ApiController
    {
        // POST api/
        public ActionResult Post(JObject jsonResult)
        {
            #region "check callback key if applicable"
            string callbackKey = Request.Headers.GetValues("Authorization").First();
            Debug.WriteLine("callback key: "+callbackKey);
            #endregion
            #region "Extract data from request"
            string name = jsonResult["name"].ToString();
            string sessionUser = jsonResult["sessionUser"].ToString();
            string packageId = jsonResult["packageId"].ToString();
            string message = jsonResult["message"].ToString();
            string documentId = jsonResult["documentId"].ToString();
            string createdDate = jsonResult["createdDate"].ToString();
            OssCallbackVo ossCallbackVo = new OssCallbackVo
            {
                Name = name,
                SessionUser = sessionUser,
                PackageId = packageId,
                Message = message,
                DocumentId = documentId,
                CreatedDate = createdDate
            };
            Debug.WriteLine("callback payload: " + jsonResult.ToString());
            #endregion
            #region "process callback"
            OssCallbackHandler callbackHandlder = new OssCallbackHandler();
            Task.Run(async () => await callbackHandlder.ProcessOssCallback(ossCallbackVo));
            #endregion
            return new HttpStatusCodeResult(200);
        }
    }

Once all documents in a package has been signed and the package completed, OneSpan Sign will make a POST request to the registered URL with the following example JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}
Note: The "sessionUser" above refers to signer Id, so it's recommended to set custom Id (in SDK) or signer Id(in REST) when signer creation and store it at your local database. Then, we will distribute to different service functions depending on the callback event. A service class with asynchronous method was used to handle this business logic.
    public class OssCallbackHandler
    {
        #region Oss Callback Handler
        public Task ProcessOssCallback(OssCallbackVo ossCallbackVo)
        {
            switch (ossCallbackVo.Name)
            {
                case C.OssCallbackEvents.PACKAGE_CREATE:
                    break;
                case C.OssCallbackEvents.PACKAGE_ACTIVATE:
                    OssCallback_PACKAGE_ACTIVATE(ossCallbackVo);
                    break;
                case C.OssCallbackEvents.PACKAGE_DEACTIVATE:
                    break;
                case C.OssCallbackEvents.PACKAGE_READY_FOR_COMPLETION:
                    break;
                case C.OssCallbackEvents.PACKAGE_COMPLETE:
                    OssCallback_PACKAGE_COMPLETE(ossCallbackVo);
                    break;
                case C.OssCallbackEvents.PACKAGE_TRASH:
                    break;
                case C.OssCallbackEvents.PACKAGE_RESTORE:
                    break;
                case C.OssCallbackEvents.PACKAGE_DELETE:
                    break;
                case C.OssCallbackEvents.PACKAGE_DECLINE:
                    break;
                case C.OssCallbackEvents.PACKAGE_EXPIRE:
                    break;
                case C.OssCallbackEvents.PACKAGE_OPT_OUT:
                    break;
                case C.OssCallbackEvents.DOCUMENT_SIGNED:
                    break;
                case C.OssCallbackEvents.ROLE_REASSIGN:
                    break;
                case C.OssCallbackEvents.SIGNER_COMPLETE:
                    break;
                case C.OssCallbackEvents.KBA_FAILURE:
                    break;
                case C.OssCallbackEvents.EMAIL_BOUNCE:
                    break;
                case C.OssCallbackEvents.PACKAGE_ATTACHMENT:
                    break;
                case C.OssCallbackEvents.SIGNER_LOCKED:
                    break;
                case C.OssCallbackEvents.PACKAGE_ARCHIVE:
                    break;
                case C.OssCallbackEvents.TEMPLATE_CREATE:
                    break;
            }
            return Task.CompletedTask;
        }
        private void OssCallback_PACKAGE_ACTIVATE(OssCallbackVo ossCallbackVo)
        {
        }
        private void OssCallback_PACKAGE_COMPLETE(OssCallbackVo ossCallbackVo)
        {
            //change data in your DB
            //download document
            OssService service = new OssService();
            service.downloadDocument(ossCallbackVo.PackageId);
            
        }
        #endregion
    }

We’ve left the stub functions handling all available callback events. In this example, PACKAGE_COMPLETE event was monitored and triggered the corresponding service function. Then eslClient was utilized to download the signed documents.

        public void downloadDocument(string packageId)
        {
            EslClient eslClient = new EslClient(C.OSS.API_KEY, C.OSS.API_URL);
            PackageId pkgId = new PackageId(packageId);
            byte[] content = eslClient.DownloadZippedDocuments(pkgId);
            string fileLocation = C.SIGNED_DOCUMENTS_STORAGE_PATH + "\\" + pkgId + "_" + DateTime.Now.ToString("yyyy_MM_dd") + ".zip";
            Debug.WriteLine("file save path: " + fileLocation);
            File.WriteAllBytes(@fileLocation, content);
            
        }

Finally, all your OneSpan Sign related configurations are stored in Constants.cs file, adjust to your own information before running the code.

Running Your Code

Go ahead and run your project by pressing on Run in Visual Studio. Then, open a command prompt and change the directory to the location where you saved your ngrok executable. Enter the following command:

ngrok http [port] -host-header="localhost:[port]"
Below is a screenshot of what you can expect after running the command:

1-2

Then, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. https://b404b60a.ngrok.io/api/Callback), input a callback key and register for the "Transaction completed" event. Finally, create, send, and complete a test package. You should be able to view the signed documents as a zipped file in the location where you chose to save it in the Constants.cs file. And the moment OneSpan Sign sent callback notification to your listener, you'll see below content or something similar at your IDE console:

Capture

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

Requirements

Register for Event Notifications

Before the OneSpan Sign system can notify you of an event, you must first register to be notified in case of an event. You can follow this feature guide on how to register for event notifications.

In our example, we will simply do all the registrations from web portal:

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

Requirements

Before diving into the code, you will need to configure and install a couple of things.

Register for Event Notifications

Before the OneSpan Sign system can notify you of an event, you must first register to be notified in case of an event. You can follow this feature guide on how to register for event notifications.

In our example, we will simply do all the registrations from web portal:

Capture

Node.js

You can download the installer from the following link. Node.js is available for Windows, Mac, and Linux.

SublimeText

You will also need a text editor, such as SublimeText. You can download a free copy, here.

Ngrok

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The Code

In this guide, we'll build a simple Node.js project. The complete source code can be found here. Please feel free to directly run the demo, or go ahead and copy paste all necessary code snippets to your existing project.

The entry point is "listener.js" where below codes are included:

const express = require('express'); //node.js web application framework that provides a robust set of features to develop web applications
const bodyParser = require('body-parser'); //node.js middleware for handling JSON, Raw, Text and URL encoded form data.
const oss = require('./ossFunctions.js');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true,
}));
app.post('/event', (req, res) => {
  const callbakKey = req.get('Authorization');
  const payload = req.body;
  console.log('callback key: '+callbakKey);
  console.log('payload: '+ JSON.stringify(payload));
  if(payload.name == 'PACKAGE_COMPLETE'){
  	oss.downloadZippedDocument(payload);
  }
  res.send('OK');
});
const portToListenOn = 3800;
app.listen(portToListenOn, () => {
  console.log(`Listening for OneSpan Sign notifications on port ${portToListenOn}. Started ${new Date().toString()}`);
});

We'll use the express framework in this demo. Express is a minimal and flexible Node.js web application framework that provides a robust set of features for web and mobile applications. Optionally, you can add the "body-parser" middleware to parse incoming request bodies in a middleware before your handlers, available under the req.body property.

const express = require('express'); 
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true,
}));

If you do not have express and body-parser installed, open a command prompt window and change the directory where you saved your "listener.js" file. Then enter the following two lines:

npm install [email protected] --save
npm install [email protected] --save

Next, the POST calls from OneSpan Sign are "routed" to "localhost:3800/event". Routing refers to the definition of application end points (URIs) and how they respond to client requests.

In this example, we followed the normal workflow handling callback notifications. First of all, we parsed the callback key you've set in your web portal:

  const callbakKey = req.get('Authorization');
  console.log('callback key: '+callbakKey);

The callback key you registered is passed through the Authorization header as "Basic {callbackKey}". You’ve use this to make sure you’re receiving notifications that contain the shared secret, so you know you’re not getting spoof calls and can react accordingly.

Once all documents in a package has been signed and the package completed, OneSpan Sign will make a POST request to the registered URL with the following example JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}
Note: The "sessionUser" above refers to signer Id, so it's recommended to set signer Id when signer creation and store it at your local database.

Because we've already used body-parser middleware, we can directly get this JSON object and according to the event type, we can distribute into different service functions:

  const payload = req.body;
  console.log('payload: '+ JSON.stringify(payload));
  if(payload.name == 'PACKAGE_COMPLETE'){
  	oss.downloadZippedDocument(payload);
  }

In the "oss" module, we simply exposed a function downloading the completed package:

const request = require('request');
const fs = require('fs');
const http = require('http');
const API_URL = 'api_url';
const API_KEY = 'api_key';
const FILE_SAVE_PATH = 'file_save_path';
const ossFunctions = module.exports = 
{
  downloadZippedDocument: async function (payload) 
  {
  	const options = 
  	{ 
  		method: 'GET',
		url: API_URL+'/packages/' + payload.packageId + '/documents/zip',
		headers: 
		{ 	
		    accept: 'application/zip',
		    authorization: 'Basic ' + API_KEY}
	};
	const file_path = FILE_SAVE_PATH+'/package_' + payload.packageId + '_'+ Date.now()+'.zip';
	request(options)
	  .pipe(fs.createWriteStream(file_path))
	  .on('close', function () {
	    console.log('File written!');
	  });
  }
};

Finally, you can start your server and listens on port 3800 for connections.

const portToListenOn = 3800;
app.listen(portToListenOn, () => {
  console.log(`Listening for OneSpan Sign notifications on port ${portToListenOn}. Started ${new Date().toString()}`);
});

Running Your Project

Go ahead and run your local server with Node.js by opening a command prompt and changing the current directory where you saved your "listener.js" file. Then, enter:

node listener.js

In a new command prompt, change the directory to the location where you saved your ngrok executable. Enter the following command:

ngrok http [port] -host-header="localhost:[port]"

Below is a screenshot of what you can expect after running the command:

1-2

Then, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. https://4255b9d0.ngrok.io/event) and register for the "transaction complete" event. Finally, create, send, and complete a test package. You should be able to view the JSON sent by OneSpan Sign printed in the command prompt window.

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account.

Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request.

The Code

If you don’t already have Ruby (version 2.3.3) installed, you can download it from their official website, here. You will also need to download the Development Toolkit in order to use the JSON module. Included in the link is a tutorial on how to install the Developer Toolkit.

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The first thing you’ll want to do is install the 'json' and 'sinatra' module. Open your command prompt and enter the following line:

gem install json
gem install sinatra

Now, in your favorite text editor, create a new file name "listener.rb" and save it in a location of your choice. Go ahead and copy the code below.

require 'sinatra'
require 'json'
post '/event' do
  request_payload = JSON.parse(request.body.read)
  puts request_payload
  status 200
end

The first couple of lines imports the modules needed for this example.

require 'sinatra'
require 'json'

Next, the endpoint URL is defined (i.e. http://localhost:4567/event) for OneSpan Sign to hit. There is a POST request handler called /event, which is going to serve all the requests from OneSpan Sign.

post '/event' do
  request_payload = JSON.parse(request.body.read)
  puts request_payload
  status 200
end

In this simple example, the JSON payload is printed to the console.

Running Your Code

Open your command prompt and change the current directory to the location where you saved your "listener.rb" file. Then, enter the following line:

ruby listener.py

Then, in a new command prompt window, change the current directory to the location when you saved your ngrok executable file and enter the following line:

ngrok http 4567 -host-header="localhost:4567"

Finally, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. http://f3e93555.ngrok.io/event) and register for the "transaction complete" event. Finally, create, send, and complete a test package. You should be able to view the JSON sent by OneSpan Sign printed in the command prompt window.

1

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request. You can find a full list of all event types in the documentation.

The Code

If you don’t already have Python (version 2.7) installed, you can download it from their official website. In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application. You can also get the complete example code from the Developer Community Code Share.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

The first thing you’ll want to do is install the "web.py" module. In short, "web.py" is a framework for Python that allows you to create web applications. Open your command prompt and enter the following line:

$ pip install web.py

Now, in your favorite text editor, create a new file named "listener.py" and save it in a location of your choice. Go ahead and copy the code below.

import web
urls = ('/.*', 'event')
class event:
    def POST(self):
        data = web.data()
        print
        print 'OneSpan Sign Notification:'
        print data
        print
    return 'OK'
if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

The first line imports the "web.py" module.

import web

Next, we need to define our URL structure. The line below says we want the URL / (i.e. the main landing page http://localhost:8080) to be handled by the class named event.

urls = ('/.*', 'event')

Now, you need to write the event class. The POST function in this class will get called by web.py anytime OneSpan Sign makes a POST request (triggered by the events you registered in OneSpan Sign) to the callback URL defined by ngrok. In this example, the JSON payload is printed to the console.

class event:
    def POST(self):
        data = web.data()
        print
        print 'OneSpan Sign Notification:'
        print data
        print
    return 'OK'

Finally, you tell web.py to create an application with the URL listed above, looking up the classes in the global namespace of this file.

if __name__ == '__main__':
    app = web.application(urls, globals())
    app.run()

Running Your Code

Open your command prompt and change the current directory to the location where you saved your "listener.py" file. Then, enter the following line:

python listener.py

Then, in a new command prompt window, change the current directory to the location when you saved your ngrok executable file and enter the following line:

ngrok http 8080 -host-header="localhost:8080"

Finally, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. http://f3e93555.ngrok.io/event) and register for the "transaction complete" event. Finally, create, send, and complete a test package. You should be able to view the JSON sent by OneSpan Sign printed in the command prompt window.

1

Get the Code

You can use callbacks event notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll information by letting you register a URL that we will notify anytime an event happens in your account. When the event occurs, for example, when a transaction has been completed, OneSpan Sign creates an JSON object. This object contains all the relevant information, including the type of event and the data associated with that event. OneSpan Sign then sends the JSON object to the URL in your account's callback notification settings via an HTTP POST request.

The Code

If you don’t already have Go installed, you can download it from the official website, here.

In order to receive callback event notifications, you will need a publicly accessible URL to hit and work. Your localhost server on its own will not. Ngrok is a very simple and easy to use tool that creates a secure tunnel on your local machine along with a public URL you can use for browsing your local site. This saves you the trouble of deploying your web application. The complete example code is available on our Developer Community Code Share.

Ngrok should only be used for testing and development purposes. It should not be used in a production environment.

In your favorite text editor, create a new file named "listener.go" in a location of your choice and copy the code down below.

package main
import (
	"io"
	"log"
	"net/http"
	"os"
)
func handleEventNotification(w http.ResponseWriter, r *http.Request) {
	_, err := io.Copy(os.Stdout, r.Body)
	if err != nil {
		log.Println(err)
		return
	}
}
func main() {
    log.Println("Starting server...")
	http.HandleFunc("/event", handleEventNotification)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

In the main() function, the http requests to the path /event are handled by the http.HandleFunc library using the handleEventNotification function.

The http.ListenAndServe line starts a new webserver on localhost:8080. It is important to note that http.ListenAndServe can return an error, so it wrapped around log.Fatal() in such situations.

In this example, the contents of the JSON is simply copied to stdout using the io.Copy method (i.e. print the JSON payload to the terminal console).

Running Your Code

Open your command prompt and change the current directory to the location where you saved your "listener.go" file. Then, enter the following lines:

go build listener.go
listener.exe

Then, in a new command prompt window, change the current directory to the location when you saved your ngrok executable file and enter the following line:

ngrok http 8080

Finally, login to your OneSpan Sign account and browse to the Admin page. Enter in the "Callback URL" field the URL to your callback listener (i.e. http://f3e93555.ngrok.io/event) and register for the "transaction complete" event. Finally, create, send, and complete a test package. You should be able to view the JSON sent by OneSpan Sign printed in the command prompt window.