This guide will walk you through the steps necessary to create and send a document package (transaction in the new UI) with the OneSpan Sign Java SDK, including, downloading the Java SDK, downloading the Eclipse Java IDE, and creating/configuring a Java project.

Requirements

Below are a few requirements for following along with this guide. Downloading the Java SDK Before you can use the Java SDK, you will need to download it. You can find the download by visiting the following link. Download the Java SDKDownloading a Java IDE This guide uses the Eclipse IDE. You can use another, but everything in this guide will be described using Eclipse. Below is a link to download Eclipse. You can use any of the download packages that is for Java development. Download Eclipse Go ahead and install Eclipse by unzipping the zip file to your preferred location. For example, C:/Eclipse/.

Create and Send a Package

Now that you have all of the essentials for completing the guide, you can go ahead and get started. Create and Configure a Java Project Open Eclipse by running eclipse.exe from the root eclipse folder. Once it has started up: if it is not already open, open the Java perspective. You can do this by going to Window -> Open Perspective -> Other… -> Java.

Capture

Once you have the Java perspective open, you should see a View called the Package Explorer on the left side of the screen. Right-click inside this window and go to New -> Java Project. That will open a window like the one below:

Capture

Name your project whatever you would like. For example, CreateAndSendPackage. Then, hit next. Choose the Libraries tab, click the Add External JAR button, navigate to the location that you saved your SDK to, and select the sdk jar-with-dependencies jar. After you select Open, you will see that the SDK jar has been added to your build path.

Capture

Select Finish. Your new project has now been added to your Package Explorer view.

Capture

Expand the package by clicking on the arrow to the left, right click on the src folder and go to New -> Package. Enter what you want for the package name. For example, com.esignlive.example. Select Finish.

Capture

Right-click on your new package in the Package Explorer and go to New -> File to create a new java file. Enter a name for the file. For example, SimpleCreateAndSendPackage.java. Select Finish. Finally, add a sample PDF file that you want to have signed to your project with a simple copy and paste from your file system into your project in the package explorer. This completes the setup and configuration. Your project should now look like this:

Capture

You are now ready to write the code in your Java class.

The Code

In this section, the code will be broken down section by section. You can download the full sample code from the Developer Community Code Share, here. The first few lines define your connection information for OneSpan Sign.
public static final String API_KEY = "your_api_key";
public static final String API_URL = "https://sandbox.esignlive.com/api";
// USE https://apps.esignlive.com/api FOR PRODUCTION
To retrieve your API key, log in to your OneSpan Sign account and click on ACCOUNT from the top menu. Your API key is listed there. By default, the value is hidden. Select Unlock to show the value. Now, replace with your API key value. Next is the API_URL. If you’re using the Sandbox, the correct URL is already in place. If in production, you should use the commented out URL.
EslClient eslClient = new EslClient(API_KEY, API_URL);
The above line of code creates our OneSpan Sign Client using your OneSpan Sign account’s API Key and the appropriate API URL that you defined above. The next block of code is where you actually create the document package. Within this block, you give your package a name.
DocumentPackage documentPackage = newPackageNamed("Test Package Java SDK")
Next, two signers are added to the package. One being yourself and the other being the person you will send the package to for signature. In this block, you will replace the email addresses and names and optionally company and title with your test info. And setting Custom Id in SDK could better identify your signer.
.withSigner(newSignerWithEmail("[email protected]")
        .withCustomId("Signer")                           //optional
        .withFirstName("SignerFirstName")
        .withLastName("SignerLastName") 
	.withCompany("ABC Company")                       //optional
	.withTitle("Applicant"))                          //optional
.withSigner(newSignerWithEmail("[email protected]")
        .withFirstName("YourFirstName")
        .withLastName("YourLastName"))
Now, you add your document to be signed and also place the signature blocks for your signers. Again, remember to replace the sample values in this block with your test info. Optionally, setting Document and Signature Ids would help you better locate your signature.
.withDocument(newDocumentWithName("sampleAgreement")
        .withId("document1")                              //optional
        .fromFile("your_file_path")
        .withSignature(signatureFor("[email protected]")
		.withId(new SignatureId("signature1"))    //optional
                .onPage(0)
     	        .atPosition(175, 165))
        .withSignature(signatureFor("[email protected]")
                .onPage(0)
                .atPosition(550, 165)))
