To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Eclipse IDE for Java EE Developers: You can download it from here.
  • OneSpan Sign's Java SDK: You can download it from our Community Portal. Or alternatively, you can import them from our Maven Repository by using the following commands:
    <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.

Processing an Event Notification

In this example, a simple Servlet project will be built. You can also directly import the source code as an existing maven project, or copy and paste all necessary files and codes to your existing Servlet project.

The Servlet is needed to handle callback requests sent from OneSpan Sign. The following code sample creates an action controller to process event notifications. In this example, the doPost() method is used to intercept HTTP POST requests.

The final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

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();
		}
	}
}

Making a POST Request

The registered callback key is passed through the Authorization header as Basic {callbackKey}. This ensures that you receive only notifications that contain the shared secret. Once all documents in a package have been signed and the package completed, OneSpan Sign will make a POST request to the registered URL. Here is an example of a JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}

The sessionUser above refers to Signer Id, so it is recommended that you set the Custom Id (in SDK) or Signer Id (in REST) at signer creation and store it in your local database. Then, the package id will be used to download the signed documents. A service class will hande this business logic, using this code.

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();
		}
	}
}

This code utilizes eslClient to download the signed documents.

Mapping your Servlet Controller to the Callback Route

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

To run your code, use the following procedure:

  1. In your Project Explorer, right-click on the servlet project created above, and select Run As > Run on Server.
  2. Click Finish.
  3. 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]"

    Here is what you can expect to see after running this command:

    1-2

  4. Login to your OneSpan Sign account and browse to the Admin page.
  5. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback
  6. Enter a callback key and register for the Transaction completed event.
  7. Create, send, and complete a test transaction. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

    Capture

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Eclipse IDE for Java EE Developers: You can download it from here.
  • OneSpan Sign's Java SDK: You can download it from our Community Portal. Or alternatively, you can import them from our Maven Repository by using the following commands:
    <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.

Processing an Event Notification

In this example, a Spring Boot project using Spring Asynchronous Methods will be built. You can also directly import the source code as an existing maven project, or copy and paste all necessary files and codes to your existing Servlet project.

For more information, refer to the official tutorials on Building a RESTful Web Service with Spring Boot and Creating Asynchronous Methods.

This project is needed to handle callback requests sent from OneSpan Sign. The following code sample creates an action controller to process event notifications. In this example, the doPost() method is used to intercept HTTP POST requests.

The final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

@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();
		}
	}
}

Making a POST Request

The registered callback key is passed through the Authorization header as Basic {callbackKey}. This ensures that you receive only notifications that contain the shared secret. Once all documents in a package have been signed and the package completed, OneSpan Sign will make a POST request to the registered URL. Here is an example of a JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}

The sessionUser above refers to Signer Id, so it is recommended that you set the Custom Id (in SDK) or Signer Id (in REST) at signer creation and store it in your local database. Then, the package id will be used to download the signed documents. A service class will hande this business logic, using this code.

@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.

Updating Your Properties Files

All your OneSpan Sign related configurations are stored in an oss.properties file. Before running your code you must update this file to include your own information:

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

To run your code, use the following procedure:

  1. Run the main function in your Application.java class.
  2. Open a command prompt and change the directory location to the location of your ngrok executable.
  3. Enter the following command:
    ngrok http [port] -host-header="localhost:[port]"

    Here is what you can expect to see after running the command:

    1-2

  4. Login to your OneSpan Sign account and browse to the Admin page.
  5. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback
  6. Enter a callback key and register for the Transaction completed event.
  7. Create, send, and complete a test transaction. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

    Capture

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Visual Studio Community 2017: 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 can download it from our Community Portal.
  • 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.

Processing an Event Notification

In this example, you will need to create a new ASP.NET Web API Application project. Once your project has been created, add a new controller and name it CallbackController. This project is needed to handle callback requests sent from OneSpan Sign. The following code sample creates an action controller to process event notifications.

The final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

    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);
        }
    }

Making a POST Request

The registered callback key is passed through the Authorization header as Basic {callbackKey}. This ensures that you receive only notifications that contain the shared secret. Once all documents in a package have been signed and the package completed, OneSpan Sign will make a POST request to the registered URL. Here is an example of a JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}

The sessionUser above refers to Signer Id, so it is recommended that you set the Custom Id (in SDK) or Signer Id (in REST) at signer creation and store it in your local database. Then, the package id will be used to download the signed documents. A service class will hande this business logic, using this code.

    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);
            
        }

