> You are reading the Docusign Developer Documentation. For clean Markdown of any page, append .md to the page URL.
>
> Documentation indexes by section:
> - APIs and SDKs: https://docusign.docs.buildwithfern.com/docs/llms.txt
> - Platform 101: https://docusign.docs.buildwithfern.com/platform/llms.txt
> - Extension Apps: https://docusign.docs.buildwithfern.com/extension-apps/llms.txt
> - Docusign CLI: https://docusign.docs.buildwithfern.com/docusign-cli/llms.txt
>
> Authentication (OAuth, JWT Grant, M2M): https://docusign.docs.buildwithfern.com/platform/auth
> Webhooks and Connect: https://docusign.docs.buildwithfern.com/platform/webhooks
>
> OpenAPI specifications: https://docusign.docs.buildwithfern.com/openapi.json
> MCP server: https://docusign.docs.buildwithfern.com/_mcp/server

# How to embed an elastic signing agreement

> This page shows how to embed an agreement into your site by using an elastic template and the GetCode JavaScript in the web UI.

This topic demonstrates how to embed an agreement using an elastic template with a unique agreement link and dynamic content using the [ClickWraps:createHasAgreed](/docs/click-api/reference/accounts/clickwraps/createhasagreed) method.

> **Important:** You must  [create](/docs/click-api/how-to/create-elastic-templates), [activate](/docs/click-api/how-to/activate-elastic-template), and [add dynamic content](/docs/click-api/click101/customize-elastic-template-fields#add-dynamic-content-to-your-elastic-template)  to a elastic template to complete this how-to.

> **Note**
>
> Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects: [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).

## Required data

Running the code in this how-to requires this data:

| Data element                     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    |
| -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| \{API_ACCOUNT_ID}                | A [GUID](http://guid.one/) value that identifies your account. This value is automatically generated by Docusign for any account you create. Copy the value from the **API Account ID** field on the [Apps and Keys](https://admindemo.docusign.com/authenticate?goTo=appsAndKeys) page.                                                                                                                                                                                                                                                                                                                                                                                       |
| \{BASE_PATH}                     | A string value that forms the root of the URL required to make API calls. The base path value in the example code is set to target the developer environment at https\://\<domain>/clickapi Where \<domain> is demo.docusign.net for the developer environment and is the result of the GetUserInfo call in production.                                                                                                                                                                                                                                                                                                                                                        |
| \{CLICKWRAP_ID}                  | A [GUID](http://guid.one/) value that identifies an individual elastic template. You can obtain this value by following the steps in [How to get a list of elastic templates](/docs/click-api/how-to/retrieve-elastic-templates).                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Elastic template dynamic content | Elastic template [dynamic content](/docs/click-api/click101/customize-elastic-template-fields) enables you to add customized field values to each instance of a elastic template agreement. This is the set of fields that appears on a given elastic template document within the **INSERT DATA** editor.                                                                                                                                                                                                                                                                                                                                                                     |
| \{CLIENT_USER_ID}                | A unique identifier for a user that should originate from your own system. Docusign uses this value to identify each user. Note that:- This value can be anything your backend system will use to track individual users. Examples include employee IDs, email addresses, and surrogate key values.
- The Click API uses the client user ID, API account ID, and clickwrap ID to track which users have already accepted an elastic signing agreement.
- An elastic template agreement will not appear again after it has been accepted with a given client user ID. The client user ID needs to be updated to a new, unique value each time the elastic template is embedded. |

## Step 1. Obtain your OAuth token

To make the API call shown in this how-to, you need a valid OAuth access token. Docusign supports access tokens for three different recommended OAuth grant types: Public Authorization Code Grant, Confidential Authorization Code Grant, and JSON Web Token (JWT) Grant. Choose the OAuth grant type appropriate for your scenario.

> **Note**
>
> See [Authentication](/docs/click-api/click101/auth) for guidance on your options to get an OAuth token.

![Three icons that represent the three methods a user can use to obtain an OAuth token: JSON Web Token (JWT), Public Authorization Code Grant (ACG), and Confidential Authorization Code grant](/_fern-files/_img/64f473773042ee439449a096bf7673292b1585b86a4ccc55f82ba0dda41f61a1.webp)

## Step 2. Construct your API headers

After you have a valid OAuth access token, you are ready to construct the API headers that you will pass to the API call. Construct your headers like this, but make sure to substitute your valid OAuth access token for \{ACCESS_TOKEN}.

**`Bash`**

```bash title="Bash"
declare -a Headers=('--header' "Authorization: Bearer ${ACCESS_TOKEN}"
    '--header' "Content-Type: application/json"
    '--header' "Accept: application/json")
```

**`C#`**

```csharp title="C#"
var docuSignClient = new DocuSignClient(basePath);
docuSignClient.Configuration.DefaultHeader.Add("Authorization", "Bearer " + accessToken);
var clickAccountApi = new AccountsApi(docuSignClient);
```

**`Java`**

```java title="Java"
ApiClient apiClient = new ApiClient(basePath);
apiClient.addDefaultHeader(HttpHeaders.AUTHORIZATION, BEARER_AUTHENTICATION + userAccessToken);
apiClient.addAuthorization("docusignAccessCode", new OAuth());
return apiClient;
```

**`Node.js`**

```javascript title="Node.js"
const dsApiClient = new docusignClick.ApiClient();
dsApiClient.setBasePath(args.basePath);
dsApiClient.addDefaultHeader('Authorization', 'Bearer ' + args.accessToken);
```

**`PHP`**

```php title="PHP"
$config = new Configuration();
$config->setHost('https://demo.docusign.net/clickapi');
$config->addDefaultHeader('Authorization', 'Bearer ' . $args['ds_access_token']);
$this->apiClient = new ApiClient($config);
```

**`PowerShell`**

```text title="PowerShell"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", "Bearer $accessToken")
$headers.add("Accept", "application/json")
$headers.add("Content-Type", "application/json")
```

**`Python`**

```python title="Python"
api_client = create_click_api_client(
    access_token=args["access_token"]
)
```

**`Ruby`**

```ruby title="Ruby"
configuration = DocuSign_Click::Configuration.new
configuration.host = args[:base_path]

api_client = DocuSign_Click::ApiClient.new configuration
api_client.set_default_header('Authorization', "Bearer #{args[:access_token]}")
```

## Step 3. Construct the request body

Next, create the request body. The metadata provided in the gist matches the available dynamic fields in the **INSERT DATA** editor.

**`Bash`**

```bash title="Bash"
request_data=$(mktemp /tmp/request-cw-001.XXXXXX)
printf \
    '
    {
  "clientUserId": "'"$client_user_id"'",
  "documentData": {
    "fullName": "'"$full_name"'",
    "email": "'"$email_address"'",
    "company": "'"$company_name"'",
    "title": "'"$title"'",
    "date": "'"$(date -I)"'"
  }
  }' >$request_data
```

**`C#`**

```csharp title="C#"
var userAgreementRequest = new UserAgreementRequest { DocumentData = new Dictionary<string, string>() };
userAgreementRequest.DocumentData.Add("fullName", fullName);
userAgreementRequest.DocumentData.Add("email", email);
userAgreementRequest.DocumentData.Add("company", company);
userAgreementRequest.DocumentData.Add("title", title);
userAgreementRequest.DocumentData.Add("date", date);

userAgreementRequest.ClientUserId = email;

return userAgreementRequest;
```

**`Java`**

```java title="Java"
UserAgreementRequest userAgreementRequest = new UserAgreementRequest();
userAgreementRequest.setClientUserId(email);
Map<String, String> documentData = new HashMap<String, String>();
documentData.put("fullName", fullName);
documentData.put("email", email);
documentData.put("company", company);
documentData.put("title", title);
documentData.put("date", date);
userAgreementRequest.setDocumentData(documentData);
```

**`Node.js`**

```javascript title="Node.js"
const userAgreement = new docusignClick.UserAgreementRequest.constructFromObject({
  clientUserId: documentArgs.email,
  documentData: {
   fullName: documentArgs.fullName,
   email: documentArgs.email,
   company: documentArgs.company,
   title: documentArgs.jobTitle,
   date: documentArgs.date,
  },
 //  requireReacceptance: true,
});
```

**`PHP`**

```php title="PHP"
$accountsApi = $clientService->accountsApi();
$documentData = new UserAgreementRequest();
$documentData->setClientUserId($args["email_address"]);
$rawData  = [
    'fullName' => $args["full_name"],
    'email' => $args["email_address"],
    'company' => $args["company"],
    'title' => $args['job_title'],
    'date' => $args['date']
];
$documentData->setDocumentData($rawData);
```

**`PowerShell`**

```text title="PowerShell"
$requestData = New-TemporaryFile
$response = New-TemporaryFile

@{
  clientUserId = $client_user_id;
  documentData =
  @{
    fullName = $full_name;
    email    = $email_address;
    company  = $company_name;
    title    = $title;
    date     = $((Get-Date).ToString("yyyy-MM-ddThh:mm:ssK"))
  };
}  | ConvertTo-Json -Depth 32 > $requestData
```

**`Python`**

```python title="Python"
user_agreement_request = UserAgreementRequest(
    client_user_id=args["email"],
    document_data={
        "fullName": args["fullName"],
        "email": args["email"],
        "company": args["company"],
        "title": args["title"],
        "date": args["date"]
    },
)
```

**`Ruby`**

```ruby title="Ruby"
document_data = {
  'fullName' => args[:full_name],
  'email' => args[:email],
  'company' => args[:company],
  'title' => args[:title],
  'date' => args[:date]
}

userAgreementRequest = DocuSign_Click::UserAgreementRequest.new({
                                                                  clientUserId: args[:email],
                                                                  documentData: document_data
                                                                })
```

## Step 4. Call the Click API

Now that you have constructed your API headers and request body, make a POST request to the Click API and include the request body to populate the dynamic fields within your elastic signing agreement. Here’s how you make the call, but make sure to substitute your API account ID for \{account_id} and elastic template ID for \{clickwrap_id}.

> **Note:** For compatibility with previous versions of the Click API, elastic templates use clickwrap endpoints.

> **Note**
>
> View the source code for this how-to on GitHub: [Bash](https://github.com/docusign/code-examples-bash/blob/master/examples/Click/eg006EmbedClickwrap.sh), [C#](https://github.com/docusign/code-examples-csharp/blob/master/launcher-csharp/Click/Examples/EmbedClickwrap.cs), [Java](https://github.com/docusign/code-examples-java/blob/master/src/main/java/com/docusign/controller/click/services/EmbedClickwrapService.java), [Node.js](https://github.com/docusign/code-examples-node/blob/master/lib/click/examples/embedClickwrap.js), [PHP](https://github.com/docusign/code-examples-php/blob/master/src/Services/Examples/Click/EmbedClickwrapService.php/), [PowerShell](https://github.com/docusign/code-examples-powershell/blob/master/examples/Click/eg006EmbedClickwrap.ps1), [Python](https://github.com/docusign/code-examples-python/blob/master/app/click/examples/eg006_embed_clickwrap.py), or [Ruby](https://github.com/docusign/code-examples-ruby/blob/master/app/services/clickwrap/eg006_embed_clickwrap_service.rb).

**`Bash`**

```bash title="Bash"
response=$(mktemp /tmp/response-cw.XXXXXX)

curl --request POST https://demo.docusign.net/clickapi/v1/accounts/${account_id}/clickwraps/${clickwrap_id}/agreements \
    "${Headers[@]}" \
    --data-binary @${request_data} \
    --output ${response}
```

**`C#`**

```csharp title="C#"
var userAgreementRequest = BuildUpdateClickwrapHasAgreedRequest(fullName, email, company, title, date);

var response = clickAccountApi.CreateHasAgreedWithHttpInfo(accountId, clickwrapId, userAgreementRequest);
response.Headers.TryGetValue("X-RateLimit-Remaining", out string remaining);
response.Headers.TryGetValue("X-RateLimit-Reset", out string reset);

if (reset != null && remaining != null)
{
    DateTime resetDate = DateTimeOffset.FromUnixTimeSeconds(long.Parse(reset)).UtcDateTime;
    Console.WriteLine("API calls remaining: " + remaining);
    Console.WriteLine("Next Reset: " + resetDate);
}

if (response.StatusCode == 201)
{
    return response.Data;
}
else
{
    // This typically means that the agreement was already agreed
    var errorAlreadyAgreed = new UserAgreementResponse();
    errorAlreadyAgreed.AgreementUrl = "Already Agreed";
    return errorAlreadyAgreed;
}
```

**`Java`**

```java title="Java"
ApiResponse<UserAgreementResponse> response = accountsApi.createHasAgreedWithHttpInfo(accountId, clickwrapId,
        userAgreementRequest);

Map<String, List<String>> headers = response.getHeaders();
List<String> remaining = headers.get("X-RateLimit-Remaining");
List<String> reset = headers.get("X-RateLimit-Reset");

if (remaining != null & reset != null) {
    Instant resetInstant = Instant.ofEpochSecond(Long.parseLong(reset.get(0)));
    System.out.println("API calls remaining: " + remaining);
    System.out.println("Next Reset: " + resetInstant);
}

if (response.getStatusCode() == 201) {
    return response.getData().getAgreementUrl();
}
return "Already Agreed";
```

**`Node.js`**

```javascript title="Node.js"
const accountApi = new docusignClick.AccountsApi(dsApiClient);

// Embed the clickwrap
const result = await new Promise((resolve, reject) => {
  accountApi.createHasAgreed(
 args.accountId, args.clickwrapId, {
   userAgreementRequest: userAgreement
 },
  (err, data, response) => {
      if (err) return reject(err);
      resolve({ data, response });
    });
  });

const headers = result.response.headers;
const remaining = headers['x-ratelimit-remaining'];
const reset = headers['x-ratelimit-reset'];

if (remaining && reset) {
  const resetInstant = new Date(Number(reset) * 1000);
  console.log(`API calls remaining: ${remaining}`);
  console.log(`Next Reset: ${resetInstant.toISOString()}`);
}
```

**`PHP`**

```php title="PHP"
$response =  $accountsApi->createHasAgreedWithHttpInfo($args['account_id'], $args['clickwrap_id'], $documentData);

$remaining = $response[2]['X-RateLimit-Remaining'] ?? null;
$reset = $response[2]['X-RateLimit-Reset'] ?? null;

if ($remaining !== null && $reset !== null) {
    $resetInstant = (new DateTime())->setTimestamp((int)$reset);
    error_log("API calls remaining: $remaining");
    error_log("Next Reset: " . $resetInstant->format(\DateTime::ATOM));
}

if ($response[0]->getStatus() == "created") {
    return $response[0]->getAgreementUrl();
} else {
    return "Already Agreed";
}
```

**`PowerShell`**

```text title="PowerShell"
Invoke-RestMethod `
-Uri "https://demo.docusign.net/clickapi/v1/accounts/$APIAccountId/clickwraps/$ClickWrapId/agreements" `
-UseBasicParsing `
-Method "POST" `
-Headers @{
"Authorization" = "Bearer $accessToken"
"Content-Type"  = "application/json"
"Accept" = "application/json"
} `
-InFile (Resolve-Path $requestData).Path `
-OutFile $response
```

**`Python`**

```python title="Python"
accounts_api = AccountsApi(api_client)
clickwrap = ast.literal_eval(args["clickwrap"])
print(type(clickwrap))
(response, status, headers) = accounts_api.create_has_agreed_with_http_info(
    account_id=args["account_id"],
    clickwrap_id=clickwrap["clickwrap_id"],
    user_agreement_request=user_agreement_request,
)

remaining = headers.get("X-RateLimit-Remaining")
reset = headers.get("X-RateLimit-Reset")

if remaining is not None and reset is not None:
    reset_date = dt.fromtimestamp(int(reset), tz=timezone.utc)
    print(f"API calls remaining: {remaining}")
    print(f"Next Reset: {reset_date}")
```

**`Ruby`**

```ruby title="Ruby"
accounts_api = DocuSign_Click::AccountsApi.new(api_client)

response, _status, headers = accounts_api.create_has_agreed_with_http_info(args[:account_id], args[:clickwrap_id], userAgreementRequest)

remaining = headers['X-RateLimit-Remaining']
reset = headers['X-RateLimit-Reset']

if remaining && reset
  reset_date = Time.at(reset.to_i).utc
  puts "API calls remaining: #{remaining}"
  puts "Next Reset: #{reset_date}"
end

response.as_json
```

## Expected response

Copy the `agreementUrl` from the JSON response and paste it in the corresponding line in the HTML in the next step.

**`JSON`**

```json title="JSON"
{
  "accountId": "d4bb3256-xxxx-xxxx-xxxx-87abac8ebd46",
  "clickwrapId": "b85992df-xxxx-xxxx-xxxx-e1c524e8a6bd",
  "clientUserId": "1013ps1",
  "agreementId": "4532d6d0-xxxx-xxxx-xxxx-521d3abba8c3",
  "documents": [
    {
      "documentName": "Terms of Service",
      "order": 1,
      "fileExtension": "pdf"
    }
  ],
  "consumerDisclosureEnabled": true,
  "agreementUrl": "https://demo.docusign.net/clickapi/v1/redeem?agreementToken=AcTZT8…P5gvB0",
  "createdOn": "2022-10-07T16:19:17.7350578Z",
  "status": "created",
  "versionId": "869800a8-xxxx-xxxx-xxxx-997a7f6a5a8b",
  "versionNumber": 1,
  "settings": {
    "displayName": "Terms of Service",
    "hasDeclineButton": false,
    "actionButtonAlignment": "left",
    "mustRead": true,
    "mustView": false,
    "requireAccept": true,
    "downloadable": true,
    "sendToEmail": false,
    "consentButtonText": "I Agree",
    "allowClientOnly": true,
    "format": "modal",
    "documentDisplay": "document",
    "statementAlignment": "bottom"
  },
  "documentData": {
    "email": "larry.lee@mail.com",
    "title": "General Counsel",
    "fullName": "Larry Lee",
    "company": "Tally",
    "date": "2022-10-13T05:17:14-07:00"
"
  }
}
```

## Step 5. Write your HTML for embedding the elastic template

Write the code you need to embed your elastic template on your web page. This includes three HTML tags:

* A `<div>` that identifies where on your web page the elastic template should render
* Two `<script>` tags:

  * One that calls the Docusign elastic template JavaScript library
  * Another that calls the Docusign `Clickwrap.render` method from the JavaScript library

    * Paste the `agreementUrl` that is generated in the prior step

**`HTML`**

```json title="HTML"
<div id="ds-terms-of-service"></div>
<script src="https://demo.docusign.net/clickapi/sdk/latest/docusign-click.js"></script>
<script>docuSignClick.Clickwrap.render({
  agreementUrl: "https://demo.docusign.net/clickapi/v1/redeem?agreementToken=AcTZT8…P5gvB0",
  onAgreed: function() {
    // Triggered if the user has just agreed
  }
}, "#ds-terms-of-service");
</script>
```

## Expected response

You can paste the HTML gist with your unique `agreementUrl` into an [HTML editor](https://www.w3schools.com/html/tryit.asp?filename=tryhtml_intro) to preview your elastic template with dynamic content.

![Previewing your elastic template](/_fern-files/_img/97ba491cd21ed23ec72cb77c5ee7ab4019f0955773e4d4970017859f57d9884c.webp)

## Next steps

* Run this code example from our [Quickstart](/docs/esign-rest-api/quickstart) or launcher projects:    [Bash](https://github.com/docusign/code-examples-bash), [C#](https://github.com/docusign/code-examples-csharp), [Java](https://github.com/docusign/code-examples-java), [Node.js](https://github.com/docusign/code-examples-node), [PHP](https://github.com/docusign/code-examples-php), [PowerShell](https://github.com/docusign/code-examples-powershell), [Python](https://github.com/docusign/code-examples-python), or [Ruby](https://github.com/docusign/code-examples-ruby).
* Learn [How to customize a elastic template's appearance](/docs/click-api/how-to/customize-elastic-template-appearance).
* See [How to get a list of elastic templates](/docs/click-api/how-to/retrieve-elastic-templates).
* See how to [Go-Live](/docs/click-api/go-live) with a completed app and find the base path for API calls in the production environment.
* See the list of [Click event callbacks](/docs/click-api/click101/callbacks)