Finally, you build your package.
.build();
Now that the document package object is ready, you access your OneSpan Sign Client, create your package, and send it to the signers.
// Issue the request to the OneSpan Sign server to create the DocumentPackage
PackageId packageId = eslClient.createPackageOneStep(documentPackage);
 
// Send the package to be signed by the participants
eslClient.sendPackage(packageId);

Running the Code

With your Java class completed, you can go ahead and execute your simple application. There are a few ways you can do this from Eclipse. In the toolbar, you can select the run button, you can select Run -> Run from the menu bar, or you can right click on your Java class in the Package Explorer and choose Run As -> Java Application. If you check your OneSpan Sign Sandbox account inbox, you will see that the package has been created and waiting for signature. Here is an example of what you might expect:

CaptureGet the Code

This guide will cover how to: download the .NET SDK and Microsoft Visual Studio, create and configure a C# project, and create and send a document package (transaction in the new UI). Before you can write your code, you will need to set up your environment to use the .NET SDK. Downloading the .NET SDK Before you can use the .NET SDK, you will need to download it. Below is the link where you can download the .NET SDK. Download the .NET SDKDownloading Microsoft Visual Studio This guide uses Microsoft Visual Studio 2017. You can use something else, but everything in this guide will be described using Visual Studio. Below is a link to download where you can download it. Download Microsoft Visual Studio Community 2017

Create and Send a Package

Now that you have the necessary tools, you can go ahead and get started. Create and Configure Your C# Project

Capture

Select OK. You will now see your solution/project in the Solution Explorer. Next, add the .NET SDK as a reference by right clicking on References, in your project, in the Solutions Explorer. Choose Add Reference… In the dialog that pops up, choose Browse, select the Browse… button at the bottom, navigate to where you unzipped the .NET SDK, select the three .dll files, and choose Add.

Capture

Finally, right click on your project, select Add -> New Item…, select the Code section in the pop-up, choose Code File, name the file whatever you want (e.g. CreateAndSendPackge.cs), and select Add.

Capture

You will now see this file in your project in the Solution Explorer.

The Code

This segment of the guide will breakdown the code section by section. You can get the complete sample code from the Developer Community Code Share, here. The first few lines define the libraries you will use.
using System;
using System.IO;
using Silanis.ESL.SDK;
using Silanis.ESL.SDK.Builder;
The next few lines define your connection settings for OneSpan Sign. Be sure to replace YOUR_API_KEY with your API key. You can find this value by logging into OneSpan Sign and going to the ACCOUNT tab.
private static String apiUrl = "https://sandbox.esignlive.com/api";
// USE https://apps.esignlive.com/api FOR PRODUCTION
private static String apiKey = "YOUR_API_KEY";
The first thing you do is connect to the OneSpan Sign client using the API URL and API key you defined above.
EslClient eslClient = new EslClient(apiKey, apiUrl);
In the next line, you create a FileStream and read in the file you are wanting to upload with your package. Make sure you replace the placeholder text with the location of your PDF file.
FileStream fs = File.OpenRead("PATH_TO_YOUR_PDF");
Next, the package is created.
DocumentPackage superDuperPackage = PackageBuilder
 	.NewPackageNamed("Test Package .NET")
 	.WithSettings(DocumentPackageSettingsBuilder.NewDocumentPackageSettings())
Then, the signers are added to the package.
.WithSigner(SignerBuilder.NewSignerWithEmail("[email protected]")
                      .WithFirstName("Signer First Name")
                      .WithLastName("Signer Last Name")
                      .WithCustomId("Signer"))
.WithSigner(SignerBuilder.NewSignerWithEmail("[email protected]")
     	              .WithFirstName("Your First Name")
                      .WithLastName("Your Last Name"))
Next, the document is added, including signature boxes for required signers.
.WithDocument(DocumentBuilder.NewDocumentNamed("sampleAgreement")
                    	.FromStream(fs, DocumentType.PDF)
                    	.WithSignature(SignatureBuilder
                    	    .SignatureFor("[email protected]")
                       	    .OnPage(0)
                       	    .AtPosition(175, 165))
                   	.WithSignature(SignatureBuilder
                   	    .SignatureFor("[email protected]")
                       	    .OnPage(0)
                       	    .AtPosition(550, 165))
                   	)
With the package completely defined, you now build the package and send it.
.Build();
 
PackageId packageId = eslClient.CreatePackageOneStep(superDuperPackage);
eslClient.SendPackage(packageId);