Updating Your Property Files

All your OneSpan Sign related configurations are stored in a Constants.cs file. Before running your code you must update this file to include your own information:

Running Your Code

To run your code, use the following procedure:

  1. In Visual Studio, run your project by pressing on Run.
  2. 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]"

    Here is what you can expect to see after running the command:

    1-2

  3. Login to your OneSpan Sign account and browse to the Admin page.
  4. In the Callback URL" field enter the URL to your callback listener. For example, https://b404b60a.ngrok.io/api/Callback.
  5. Enter a callback key and register for the Transaction completed" event.
  6. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

    Capture

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • SublimeText: A text editor is needed for this procedure. For this guide, the SublimeText text editor is used. If you do not already have it, you can download it for free, here.
  • XAMPP: You will need to create a local host server. We recommend that you use XAMPP, which is a free open-source cross-platform web server with PHP and PERL interpreters. It’s simple, lightweight and allows you to test your scripts locally. You can download it for free from their official website.
  • 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.

Processing an Event Notification

Create a new file in SublimeText named callback.php. Copy and paste the following code into this file.

The final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

<?php
$headerArray = apache_request_headers();
if (array_key_exists('Authorization', $headerArray)) {
	$callbackKey = $headerArray['Authorization'];
}
$data = file_get_contents('php://input');
$payload = json_decode($data, true);
$packageId = $payload['packageId'];
$eventNmae = $payload['name'];
// buffer all upcoming output
ob_start();
http_response_code(200);
// get the size of the output
$size = ob_get_length();
// send headers to tell the browser to close the connection
header("Content-Length: $size");
header('Connection: close');
// flush all output
ob_end_flush();
ob_flush();
flush();
if ($eventNmae == 'PACKAGE_COMPLETE') {
	$curl = curl_init();
	curl_setopt_array($curl, array(
		CURLOPT_URL => "https://sandbox.esignlive.com/api/packages/" . $packageId . "/documents/zip",
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_SSL_VERIFYHOST => false,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "GET",
		CURLOPT_HTTPHEADER => array(
			"authorization: Basic your_api_key",
		),
	));
	$response = curl_exec($curl);
	$err = curl_error($curl);
	curl_close($curl);
	if ($err) {
		echo "cURL Error #:" . $err;
	} else {
		file_put_contents("your_file_path/documents_" . $packageId . "_" . date("Y_m_d_H_i_s") . ".zip", $response);
	}
}
?>

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

$headerArray = apache_request_headers();
if (array_key_exists('Authorization', $headerArray)) {
	$callbackKey = $headerArray['Authorization'];
}

Making a POST Request

The registered callback key is passed through the Authorization header as Basic {callbackKey}. This ensures that you receive only notifications that contain the shared secret. Once all documents in a package have been signed and the package completed, OneSpan Sign will make a POST request to the registered URL. Here is an example of a JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}

The sessionUser above refers to Signer Id, so it is recommended that you set the Custom Id (in SDK) or Signer Id (in REST) at signer creation and store it in your local database. Then, the package id will be used to download the signed documents. A service class will hande this business logic, using this code.

Parsing the Request Body

To parse the request body use the following code samples.

The php://input wrapper is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input" instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives.

$data = file_get_contents('php://input');

Next, the JSON sent from OneSpan Sign is decoded using json_decode and then converted into an array.

$payload = json_decode($data, true);
$packageId = $payload['packageId'];
$eventNmae = $payload['name'];

Before consuming the request depending on the callback event type, close the connection and return a status 200 to avoid exceeding the timeout.

// buffer all upcoming output
ob_start();
http_response_code(200);
// get the size of the output
$size = ob_get_length();
// send headers to tell the browser to close the connection
header("Content-Length: $size");
header('Connection: close');
// flush all output
ob_end_flush();
ob_flush();
flush();

Then, use the cURL library to send your HTTP request to OneSpan Sign's API and download the signed documents.

if ($eventNmae == 'PACKAGE_COMPLETE') {
	$curl = curl_init();
	curl_setopt_array($curl, array(
		CURLOPT_URL => "https://sandbox.esignlive.com/api/packages/" . $packageId . "/documents/zip",
		CURLOPT_RETURNTRANSFER => true,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_TIMEOUT => 30,
		CURLOPT_SSL_VERIFYHOST => false,
		CURLOPT_SSL_VERIFYPEER => false,
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_CUSTOMREQUEST => "GET",
		CURLOPT_HTTPHEADER => array(
			"authorization: Basic your_api_key",
		),
	));
	$response = curl_exec($curl);
	$err = curl_error($curl);
	curl_close($curl);
	if ($err) {
		echo "cURL Error #:" . $err;
	} else {
		file_put_contents("your_file_path/documents_" . $packageId . "_" . date("Y_m_d_H_i_s") . ".zip", $response);
	}
}

