> For the complete documentation index, see [llms.txt](https://wiki.datadike.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://wiki.datadike.com/sonar/administration/integrations/docusign.md).

# DocuSign

Collect the e-signature of a term of responsibility with DocuSign eSignature and file the signed PDF in SONAR, against the employee and the device.

## What this is and when to use it

When a device is handed to an employee, the term of responsibility is usually printed, signed, scanned and uploaded by hand. With DocuSign eSignature the employee signs by email, and the signed PDF reaches SONAR on its own, filed against the employee and the device like a term uploaded in **Management › Terms**.

The flow has six steps:

1. Your intermediary service reads the employee and the device in SONAR.
2. It creates a DocuSign envelope from a term template, filled in with the device data.
3. The employee receives the DocuSign email and signs.
4. DocuSign Connect notifies your intermediary service that the envelope is completed.
5. The service downloads the signed PDF, with its certificate of completion, and uploads it to SONAR as the term of that employee and device.
6. Optionally, the service comments on and closes the delivery request in Jira Service Management.

DocuSign Connect cannot send the `X-API-KEY` header, and it delivers notifications, not files. That is why the receiver of Connect is your intermediary service, never the SONAR API. See [Plan an integration](https://wiki.datadike.com/sonar/administration/integrations/plan-an-integration.md) for the role of that service.

{% hint style="info" %}
The DocuSign details on this page follow DocuSign's public documentation as of October 2026. DocuSign can change them; check the vendor references at the end of the page before you build.
{% endhint %}

## Before you start

**In DocuSign**

* **Account.** A developer (demo) account for testing, and a production account on a plan that includes the API and Connect.
* **Application.** An **Integration Key** created in **Apps and Keys**, with an RSA key pair.
* **Authentication.** JWT Grant with a service user. Consent is given once, through this address (production uses `account.docusign.com`):

  ```
  https://account-d.docusign.com/oauth/auth?response_type=code
    &scope=signature%20impersonation&client_id=<INTEGRATION_KEY>
    &redirect_uri=<REGISTERED_URI>
  ```
* **Template.** A term template with one signer role, for example `Employee`, and text fields with stable labels such as `hostname`, `serial`, `model` and `registration`.
* **Connect.** HMAC enabled, with a secret kept by your intermediary service.

**In SONAR**

* A service user and an API key for this flow, as described in [Plan an integration](https://wiki.datadike.com/sonar/administration/integrations/plan-an-integration.md). Give its role **List Agents**, and in **Client & Site Access** the clients and sites of the employees it must read.
* Every employee who will sign registered in **Management › Employees**, with their **Name** and **Username**. SONAR files a term against the employee whose **Username** matches, and checks that the **Name** matches too. See [Employees](https://wiki.datadike.com/sonar/administration/employees/employees.md).
* The signer's email, from your directory or from the employee's `email` in SONAR, which is set through the API.
* One term per employee and device. A device that already holds a term of that employee takes no other until the old one is deleted.

{% hint style="info" %}
**How the employee fields are named in the API.** The **Name** shown in **Management › Employees** is the field `employer`, and the **Username** is `username`; the term upload calls the same value `registration`. Use these two values exactly as SONAR returns them, including upper and lower case.
{% endhint %}

## Steps

### 1. Read the employee and the device in SONAR

```
# Employee: filter the list by username on your side
GET https://api.example.com/employees/
# Device, with manufacturer, model and serial number
GET https://api.example.com/agents/<agent_id>/
# Confirm the device has no term of this employee yet
GET https://api.example.com/agents/<agent_id>/terms/
```

The employee list is not paginated and takes no filter: filter it on your side, and keep a cached copy instead of reading it for every envelope. Keep the employee's `employer` (the **Name**) and `username`: step 6 sends them back.

To find devices that still have no term, use `GET /terms/agents-with-terms/?filter=without-terms`. To suggest the employee of a device, match the device's `logged_in_username` with `GET /employees/usernames/`. The serial number is in the device details, see [API](https://wiki.datadike.com/sonar/reference/api.md#devices).

### 2. Get a DocuSign access token

Build a JWT signed with RS256 with these claims, and exchange it for an access token:

```
{"iss": "<INTEGRATION_KEY>", "sub": "<USER_GUID>",
 "aud": "account-d.docusign.com", "iat": 1760450000, "exp": 1760453600,
 "scope": "signature impersonation"}

POST https://account-d.docusign.com/oauth/token
Content-Type: application/x-www-form-urlencoded

grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=<JWT>
```

The token lasts one hour and there is no refresh token: build a new JWT before it expires. Then call `GET /oauth/userinfo` to get `base_uri` and `account_id`. Do not hard-code the production base address.

### 3. Create and send the envelope

```
POST {base_uri}/restapi/v2.1/accounts/{accountId}/envelopes
Authorization: Bearer <token>
Content-Type: application/json
```

```json
{
  "templateId": "<TEMPLATE_ID>",
  "emailSubject": "Term of responsibility - WS-0001",
  "status": "sent",
  "templateRoles": [{
    "roleName": "Employee",
    "name": "John Doe",
    "email": "jdoe@example.com",
    "tabs": {"textTabs": [
      {"tabLabel": "hostname",     "value": "WS-0001"},
      {"tabLabel": "serial",       "value": "SN-000123"},
      {"tabLabel": "model",        "value": "Laptop Model X"},
      {"tabLabel": "registration", "value": "102938"}
    ]}
  }],
  "customFields": {"textCustomFields": [
    {"name": "sonar_agent_id",     "value": "<agent_id>", "show": "false"},
    {"name": "sonar_registration", "value": "102938",     "show": "false"},
    {"name": "sonar_employer",     "value": "John Doe",   "show": "false"}
  ]},
  "eventNotification": {
    "url": "https://integration.example.com/docusign/connect",
    "requireAcknowledgment": "true",
    "deliveryMode": "SIM",
    "events": ["envelope-completed", "envelope-declined", "envelope-voided"],
    "eventData": {"version": "restv2.1", "includeData": ["custom_fields", "recipients"]}
  }
}
```

`sonar_registration` holds the employee's `username` and `sonar_employer` the employee's `employer` (the **Name**), as read in step 1. The envelope's custom fields carry these SONAR identifiers through to the completion notification. Keep the `envelopeId` returned with the employee and device pair. Instead of a notification per envelope, you can also configure Connect for the whole DocuSign account.

### 4. Receive the Connect notification

Connect sends a JSON `POST` to your intermediary service. Validate the HMAC signature before you process it:

```python
import base64, hashlib, hmac

def valid_signature(raw_body: bytes, headers: dict, secret: str) -> bool:
    expected = base64.b64encode(
        hmac.new(secret.encode(), raw_body, hashlib.sha256).digest()
    ).decode()
    received = [v for k, v in headers.items()
                if k.lower().startswith("x-docusign-signature-")]
    return any(hmac.compare_digest(expected, r) for r in received)
```

* Compute the HMAC over the raw bytes of the body, before any parsing.
* Answer `200` in less than 100 seconds and do the rest asynchronously. Without an acknowledgement, DocuSign retries at growing intervals for up to 15 days.
* Handle repeated events idempotently, by `envelopeId`.
* The event is in `event` (for example `envelope-completed`) and the identifier in `data.envelopeId`. The custom fields are in `data.envelopeSummary.customFields`.

### 5. Download the signed PDF

```
GET {base_uri}/restapi/v2.1/accounts/{accountId}/envelopes/{envelopeId}/documents/combined?certificate=true
Authorization: Bearer <token>
```

The answer is one PDF with the signed document and the certificate of completion. If the file is larger than 10 MB, use `certificate=false` and keep the certificate in DocuSign.

### 6. File the term in SONAR

Upload the PDF to `POST /terms/term-upload/`, as `multipart/form-data`, with four fields, all required:

| Field          | Value                                                                                                                                                                             |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `agent_id`     | The device                                                                                                                                                                        |
| `registration` | The employee's `username`                                                                                                                                                         |
| `employer`     | The employee's `employer`, the **Name** shown in SONAR                                                                                                                            |
| `file`         | The PDF or DOCX, up to 10 MB. Declare the content type on the file part: `application/pdf`, or `application/vnd.openxmlformats-officedocument.wordprocessingml.document` for DOCX |

If no employee has that `username`, SONAR creates one, with the `username` and the `employer` sent, no email and no site.

```python
import requests

def file_term(sonar_api, sonar_key, agent_id, registration, employer, pdf_bytes, name):
    resp = requests.post(
        f"{sonar_api}/terms/term-upload/",
        headers={"X-API-KEY": sonar_key},
        data={"agent_id": agent_id, "registration": registration, "employer": employer},
        files={"file": (name, pdf_bytes, "application/pdf")},
        timeout=30,
    )
    if resp.status_code == 201:
        return "filed"
    if resp.status_code == 400 and "already has a term" in resp.text:
        return "already_filed"  # keep it, or delete the old term and upload again
    resp.raise_for_status()
```

A successful upload answers `201` with `"Term sent successfully"`, without the term's identifier. To get it, read `GET /agents/<agent_id>/terms/`.

Name the file so it can be traced, for example `term_<registration>_<hostname>_<envelopeId>.pdf`. To replace a term, delete the old one with `DELETE /terms/delete-term/<term_id>/` and upload the new one.

### Declined and voided envelopes

On `envelope-declined` and `envelope-voided`, send nothing to SONAR. Record the reason in your service and, if there is a request in Jira Service Management, comment on it and leave it pending for the team. Expired envelopes also arrive as `envelope-voided`.

### Variant: start from a Jira Service Management request

Jira Service Management can be the starting point, from an equipment delivery request:

1. The service desk agent opens the request with the registration and the hostname.
2. An Automation rule calls SONAR with **Send web request** to validate the device and get its model and serial number, as in [Jira Service Management](https://wiki.datadike.com/sonar/administration/integrations/jira-service-management.md#scenario-c-jira-service-management-reads-and-updates-sonar).
3. The same rule creates the envelope with the Automation action **Send custom Docusign request**, available on Jira Service Management Cloud Standard, Premium and Enterprise. It uses an Integration Key with OAuth configured by the Jira administrator.
4. Connect notifies your intermediary service, which files the PDF in SONAR (steps 4 to 6) and comments on and transitions the request.

Here the intermediary service only receives Connect and moves the file: Automation cannot download the PDF and send it on as a file. A third-party app named *DocuSign for Jira* exists in the Atlassian Marketplace, published by a partner rather than by DocuSign; this flow does not need it.

## More use cases

**Term campaign for every device without one.** List the devices without a term with `GET /terms/agents-with-terms/?filter=without-terms`, relate each device's user to an employee with `GET /employees/usernames/`, and send the terms in bulk with DocuSign's `POST /bulk_send_lists` and `POST /bulk_send_lists/{listId}/send`. Review the list before sending: the link between the logged-in user and the employee can be out of date. Each list takes up to 1,000 sends, and bulk sending requires specific DocuSign plans. Filing in SONAR follows steps 4 to 6.

**Signing inside the Jira Service Management portal.** Create the envelope with `clientUserId` on the recipient. When the employee clicks to sign, your service calls `POST /envelopes/{envelopeId}/views/recipient` and redirects the employee to the address returned. That address is single-use and expires in 5 minutes, so generate it only at that moment. Your service then becomes responsible for authenticating the employee before redirecting.

**Return term when an employee leaves.** DocuSign handles this with a second template. SONAR keeps one term per employee and device, without telling a delivery term from a return term, so keep the return term in DocuSign or in the Jira Service Management request. Replacing the delivery term in SONAR would delete the original record.

## How to verify it worked

| Test                                            | Expected result                                                                             |
| ----------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Send an envelope to a test employee and sign it | The signed PDF appears in the device's **TERMS** tab and in `GET /agents/<agent_id>/terms/` |
| Decline an envelope                             | Nothing is sent to SONAR; the refusal is recorded in your service                           |
| Send the same Connect notification twice        | No duplicate term: the second upload answers `400` and your service keeps the first         |

**Management › Terms** shows the term on the device's row, with the file name, the upload date and the key's user as the uploader.

## Common errors

| Symptom                                                                                                     | Cause                                                              | Fix                                                                                                                                                                                                                  |
| ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `400` with `The employee '...' already has a term in this device.`                                          | That employee already holds a term on that device                  | Keep it, or delete it with `DELETE /terms/delete-term/<term_id>/` and upload again                                                                                                                                   |
| `400` with `The record '...' already belongs to '...', not '...'.`                                          | The `username` exists in SONAR with another **Name**               | Send the employee's `employer` exactly as SONAR returns it. An employee created from a Windows sign-in has an empty `employer`, and the console shows the username in its place, until someone fills in the **Name** |
| `400` with `File size must be at most 10MB`                                                                 | The PDF is larger than 10 MB                                       | Download it with `certificate=false`                                                                                                                                                                                 |
| `400` with `Only PDF and DOCX files are allowed`                                                            | The file part was sent without a content type, or with another one | Declare `application/pdf` on the file part                                                                                                                                                                           |
| `400` with `agent_id is required`, `employer is required`, `registration is required` or `file is required` | A field is missing                                                 | Send the four fields                                                                                                                                                                                                 |
| `404` on upload                                                                                             | The `agent_id` does not exist                                      | Take it from `GET /agents/`                                                                                                                                                                                          |
| A new employee appears with no email and no site                                                            | No employee had that `username`, so SONAR created one              | Check the `username` sent; register employees before sending envelopes                                                                                                                                               |
| Notifications rejected by your service                                                                      | HMAC computed on the parsed body, or wrong secret                  | Compute it on the raw bytes, with the Connect secret                                                                                                                                                                 |
| DocuSign keeps resending the same notification                                                              | Your service did not answer `200` in time                          | Acknowledge first, process asynchronously                                                                                                                                                                            |

## Rules and limits

| Item                          | Rule                                                                                           |
| ----------------------------- | ---------------------------------------------------------------------------------------------- |
| Terms per employee and device | One. Delete the old one to replace it                                                          |
| File in SONAR                 | PDF or DOCX, up to 10 MB, with its content type declared on the file part                      |
| Employee                      | `registration` is the employee's `username`; `employer` must match the employee's **Name**     |
| DocuSign API limit            | 3,000 calls per hour per account, with bursts of 500 every 30 seconds in production            |
| Status polling                | At most one query per envelope every 15 minutes. Use Connect instead of polling                |
| DocuSign token                | Valid one hour, with no refresh; build a new JWT                                               |
| Document download             | At most 3 downloads of the combined document of the same envelope per hour                     |
| Go-live                       | Moving to production requires a DocuSign go-live review. Excessive polling can fail the review |

## Vendor references

* JWT Grant: <https://developers.docusign.com/platform/auth/jwt-get-token/>
* Creating envelopes: <https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopes/create/>
* Template field values: <https://developers.docusign.com/docs/esign-rest-api/how-to/set-template-tab-values/>
* Connect JSON SIM event model: <https://developers.docusign.com/platform/webhooks/connect/json-sim-event-model/>
* Connect HMAC: <https://developers.docusign.com/platform/webhooks/connect/hmac/>
* Downloading documents: <https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopedocuments/get/>
* Rules and limits: <https://developers.docusign.com/docs/esign-rest-api/esign101/rules-and-limits/>
* Bulk send: <https://developers.docusign.com/docs/esign-rest-api/reference/bulkenvelopes/bulksend/>
* Embedded signing: <https://developers.docusign.com/docs/esign-rest-api/reference/envelopes/envelopeviews/createrecipient/>
* DocuSign in Atlassian Automation: <https://support.atlassian.com/cloud-automation/docs/use-docusign-with-automation/>

## Related pages

* [Plan an integration](https://wiki.datadike.com/sonar/administration/integrations/plan-an-integration.md)
* [Terms](https://wiki.datadike.com/sonar/administration/employees/terms.md)
* [Employees](https://wiki.datadike.com/sonar/administration/employees/employees.md)
* [Jira Service Management](https://wiki.datadike.com/sonar/administration/integrations/jira-service-management.md)
* [API](https://wiki.datadike.com/sonar/reference/api.md)