Running Your Code

Execute this code by selecting Start from the toolbar. After doing this, you should be able to log into OneSpan Sign account and view the package you just created.

Capture

Get the Code

This quick start guide will cover how to create and send a document package (transaction in the new UI) with the OneSpan Sign REST API. If you do not have a Sandbox account, see the Web UI guide for how you can get signed up.

The REST API

Below is the REST API for creating and sending a package. We used a basically minimum payload as an example where 2 signers, 1 document and 1 signature per signer are added to the package. For a complete description of each field and other optional attributes, take a look at the JSON Properties section at the end of the guide. You can find a complete description of each field and all optional attributes in JSON Properties section at the end of the guide. And also refer to the Interactive API reference for more information.

HTTP Request

POST /api/packages

HTTP Headers

Authorization: Basic api_key Accept: application/json Content-Type: multipart/form-data

Request Payload

------WebKitFormBoundary1bNO60n7FqP5WO4t
Content-Disposition: form-data; name="file"; filename="testDocumentExtraction.pdf"
Content-Type: application/pdf
%PDF-1.5
%µµµµ
1 0 obj
<>>>
endobj.... 
------WebKitFormBoundary1bNO60n7FqP5WO4t
Content-Disposition: form-data; name="payload"
{
   "roles":[
      {
         "id":"Role1",
         "signers":[
            {
               "email":"[email protected]",
               "firstName":"1.firstname",
               "lastName":"1.lastname",
               "company":"OneSpan Sign"
            }
         ]
      },
      {
         "id":"Role2",
         "signers":[
            {
               "email":"[email protected]",
               "firstName":"2.firstname",
               "lastName":"2.lastname",
               "company":"OneSpan Sign"
            }
         ]
      }
   ],
   "documents":[
      {
         "approvals":[
            {
               "role":"Role1",
               "fields":[
                  {
                     "page":0,
                     "top":100,
                     "subtype":"FULLNAME",
                     "height":50,
                     "left":100,
                     "width":200,
                     "type":"SIGNATURE"
                  }
               ]
            },
            {
               "role":"Role2",
               "fields":[
                  {
                     "page":0,
                     "top":300,
                     "subtype":"FULLNAME",
                     "height":50,
                     "left":100,
                     "width":200,
                     "type":"SIGNATURE"
                  }
               ]
            }
         ],
         "name":"Test Document"
      }
   ],
   "name":"Example Package",
   "type":"PACKAGE",
   "language":"en",
   "emailMessage":"",
   "description":"New Package",
   "autocomplete":true,
   "status":"SENT"
}
------WebKitFormBoundary1bNO60n7FqP5WO4t--

Response Payload

{
    "id": "9sKhW-h-qS9m6Ho3zRv3n2a-rkI="
}

Configuration

Before you can get started, you will need to set up your environment. This example uses Java and Eclipse. Go ahead and create a new project (e.g. CreateAndSendPackageRest) and .java file (e.g. CreateAndSendPackageRest.java). If you need help getting this set up, see this previous guide for more detailed instructions on setting up a project.

The Code