Running Your Code

To run your code, use the following procedure:

  1. Using XAMPP, run your local server.
  2. 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]"

    Here is what you can expect to see after running this command:
    1-2

  3. Login to your OneSpan Sign account and browse to the Admin page.
  4. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback
  5. Enter a callback key and register for the Transaction completed event.
  6. Create, send, and complete a test transaction. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

    Capture

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Node.js: You can download the installer from the following link. Node.js is available for Windows, Mac, and Linux.
  • SublimeText: A text editor is needed for this procedure. For this guide, the SublimeText text editor is used. If you do not already have it, you can download it for free, 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 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.

Processing an Event Notification

In this example, you will build a simple Node.js project. You can copy and paste all necessary files and codes to your existing project.

The final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

In the code sample below, the entry point is listener.js:

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()}`);
});

Parsing the Request Body

For the purposes of this example, an express framework is used. 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 the 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 an express framework and body-parser installed, open a command prompt window and change to the directory where you saved your listener.js file. Then enter the following two lines:

npm install express@latest --save
npm install body-parser@latest --save

Making a POST Request

The registered callback key is passed through the Authorization header as Basic {callbackKey}. This ensures that you receive only notifications that contain the shared secret. Once all documents in a package have been signed and the package completed, OneSpan Sign will make a POST request to the registered URL. Here is an example of a JSON payload:

{
  "@class": "com.silanis.esl.packages.event.ESLProcessEvent",
  "name": "PACKAGE_COMPLETE",
  "sessionUser": "0787be84-f095-44c7-ba00-787093df86fc",
  "packageId": "KHiRfOXgKK0gpVWwwpFOSNy6o34=",
  "message": null,
  "documentId": null
}

The sessionUser above refers to Signer Id, so it is recommended that you set the Custom Id (in SDK) or Signer Id (in REST) at signer creation and store it in your local database. Then, the package id will be used to download the signed documents. A service class will hande this business logic, using this code.

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 of callback notifications. First of all, we parsed the callback key set in your web portal:

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

Retrieving the JSON object

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

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

Downloading the Package

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!');
	  });
  }
};

Starting Your Server and Listening for Connections

To start your server and listens on port 3800 for connections use the following code sample:

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

Running Your Code

  1. Open a command prompt and change the directory location to where you saved your listener.js file.
  2. Enter the following command:
    node listener.js
  3. In a new command prompt, change the directory to the location where you saved your ngrok executable.
  4. Enter the following command:
    ngrok http [port] -host-header="localhost:[port]"

    Here is what you can expect to see after running the command:

    1-2

  5. Login to your OneSpan Sign account and browse to the Admin page.
  6. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/event.
  7. Enter a callback key and register for the Transaction completed event.
  8. 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.

To download the full code sample, see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Ruby (version 2.3.3): You can download it from the official website, here.
  • Development Toolkit: This is needed to use the JSON module. You can download it here. Included in the link is a tutorial on how to install the Developer Toolkit.
  • 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.

Retrieving the JSON and Sinatra Modules

  1. The first thing you’ll want to do is install the json and sinatra modules. Open your command prompt and enter the following line:
    gem install json
    gem install sinatra
  2. In a text editor, create a new file name called listener.rb and save it in a location of your choice.
  3. In that file copy and paste the following code:
    require 'sinatra'
    require 'json'
    post '/event' do
      request_payload = JSON.parse(request.body.read)
      puts request_payload
      status 200
    end

The first two lines import the modules needed for this example.

require 'sinatra'
require 'json'

Defining the Endpoint URL

You must define an endpoint URL for OneSpan Sign to hit. For example, http://localhost:4567/event.

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 example, the JSON payload is printed to the console.

Running Your Code

  1. Open a command prompt and change the current directory to the location where you saved your listener.rb file.
  2. Enter the following command:
    ruby listener.py
  3. In a new command prompt, change the current directory to the location where you saved your ngrok executable file and enter the following:
    ngrok http 4567 -host-header="localhost:4567"
  4. Login to your OneSpan Sign account and browse to the Admin page.
  5. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback.
  6. Enter a callback key and register for the Transaction completed event.

  7. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

1

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Python (version 2.2): You can download it from the official website.
  • 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.

  • Web.py: Web.py is a framework for Python that allows you to create web applications.

Installing web.py

To install web.py, use the following procedure:

  1. Open a command prompt and enter the following:
    $ pip install web.py
  2. In a text editor, create a new file named listener.py and save it in a location of your choice.
  3. Copy the following code:
    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 (import web) imports the web.py module.

Defining the Endpoint URL

You must define an endpoint URL for OneSpan Sign to hit.

  1. Define a URL structure by entering the following code. This command says that the URL (the main landing page - http://localhost:8080) is to be handled by the class named event:
    urls = ('/.*', 'event')
  2. 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'
  3. 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

To run your code, use the following procedure:

  1. Open a command prompt and change the current directory to the location where you saved your listener.py file. T
  2. Enter the following command:
    python listener.py
  3. In a new command prompt, change the current directory to the location where you saved your ngrok executable file and enter the following:
    ngrok http 8080 -host-header="localhost:8080"
  4. In a new command prompt, change the current directory to the location where you saved your ngrok executable file and enter the following:
    ngrok http 4567 -host-header="localhost:4567"
  5. Login to your OneSpan Sign account and browse to the Admin page.
  6. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback.
  7. Enter a callback key and register for the Transaction completed event.

  8. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

1

To download the full code sample see our Code Share site.

You can use Callback Event Notifications to be notified about events that happen in your OneSpan Sign account. Callbacks solve the problem of having to poll for information by letting you register a URL that is notified anytime an event happens in your account. When an event occurs (for example, when a transaction has been completed), OneSpan Sign creates a JSON object which contains information like 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 Callback Event types in Setup Callback Notifications.

It is strongly recommended that you use a Callback Listener instead of polling for transaction statuses. The use of polling may consume unnecessary resources on both your end, and on the OneSpan Sign service.

Registering for Event Notifications

While you can follow the instructions detailed in Setting Up Callback Notifications, for the purposes of this example we will use the OneSpan Sign Web UI. For more information see Event Notifications.

OneSpan Sign enables integrators to be automatically notified of events that concern their account. On selected events, the system automatically issues messages to a destination of the integrator's choice. Before OneSpan Sign notifies you of an event, you must register to be notified of it.

To configure Event Notifications on your account:

  1. Click Admin > Event Notifications.
  2. Enter a Callback URL. This is a required field.
  3. Select your Authentication Method. Depending on the method selected different configurations can be set:
    1. None: Only a Callback URL is required.
    2. Basic: Enter a secure Callback Key.
    3. OAuth2.0: If OAuth 2.0 is select, then additional configurations are required:
      • Client ID: This is configured in your authorization server for the application.
      • Client Secret: This is configured in your authorization server for the application.
      • Authorization Server URL: The URL of your authorization server for the application.
      • Scope: Used to limit access to an account, configured in the authorization server for the application. This information should be provided by the user.
  4. Optionally, toggle on the event types, Account or Participant generated, for which you want to be notified. By default, notifications for all event types are disabled.
  5. Click Save.

If you've changed your mind, and want to disable all event notifications, click REVERT.

If you would like to enable Event Notification using OAuth Refresh Token Flow you must do so using an API. Note that we currently only support this method on Salesforce.

Prerequisites

To complete these procedures you will need the following:

  • Go: You can download it from the official website.
  • 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.

Processing an Event Notification

In this process, the final step would be to return an HTTP status code 2xx back to OneSpan Sign indicating that you have successfully received the callback, before the callback request times out in 20 seconds (which could vary between different instances). Note that if your service function has a complex workflow and will consume the request for a significant period of time, it is better to use an asynchronous method. This will avoid causing a timeout error.

  1. In a text editor, create a new file named listener.go" in a location of your choice.
  2. Copy and paste the following code into that file.
    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 code above:

  • 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, which is wrapped around log.Fatal().
  • 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

  1. Open a command prompt and change the current directory to the location where you saved your listener.go file.
  2. Enter the following commands:
    go build listener.go
    listener.exe
  3. 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
  4. Login to your OneSpan Sign account and browse to the Admin page.
  5. In the Callback URL field enter the URL to your callback listener. For example, https://4255b9d0.ngrok.io/CallbackListenerDemo/callback.
  6. Enter a callback key and register for the Transaction completed event.

  7. 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. Once OneSpan Sign sends a callback notification to your listener, you'll see something similar to this in your IDE console:

1