Integrate Electronic Signatures into Your Blazor Application

Integrate Electronic Signatures into Your Blazor Application

Team BoldSign
BoldSign

--

Adding electronic signature support to your Blazor application can significantly enhance the value of your application for your end users. This integration enables you and your users to perform various eSignature tasks directly within your app, such as sending signature requests, signing documents, tracking document statuses, and downloading signed documents. By embedding these functionalities, you eliminate the need for redirecting your users to third-party webpages for capturing signatures, thereby increasing efficiency, trust, and productivity.

In this blog post, I’ll walk you through the steps to incorporate eSignatures into your Blazor application using BoldSign.

Getting started

The procedure that follows summarizes how to set up a Blazor application and add the BoldSign package to it. It is recommended that you refer to the Getting Started with BoldSign documentation for an in-depth explanation before proceeding.

  1. Sign up for a free sandbox: Sign up for a free sandbox plan to ensure you have a BoldSign account and access to the API.
  2. Create a Blazor Server app: Open your terminal or command prompt and run the following command to create a new Blazor Server application:
    dotnet new blazorserver -o BlazorEsignApp
  3. Install the BoldSign API NuGet package: Navigate to your project directory and install the BoldSign API NuGet package with the following command:
    dotnet add package BoldSign.Api
  4. Acquire BoldSign app credentials: Obtain your API credentials from the BoldSign application.

Step 1: Set up BoldSign API clients

First, you need to set up the BoldSign API clients in your Blazor application. Add the necessary services to the Program.cs file, as demonstrated in the following code:

using BoldSign.Api;

var builder = WebApplication.CreateBuilder(args);

// Add BoldSign services
var apiKey = "YOUR_API_KEY";
var apiClient = new ApiClient("https://api.boldsign.com/", apiKey);
builder.Services.AddSingleton(apiClient);
builder.Services.AddSingleton(new DocumentClient(apiClient));
builder.Services.AddSingleton(new TemplateClient(apiClient));

builder.Services.AddControllers();
builder.Services.AddRazorPages();
builder.Services.AddServerSideBlazor();

var app = builder.Build();

if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllers();

app.MapBlazorHub();
app.MapFallbackToPage("/_Host");

app.Run();

The previous code initialized the ApiClient with the BoldSign API endpoint and your API key, and then registered DocumentClient and TemplateClient as singletons in the service collection.

Step 2: Create a document using a template

Now that your Blazor project is configured, you can begin integrating eSignature functionalities using BoldSign APIs.

To streamline the document creation process for healthcare forms, such as consent forms or medical records, you can utilize predefined templates. These templates can be created using BoldSign’s web interface or API, ensuring that all necessary fields and details are included for efficient document processing.

By preparing BoldSign templates for the documents you often use, you reduce the time and effort required to generate documents, allowing for quick and accurate preparation of forms.

By default, BoldSign sends an email to signers asking them to review and sign documents. If you prefer signers to sign within your application, you can set the disableEmails parameter to true while sending a document that uses a template.

To send a document using a template and disable email notifications, you can define a method in your Blazor component or service. Here’s an example of how you can send a document from a template in your Blazor application:

private async void SendDocumentUsingTemplate()
{
var templateRole = new Roles(
roleSignerIndex: 1,
roleSignerName: signerName,
roleSignerEmailAddress: signerEmail,
locale: Locales.EN);

var roles = new List<Roles>
{
templateRole,
};
var templateDetails = new SendForSignFromTemplate(
templateId: "Your Template ID",
title: "Document from Template",
disableEmails: true,
roles: roles,
message: "This document description"
);

var createdDocumentResult = TemplateClient.SendUsingTemplate(templateDetails);
}

In this method:

  • templateId is the ID of the template you want to use.
  • title and message provide context for the document being sent.

You can customize your application UI as shown in the following image to get the signer details and add them to the roles. After getting the details, you can send the document based on the template using the previous code example.

Customized UI to get signer details
Customized UI to get signer details

Step 3: Get the embedded signing link

After invoking the SendDocumentUsingTemplate API, you will receive a response containing the document ID. Use the document ID to generate an embedded signing link for the signer. The following code will generate the signing link, which you can embed in an iFrame.

private async Task GenerateSignLinkAsync(string documentId, string signerEmail)
{
var signLinkBase = NavigationManager.BaseUri;
EmbeddedSigningLink embeddedSigningLink = await DocumentClient
.GetEmbeddedSignLinkAsync(documentId, signerEmail,
DateTime.Now.AddMinutes(10),
$"{signLinkBase}response").ConfigureAwait(false);

signlink = embeddedSigningLink.SignLink;
}

After making the API request, you will receive the signing URL in response. Once you have the signing URL, you can embed it within an iframe in your Blazor application and customize the UI to your needs, as demonstrated in the following code:

@page "/"
@using BoldSign.Api
@using BoldSign.Model
@inject NavigationManager NavigationManager
@inject TemplateClient TemplateClient
@inject DocumentClient DocumentClient

<h2 class="title">Integrate eSignature functionality using BoldSign in your Blazor application</h2>
<p>The BoldSign API provides an easy and clean interface to integrate a complete eSignature workflow into your app in a matter of minutes. </p>

<div class="form-container">
<div class="form-group">
<label for="signerName">Signer Name:</label>
<input type="text" id="signerName" @bind="signerName" placeholder="Enter signer's name" class="input-field" />
</div>
<div class="form-group">
<label for="signerEmail">Signer Email:</label>
<input type="email" id="signerEmail" @bind="signerEmail" placeholder="Enter signer's email" class="input-field" />
</div>
<button class="sign-button" @onclick=@SendDocumentUsingTemplate>Sign Document</button>
</div>