This segment of the guide is broken down section by section. You can download the full sample code from the Developer Community Code Share, here. In the first couple lines, the connection info for your OneSpan Sign connection is defined. If you’re using the production environment, use the url "https://apps.esignlive.com/api". Make sure you replace the placeholder text with your API_KEY. You can find this value in the ACCOUNT page when signed into your OneSpan Sign Sandbox account. If you are using the production instance, you will have to contact support to get this key.
string apiKey = "YOUR_API_KEY";
string url = "https://sandbox.esignlive.com/api/packages";
After that, you will see several other variables being set that we will use in the creation of the POST call, like the form boundary value and the file you plan to upload.
String charset = "UTF-8";
File uploadFile1 = new File("C:/Eclipse/workspace_442/CreateAndSendPackage/sampleAgreement.pdf");
String boundary = Long.toHexString(System.currentTimeMillis()); // Generate a random value for the form boundary
String CRLF = "\r\n"; // Line separator used in multipart/form-data
The next line is the JSON string that defines your package. Typically, you will probably build your JSON string dynamically versus having a giant static string, like this. This is to give a good representation of the structure of the JSON you will need in order to create your package properly. Many properties are left empty in the string that are not necessary for creation. They are there to give you a list of options that are available and how they are passed in the JSON. The first part of the package JSON string is the roles object. Inside this, you can set items like the id, company, first name, last name, email, and name to customize your signer roles. Some of the other notable settings would be email message, title, and delivery. The next section of the package JSON string is the documents object. Inside this, you will set items like the name and the approvals (signature blocks). In the approvals, the main items to set would be the type, subtype, role, page, and the location settings. These will define the signatures required in each document. Finally, the last few settings of the package JSON string that you will want to note are the name, type, status, emailMessage, and autoComplete. Next, you will define the connection on which you will send your request. The first line opens the connection to the request URL. Notice that the rest of the URL for the particular request that is being made is added to the base URL, here. The rest sets up the request properties and creates the OutputStream and PrintWriter for communicating the request payload with OneSpan Sign.
HttpsURLConnection connection = null;
URL url = new URL(requestURL);
connection = (HttpsURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
connection.setRequestProperty("Authorization", "Basic " + apiKey);
connection.setRequestProperty("Accept", "application/json; esl-api-version=11.0");
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true);
Inside the try block, the actual multipart form is created. Below, you can see how the boundary, form part descriptors, and content are added in each portion of the form.
// Add pdf file.
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + uploadFile1.getName() + "\"").append(CRLF);
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(uploadFile1.getName())).append(CRLF);
writer.append("Content-Transfer-Encoding: application/pdf").append(CRLF);
writer.append(CRLF).flush();
Files.copy(uploadFile1.toPath(), output);
output.flush();
writer.append(CRLF).flush();
                 
// add json payload
writer.append("--" + boundary).append(CRLF);
writer.append("Content-Disposition: form-data; name=\"payload\"").append(CRLF);
writer.append("Content-Type: application/json; charset=" + charset).append(CRLF);
writer.append(CRLF).append(jsonContent).append(CRLF).flush();
 
// End of multipart/form-data.
writer.append("--" + boundary + "--").append(CRLF).flush();
Finally, you will make the POST call, passing your form to OneSpan Sign, creating your document package. The response code and response content are printed out to the console.
int responseCode = ((HttpURLConnection) connection).getResponseCode();
System.out.println(responseCode);
if (responseCode == 200) {
	// get and write out response
	BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();
	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();
	/ print result
	System.out.println(response.toString());
} else {
	// get and write out response
	BufferedReader in = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();
	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();
	// print result
	System.out.println(response.toString());
}
If everything with your REST call is correct, you should get a package id returned as your response, like this one:

Capture

If you log in to your OneSpan Sign account, you can see the package has been created as defined in your request.

Capture

Get the Code

Request Payload

PropertyTypeEditableRequiredDefaultSample Value(s)Reference
rolesSigner Management
idstringYesNon/aSigner1
namestringYesNon/aSigner1
emailMessagearrayYesNon/acheck referenceEmail Message
reassignbooleanYesNo0true/falseChange Signer
attachmentRequirementsarrayYesNon/acheck referenceAttachment Requirements
indexstringYesNo00/1/2/3Signer Workflow
typestringYesNoSIGNERSIGNER / SENDER
signers
idstringYesNon/aSigner1
emailstringYesYesn/a[email protected]
firstNamestringYesYesn/aPatty
lastNamestringYesYesn/aGalant
companystringYesNon/aAcme Inc.
titlestringYesNonullManaging Director
grouparrayYesNon/acheck referenceGroups
languagestringYesNon/aen/fr/es/…Configure Package Language
signature
textualstringNoNonull
handdrawnstringYesNon/aAQAAAMkGIVM7tmRJzS2cANoDcyT0ASABAwA=Signature Import Tool
deliveryarrayYesNon/acheck referenceDeliver Signed Documents By Email
knowledgeBasedAuthenticationarrayYesNon/acheck referenceSigner Authentication
autharrayYesNon/acheck referenceSigner Authentication
documentsDocument Management
descriptionstringYesNon/aTest document1 description
idstringYesNon/adocument1
dataarrayYesNon/acheck referenceDocument Attributes
approvalsSignatures
rolestringYesYesn/aSigner1
idstringYesNon/aapproval1
optionalbooleanYesNo0true/falseOptional Signature
enforceCaptureSignaturebooleanYesNo0true/falseEnforce Capture Signature
fieldsarrayYesNon/acheck referenceFields (also see Text Anchors)
namestringYesNon/adocument 1
extractbooleanYesNo0true/falseDocument Extraction/ Text Tag/ Position Extraction
extractionTypesarrayYesNon/a["TEXT_TAGS","ACROFIELDS"] Document Extraction/ Text Tag
fieldsarrayYesNon/acheck referenceField Injection
namestringYesNon/adocument1
settingsarrayYesNon/acheck referenceSigning Ceremony Customization
senderCreate a Package on Behalf of Another User
lastNamestringYesNon/aSmith
firstNamestringYesNon/aBob
emailstringYesNon/a[email protected](who is an sender under your main account)
statusstringYesNoDRAFTDRAFT / SENT / COMPLETED / ARCHIVED / DECLINED / OPTED_OUT / EXPIRED
namestringYesNon/aPackage created from template through REST API
typestringYesNoPACKAGEPACKAGE / TEMPLATE / LAYOUT
descriptionstringYesNon/aPackage created with the OneSpan Sign REST API
languagestringYesNoenen / fr / es …Configure Package Language
visibilitystringYesNoACCOUNTACCOUNT / SENDER
autoCompletebooleanYesNo1true / false
dataarrayYesNon/acheck referencePackage Attribute
duestringYesNonull08-26-17
notarizedbooleanYesNo0true/false (check reference, only use when notarization)eNotary
notaryRoleIdstringYesNon/aSigner1 (check reference, only use when notarization)eNotary
emailMessagestringYesNon/aThis message should be delivered to all signers
This quick start guide will cover how to create and send a document package (transaction in the new UI) with the OneSpan Sign REST API. If you do not have a Sandbox account, see the Web UI guide for how you can get signed up.

The REST API

Below is the REST API for creating and sending a package. We used a basically minimum payload as an example where 2 signers, 1 document and 1 signature per signer are added to the package. For a complete description of each field and other optional attributes, take a look at the JSON Properties section at the end of the guide. You can find a complete description of each field and all optional attributes in JSON Properties section at the end of the guide. And also refer to the Interactive API Reference for more information.

HTTP Request

POST /api/packages

HTTP Headers

Authorization: Basic api_key Accept: application/json Content-Type: multipart/form-data

Request Payload

------WebKitFormBoundary1bNO60n7FqP5WO4t
Content-Disposition: form-data; name="file"; filename="testDocumentExtraction.pdf"
Content-Type: application/pdf
%PDF-1.5
%µµµµ
1 0 obj
<>>>
endobj.... 
------WebKitFormBoundary1bNO60n7FqP5WO4t
Content-Disposition: form-data; name="payload"
{
   "roles":[
      {
         "id":"Role1",
         "signers":[
            {
               "email":"[email protected]",
               "firstName":"1.firstname",
               "lastName":"1.lastname",
               "company":"OneSpan Sign"
            }
         ]
      },
      {
         "id":"Role2",
         "signers":[
            {
               "email":"[email protected]",
               "firstName":"2.firstname",
               "lastName":"2.lastname",
               "company":"OneSpan Sign"
            }
         ]
      }
   ],
   "documents":[
      {
         "approvals":[
            {
               "role":"Role1",
               "fields":[
                  {
                     "page":0,
                     "top":100,
                     "subtype":"FULLNAME",
                     "height":50,
                     "left":100,
                     "width":200,
                     "type":"SIGNATURE"
                  }
               ]
            },
            {
               "role":"Role2",
               "fields":[
                  {
                     "page":0,
                     "top":300,
                     "subtype":"FULLNAME",
                     "height":50,
                     "left":100,
                     "width":200,
                     "type":"SIGNATURE"
                  }
               ]
            }
         ],
         "name":"Test Document"
      }
   ],
   "name":"Example Package",
   "type":"PACKAGE",
   "language":"en",
   "emailMessage":"",
   "description":"New Package",
   "autocomplete":true,
   "status":"SENT"
}
------WebKitFormBoundary1bNO60n7FqP5WO4t--

Response Payload

{
    "id": "9sKhW-h-qS9m6Ho3zRv3n2a-rkI="
}

Configuration

Before you can get started, you will need to set up your environment. This guide uses C# and Microsoft Visual Studio. Create a project (e.g. CreateAndSendPackageREST) and a .cs file (e.g CreateAndSendPackageREST.cs). If you need help getting this set up, see the .NET SDK guide (you can ignore the .NET SDK portion and skip to the Downloading Microsoft Visual Studio and Create and Configure Your C# Project sections) for more detailed instructions.