@if (!string.IsNullOrEmpty(signlink))
{
<div class="document-container">
<h5>Sign the document:</h5>
<iframe id="iframeID" src="@signlink" height="600" width="100%" class="document-frame"></iframe>
</div>
}

<style>
.title {
color: #0565FF;
font-family: Arial, sans-serif;
}
.form-container {
margin-top: 20px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
width: 100%;
max-width: 500px;
}
.form-group {
margin-bottom: 15px;
}
.input-field {
width: 100%;
padding: 8px;
margin-top: 5px;
box-sizing: border-box;
border: 1px solid #ccc;
border-radius: 4px;
}
.sign-button {
background-color: #0565FF;
color: white;
border: none;
padding: 10px 15px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 10px;
cursor: pointer;
border-radius: 4px;
width: 100%;
}
.sign-button:hover {
background-color: #004cbf;
}
.document-container {
margin-top: 30px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
}
.document-frame {
border: none;
border-radius: 4px;
}
</style>

@code {
private string signlink = string.Empty;

private string signerName;
private string signerEmail;

private async void SendDocumentUsingTemplate()
{
var templateRole = new Roles(
roleSignerIndex: 1,
roleSignerName: signerName,
roleSignerEmailAddress: signerEmail,
locale: Locales.EN);

var roles = new List<Roles>
{
templateRole,
};
var templateDetails = new SendForSignFromTemplate(
templateId: "Your Template Id",
title: "Document from Template",
disableEmails: true,
roles: roles,
message: "This document description"
);

var createdDocumentResult = TemplateClient.SendUsingTemplate(templateDetails);
await GenerateSignLinkAsync(createdDocumentResult.DocumentId, signerEmail).ConfigureAwait(false);

}

private async Task GenerateSignLinkAsync(string documentId, string signerEmail)
{
var signLinkBase = NavigationManager.BaseUri;
EmbeddedSigningLink embeddedSigningLink = await DocumentClient
.GetEmbeddedSignLinkAsync(documentId, signerEmail,
DateTime.Now.AddMinutes(10),
$"{signLinkBase}response").ConfigureAwait(false);

signlink = embeddedSigningLink.SignLink;
InvokeAsync(StateHasChanged);
}
}

The following figure shows a custom UI created for a signing page.

Customized signing page UI
Customized signing page UI

Step 4: Handle webhooks for document completion

To automate the downloading and distribution of signed documents, integrate webhook into your Blazor application. Refer to the Webhooks Introduction in the BoldSign documentation to set up webhooks. Subscribe to the Completed event, which triggers once all signers have signed the document and the final PDF is ready. Once you have set up the webhook in BoldSign, the next step is to configure your server to listen for this event and handle it appropriately, as demonstrated in the following code:

using BoldSign.Api;
using BoldSign.Model;
using BoldSign.Model.Webhook;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.Extensions.Caching.Distributed;

namespace BlazorEsignApp.Controllers;

[ApiController]
[Route("webhook")]
public class WebhookController: Controller
{
private readonly DocumentClient _documentClient;

public WebhookController(DocumentClient documentClient)
{
_documentClient = documentClient;
}

[HttpPost]
public async Task<IActionResult> HandleWebhookCallback()
{
var sr = new StreamReader(Request.Body);
var json = await sr.ReadToEndAsync();

if (Request.Headers[WebhookUtility.BoldSignEventHeader] == "Verification")
{
return Ok();
}

var SECRET_KEY = "YOUR_SECRET_KEY";

try
{
WebhookUtility.ValidateSignature(
json,
Request.Headers[WebhookUtility.BoldSignSignatureHeader],
SECRET_KEY);
}
catch (BoldSignSignatureException ex)
{
Console.WriteLine(ex);
return Forbid();
}

var eventPayload = WebhookUtility.ParseEvent(json);

if (eventPayload.Event.EventType == WebHookEventType.Completed)
{
var documentEvent = eventPayload.Data as DocumentEvent;
if (documentEvent != null)
{
await DownloadCompletedDocument(documentEvent.DocumentId);
}
}

return Ok();
}

private async Task DownloadCompletedDocument(string documentId)
{
try
{
var documentStream = await _documentClient.DownloadDocumentAsync(documentId);

if (documentStream != null)
{
var downloadsPath = @"C:\Downloads"; // Specify the path where the document should be saved

if (!Directory.Exists(downloadsPath))
{
Directory.CreateDirectory(downloadsPath);
}

var filePath = Path.Combine(downloadsPath, $"{documentId}.pdf");
await using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None);
await documentStream.CopyToAsync(fileStream);

Console.WriteLine($"Document {documentId} downloaded successfully.");
}
else
{
Console.WriteLine($"Error downloading document {documentId}: Document stream is null.");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error downloading document {documentId}: {ex}");
}
}
}

Set up the webhook URL in your BoldSign account to point to the endpoint you created (for example, https://yourapp.com/webhook).

Conclusion

Integrating BoldSign with your Blazor application is a straightforward process that enhances your application’s value and your end users’ document management capabilities. By following the steps outlined in this blog, you can easily send documents for signature using templates, embed the signing process directly within your application, and handle document completion events via webhooks.

We genuinely appreciate your feedback, so please leave a comment below. Feel free to reach out to our support team via our support portal if you have any questions or need further assistance with the integration. Happy coding!

Originally published at https://boldsign.com/on July 26, 2024.

--

--