The Code

This guide will breakdown the code section by section. You can download to full sample code from the Developer Community Code Share, here. In the first couple lines, the connection info for your OneSpan Sign connection is defined. If you’re using the production environment, use the url "https://apps.esignlive.com/api". Make sure you replace the placeholder text with your API_KEY. You can find this value in the ACCOUNT page when signed into your OneSpan Sign account.
string apiKey = "YOUR_API_KEY";
string url = "https://sandbox.esignlive.com/api";
The next line is the JSON string that defines your package. Typically, you will probably build your JSON string dynamically versus having a giant static string, like this. This is to give a good representation of the structure of the JSON in order to create your package properly. Many properties are purposely left empty in the string that are not necessary for creation so you can see some of the other options that are available and how they are passed in the JSON. The first part of the package JSON string is the roles object. Inside this, you can set items like the id, company, first name, last name, email, and name to customize your signer roles. Some of the other notable settings would be email message, title, and delivery. The next section of the package JSON string is the documents object. Inside this, you will set items like the name and the approvals (signature blocks). In the approvals, the main items to set would be the type, subtype, role, page, and the location settings. These will define the signatures required in each document. Finally, the last few settings of the package JSON string that you will want to note are the name, type, status, emailMessage, and autoComplete. In this example, status is set to SENT. This will send the package and notify the signers. If you want to save this package as a draft, make the value DRAFT, instead. The next line of the code will take your JSON string and make the StringContent object that you will pass as the payload in your REST API command.
StringContent jsonContent = new StringContent(jsonString, Encoding.UTF8, "application/json");
The next couple lines will read in your PDF file and use that to create your file ByteArrayContent object for your REST call. Be sure to change the placeholder to the path of your file.
byte[] fileByteArray = File.ReadAllBytes("PATH_TO_YOUR_PDF.pdf");
ByteArrayContent content = new ByteArrayContent(fileByteArray);
The next several lines define the content disposition header of the pdf file content object.
content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
content.Headers.ContentDisposition.Name = "\"file\"";
content.Headers.ContentDisposition.FileName = "\"NAME_OF_YOUR_FILE.pdf\"";
content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
The next block of code is where you create your multipart form and add your content objects created above to pass with your REST call. Be sure to set the file name.
MultipartFormDataContent form = new MultipartFormDataContent();
form.Add(content, "\"file\"", "\"NAME_OF_YOUR_FILE.pdf\"");
form.Add(jsonContent, "\"payload\"");
Next, you will create the HttpClient that you will use to make your POST request and set the appropriate header authorization and accept values.
HttpClient myClient = new HttpClient();
myClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", apiKey);
myClient.DefaultRequestHeaders.Add("Accept", "application/json");
Finally, you will make the POST call, passing your form to OneSpan Sign, creating your document package. The Debug line will display the result to the debug output console.
var response = myClient.PostAsync(new Uri(url) + "/packages/", form).Result;
Debug.WriteLine(response.Content.ReadAsStringAsync().Result);
If everything with your REST call is correct, you should get a package id returned as your response, like this one:

Capture

If you log in to your OneSpan Sign account, you can see the package has been created as defined in your request:

Capture

Get the Code

Request Payload

PropertyTypeEditableRequiredDefaultSample Value(s)Reference
rolesSigner Management
idstringYesNon/aSigner1
namestringYesNon/aSigner1
emailMessagearrayYesNon/acheck referenceEmail Message
reassignbooleanYesNo0true/falseChange Signer
attachmentRequirementsarrayYesNon/acheck referenceAttachment Requirements
indexstringYesNo00/1/2/3Signer Workflow
typestringYesNoSIGNERSIGNER / SENDER
signers
idstringYesNon/aSigner1
emailstringYesYesn/a[email protected]
firstNamestringYesYesn/aPatty
lastNamestringYesYesn/aGalant
companystringYesNon/aAcme Inc.
titlestringYesNonullManaging Director
grouparrayYesNon/acheck referenceGroups
languagestringYesNon/aen/fr/es/…Configure Package Language
signature
textualstringNoNonull
handdrawnstringYesNon/aAQAAAMkGIVM7tmRJzS2cANoDcyT0ASABAwA=Signature Import Tool
deliveryarrayYesNon/acheck referenceDeliver Signed Documents By Email
knowledgeBasedAuthenticationarrayYesNon/acheck referenceSigner Authentication
autharrayYesNon/acheck referenceSigner Authentication
documentsDocument Management
descriptionstringYesNon/aTest document1 description
idstringYesNon/adocument1
dataarrayYesNon/acheck referenceDocument Attributes
approvalsSignatures
rolestringYesYesn/aSigner1
idstringYesNon/aapproval1
optionalbooleanYesNo0true/falseOptional Signature
enforceCaptureSignaturebooleanYesNo0true/falseEnforce Capture Signature
fieldsarrayYesNon/acheck referenceFields (also see Text Anchors)
namestringYesNon/adocument 1
extractbooleanYesNo0true/falseDocument Extraction/ Text Tag/ Position Extraction
extractionTypesarrayYesNon/a["TEXT_TAGS","ACROFIELDS"] Document Extraction/ Text Tag
fieldsarrayYesNon/acheck referenceField Injection
namestringYesNon/adocument1
settingsarrayYesNon/acheck referenceSigning Ceremony Customization
senderCreate a Package on Behalf of Another User
lastNamestringYesNon/aSmith
firstNamestringYesNon/aBob
emailstringYesNon/a[email protected](who is an sender under your main account)
statusstringYesNoDRAFTDRAFT / SENT / COMPLETED / ARCHIVED / DECLINED / OPTED_OUT / EXPIRED
namestringYesNon/aPackage created from template through REST API
typestringYesNoPACKAGEPACKAGE / TEMPLATE / LAYOUT
descriptionstringYesNon/aPackage created with the OneSpan Sign REST API
languagestringYesNoenen / fr / es …Configure Package Language
visibilitystringYesNoACCOUNTACCOUNT / SENDER
autoCompletebooleanYesNo1true / false
dataarrayYesNon/acheck referencePackage Attribute
duestringYesNonull08-26-17
notarizedbooleanYesNo0true/false (check reference, only use when notarization)eNotary
notaryRoleIdstringYesNon/aSigner1 (check reference, only use when notarization)eNotary
emailMessagestringYesNon/aThis message should be delivered to all signers
This guide will walk you through the steps necessary to create and send a document package (transaction in the new UI) with the OneSpan Sign APEX SDK, including, downloading the APEX SDK, and creating an APEX class.

Requirements

Below are a few requirements for following along with this guide. Downloading the APEX SDK Before you can use the APEX SDK, you will need to download it. You can find the download by visiting the link below. Download the APEX SDKCreating a Salesforce Developer Account For this guide, you will need a Salesforce developer account. You can register for free from the link below. Salesforce Developer

Create and Send a Package

Now that you have all of the essentials for completing the guide, you can go ahead and get started. Installing and Configuring the SDK The SDK can be installed using the Deploy to Salesforce button. Alternatively, it can be installed as an unmanaged package: After installing in your sandbox or developer org, you will need to configure the connection settings by creating an entry in Custom Setting. Please ensure that you have an entry with the API name e-SignLive Connection Settings in the org and it has the following fields in it:
  • Endpoint__c
  • API_Key__c

CaptureCapture

Once you have the Custom Setting in place, you will need to ensure that you have a record in the above defined Custom Setting with a name as Main. If you don’t have a record in the Custom Setting, go the Custom Setting Detail page and click on Manage. Then in the page click on New and enter the Name as Main without the quotes and then enter your OneSpan Sign endpoint (instance endpoint + /api, for example, https://sandbox.esignlive.com/api) and the API key in the appropriate fields and click on Save.

Capture

Capture

Next step, in order for the calls to go through from Salesforce, you will need to add the remote site endpoint (same endpoint as last step, but without /api) to the Remote Site Settings of the Salesforce org from which you intend to use the SDK. Once you add the Remote Site, ensure that it is marked as Active.

Capture

This completes the setup and configuration. You are now ready to write the code in your APEX class.

The Code

In this section, the code below will be broken down section by section. You can download the sample code from the Developer Community Code Share.
public class OssCreatePackage{
 
    public void createPackage() {
        //Create esl client
        ESignLiveSDK sdk = new ESignLiveSDK();
         
        //Create package
        ESignLiveAPIObjects.Package_x pkg = new ESignLiveAPIObjects.Package_x();
        pkg.name = 'Example Package Using APEX SDK1 - ' + Datetime.now().format();
         
        String packageId = sdk.createPackage(pkg);
        System.debug('PackageId: ' + packageId);
        
        //Add Signer
        String roleResponse = sdk.addRole('John', 'Smith', '[email protected]', packageId);
         
        //Add Document
        StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'testdoc1' LIMIT 1];
        Map<String,Blob> doc = new Map<String,Blob>();
        doc.put('Sample Document', sr.Body);
         
        ESignLiveAPIObjects.Document document = new ESignLiveAPIObjects.Document();
        document.name = 'Sample Contract';
        document.id = 'document1';
         
        sdk.createDocuments(packageId, document, doc);
        //Add Signature
        Map<String,Object> role = (Map<String,Object>)JSON.deserializeUntyped(roleResponse);
        String roleId = (String)(role.get('id'));
         
        ESignLiveAPIObjects.Field field = new ESignLiveAPIObjects.Field();
        field.left = 208;
        field.width = 200;
        field.height = 50;
        field.top = 518;
        field.page = 0;
        field.subtype = 'CAPTURE';
        field.type = 'SIGNATURE';
         
        List<ESignLiveAPIObjects.Field> fields = new List<ESignLiveAPIObjects.Field>();
        fields.add(field);
         
        ESignLiveAPIObjects.Approval approval = new ESignLiveAPIObjects.Approval();
        approval.fields = fields;
        approval.role = roleId;
         
        String signatureResponse = sdk.addSignature(packageId, 'document1', approval);
         
        //Send package
        pkg.status = ESignLiveAPIObjects.PackageStatus.SENT;
         
        sdk.updatePackage(pkg, packageId);     
    }
}
The first line creates your OneSpan Sign client, it will internally use your OneSpan Sign account’s API Key and the appropriate API URL that you defined in your Custom Settings.
ESignLiveSDK sdk = new ESignLiveSDK();
The next block of code is where you create the document package. Within this block, you give your package a name.
ESignLiveAPIObjects.Package_x pkg = new ESignLiveAPIObjects.Package_x();
pkg.name = 'Example Package Using APEX SDK1 - ' + Datetime.now().format();
         
String packageId = sdk.createPackage(pkg);
System.debug('PackageId: ' + packageId);
Next, one signer is added to the package. This is the person you will send the package to for signature. In this block, you will replace the email address and name with your test info.
String roleResponse = sdk.addRole('John', 'Smith', '[email protected]', packageId);
Now, you add your document to be signed and also place the signature block for your signer. Again, remember to replace the sample values in this block with your test info.
//Add Document
StaticResource sr = [SELECT Id, Body FROM StaticResource WHERE Name = 'testdoc1' LIMIT 1];
Map<String,Blob> doc = new Map<String,Blob>();
doc.put('Sample Document', sr.Body);
         
ESignLiveAPIObjects.Document document = new ESignLiveAPIObjects.Document();
document.name = 'Sample Contract';
document.id = 'document1';
         
sdk.createDocuments(packageId, document, doc);
         
//Add Signature
Map<String,Object> role = (Map<String,Object>)JSON.deserializeUntyped(roleResponse);
String roleId = (String)(role.get('id'));
         
ESignLiveAPIObjects.Field field = new ESignLiveAPIObjects.Field();
field.left = 208;
field.width = 200;
field.height = 50;
field.top = 518;
field.page = 0;
field.subtype = 'CAPTURE';
field.type = 'SIGNATURE';
         
List<ESignLiveAPIObjects.Field> fields = new List<ESignLiveAPIObjects.Field>();
fields.add(field);
         
ESignLiveAPIObjects.Approval approval = new ESignLiveAPIObjects.Approval();
approval.fields = fields;
approval.role = roleId;
         
String signatureResponse = sdk.addSignature(packageId, 'document1', approval);
In this example, we add pdf in Static Resources in your Salesforce Developer account and read it as a blob type.

Capture Now that your package is ready, you use your OneSpan Sign client to send it to the signer.

//Send package
pkg.status = ESignLiveAPIObjects.PackageStatus.SENT;
         
sdk.updatePackage(pkg, packageId);  

Running the Code

With your APEX class completed, you can go ahead and execute it. Open up your Developer Console and press Ctrl + E to launch the Execute Anonymous Window. Type in:
new OssCreatePackage.createPackage();
And hit Execute. You can see your package ID printed in debug console:

Capture

If you check your OneSpan Sign Sandbox account inbox, you will see that the package has been created and waiting for signature. Here is an example of what you might expect:

Capture

Get the Code