TL;DR: Subscribe a webhook to the Completed event, and BoldSign calls your server when the last signer finishes. Your handler checks the signature, then calls the download endpoint with the document ID and saves the PDF. Our eSignature API page shows what else you can automate.
Your sales team sends 50 contracts a week through your app. Someone then opens each completed one, downloads the PDF and files it in the customer record. One missed file leaves a closed deal with no signed copy on record.
A webhook removes that manual step. This guide explains how webhook callbacks work, then shows code that downloads each signed document on its own.
What is a webhook callback?
A webhook callback is a message one app sends to another when something happens. You give BoldSign a web address, and we send a request to it when a document event occurs.
Think of a courier who rings your doorbell when a parcel arrives. You skip standing at the window all day to watch the street. Checking the API on a timer, called polling, is the window, and a webhook is the doorbell.
Which webhook event tells you a document is fully signed?
The Completed event fires once every recipient has signed. Use it for downloads, since the PDF is final at that point.
The Signed event fires each time one recipient signs, so a three-signer contract sends it three times. Our list of available events also covers Declined, Expired and Revoked.
How do you set up a webhook in BoldSign?
Add the webhook in the web app and subscribe it to the Completed event. BoldSign checks your address before it saves the webhook.
- Go to API, then Webhooks, and select Add Webhook.
- Choose Account Level, name the webhook and enter a public https address.
- Select the Completed event.
- Select Verify. Your endpoint must reply with status 200 within 10 seconds.
- Select Save.
The Verify step sends an event with the type Verification, which the samples below answer straight away. Account-level webhooks cover documents sent from the web app or the API. Our guide to app-level and account-level webhooks explains when to pick each one.
The webhooks introduction and the webhook setup guide show each screen.
How do you check that a webhook came from BoldSign?
Each request carries an X-BoldSign-Signature header with a timestamp and one or two signatures. Recompute the signature with your webhook secret, and reject the request when the values differ.
The header looks like t=1668693823, s0=.... The s0 value comes from your current secret. An s1 value appears only while an old secret stays valid after you roll it.
To build the check, join the timestamp, a full stop and the raw request body. Hash that text with your secret using a hash-based message authentication code (HMAC) with SHA256. Then compare the result with each signature in constant time.
Read the body before any framework parses it, since a change in spacing breaks the match. Find the secret on the webhook’s overview page by selecting Reveal. The samples also reject events older than 300 seconds, which blocks replayed requests.
Our docs to verify webhook events show the check in more languages.
How do you download the signed document when the webhook arrives?
Read the document ID from the event’s data, then call GET /v1/document/download with it and your API key. The response body is the signed PDF, ready to save.
Each sample listens on /webhook, answers the Verification event and checks the signature. On a Completed event, it downloads the file. Replace the secret, the API key and the folder path with your own.
namespace BoldSignWebhookListener
{
using System;
using System.IO;
using System.Threading.Tasks;
using BoldSign.Api;
using BoldSign.Model.Webhook;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("webhook")]
public class WebhookExampleController : ControllerBase
{
[HttpPost]
public async Task Webhook()
{
var sr = new StreamReader(this.Request.Body);
var json = await sr.ReadToEndAsync();
if (this.Request.Headers[WebhookUtility.BoldSignEventHeader] == "Verification")
{
return this.Ok();
}
// TODO: Update your webhook secret key.
var SECRET_KEY = "<<>>";
try
{
WebhookUtility.ValidateSignature(
json,
this.Request.Headers[WebhookUtility.BoldSignSignatureHeader],
SECRET_KEY);
}
catch (BoldSignSignatureException ex)
{
Console.WriteLine(ex);
return this.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 this.Ok();
}
private async Task DownloadCompletedDocument(string documentId)
{
try
{
var apiClient = new ApiClient("https://api.boldsign.com", "{Your API Key}");
var documentClient = new DocumentClient(apiClient);
var documentStream = documentClient.DownloadDocument(documentId);
// Check if the document stream is not null.
if (documentStream != null)
{
// Specify the path where the document should be saved.
var downloadsPath = @"{Specify the path where the document should be saved}";
// Ensure the directory exists
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}");
}
}
}
}
from flask import Flask, request, jsonify
import hashlib
import requests
import os
import hmac
import time
import json
app = Flask(__name__)
# TODO: Update your webhook secret key
SECRET_KEY = "<<>>"
class BoldSignWebhookError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
class BoldSignHelper:
@staticmethod
def is_from_boldsign(signature: str, body: str, secretKey: str, tolerance=300) -> bool:
parsed = BoldSignHelper.parse_header(signature)
timestamp = parsed.timestamp
signatures = parsed.signatures
if timestamp == -1:
raise BoldSignWebhookError("Unable to parse timestamp")
if not signatures:
raise BoldSignWebhookError(
"Unable to find any signature from the provided header value"
)
computedSignature = hmac.new(
key=secretKey.encode("utf-8"),
msg=(str(timestamp) + "." + body).encode("utf-8"),
digestmod=hashlib.sha256,
).hexdigest()
matched = any(hmac.compare_digest(sign, computedSignature) for sign in signatures)
if not matched:
raise BoldSignWebhookError("HMAC SHA256 signatures don't match")
age = time.time() - timestamp
if tolerance > 0 and age > tolerance:
raise BoldSignWebhookError("Event is outside of the timestamp age tolerance")
return True
@staticmethod
def parse_header(header: str):
class ParsedHeader:
def __init__(self, timestamp, signatures):
self.timestamp = timestamp
self.signatures = signatures
if not header:
raise BoldSignWebhookError("Signature header value seems to be empty")
timestamp = -1
signatures = []
for item in header.split(","):
x, y = item.strip().split("=")
if x == "t":
timestamp = int(y)
elif x in ["s0", "s1"]:
signatures.append(y)
return ParsedHeader(timestamp, signatures)
@app.route("/webhook", methods=["POST"])
def webhook():
payload = request.data.decode("utf-8")
event_header = request.headers.get("X-BoldSign-Event")
if event_header == "Verification":
return jsonify(success=True), 200
header = request.headers.get("X-BoldSign-Signature")
try:
BoldSignHelper.is_from_boldsign(header, payload, SECRET_KEY)
except BoldSignWebhookError as e:
return jsonify(error=str(e)), 400
# Handle the event.
if event_header == "Completed":
payload_json = json.loads(payload)
url = (
"https://api.boldsign.com/v1/document/download?documentId="
+ payload_json["data"]["documentId"]
)
# Change this to your desired directory.
output_directory = "{Change this to your desired directory}"
# Make sure the output directory exists, create it if not.
if not os.path.exists(output_directory):
os.makedirs(output_directory)
filename = os.path.join(output_directory, payload_json["data"]["documentId"] + ".pdf")
payload = {}
headers = {"accept": "application/json", "X-API-KEY": "{Your API Key}"}
response = requests.request("GET", url, headers=headers, data=payload)
if response.status_code == 200:
with open(filename, "wb") as f:
f.write(response.content)
print("File downloaded successfully to:", filename)
else:
print("Error downloading file:", response.text)
return jsonify(success=True), 200
if __name__ == "__main__":
app.run(port=3000)
const express = require("express");
const bodyParser = require("body-parser");
const crypto = require("crypto");
function parseHeader(header) {
if (typeof header !== "string") {
return null;
}
return header.split(",").reduce(
(dest, item) => {
const key = item.trim().split("=");
if (key[0] === "t") {
dest.timestamp = parseInt(key[1], 10);
}
if (["s0", "s1"].includes(key[0])) {
dest.signatures.push(key[1]);
}
return dest;
},
{
timestamp: -1,
signatures: [],
},
);
}
function secureCompare(a, b) {
a = Buffer.from(a);
b = Buffer.from(b);
if (a.length !== b.length) {
return false;
}
if (crypto.timingSafeEqual) {
return crypto.timingSafeEqual(a, b);
}
const len = a.length;
let result = 0;
for (let i = 0; i < len; ++i) {
result |= a[i] ^ b[i];
}
return result === 0;
}
function isFromBoldSign(signatureHeader, payload, secretKey) {
const parsed = parseHeader(signatureHeader);
if (!parsed) {
throw new Error("BoldSign signatures don't exist");
}
const signatureMatched = parsed.signatures
.map((x) => {
return crypto
.createHmac("sha256", secretKey)
.update(parsed.timestamp + "." + payload, "utf8")
.digest("hex");
})
.some((x) => {
return parsed.signatures.some((y) => secureCompare(x, y));
});
if (!signatureMatched) {
throw new Error("Unable to verify the signatures");
}
// 5 mins in seconds is a safer choice, you can adjust if you prefer it.
const tolerance = 300;
const timestampAge = Math.floor(Date.now() / 1000) - parsed.timestamp;
// Check for time tolerance to prevent replay attacks.
if (tolerance > 0 && timestampAge > tolerance) {
throw new Error("Exceeded allowed tolerance range");
}
return true;
}
const app = express();
const PORT = 3000;
// Middleware to verify BoldSign webhook signatures.
app.post("/webhook", bodyParser.raw({ type: "application/json" }), (req, res) => {
const eventType = req.headers["x-boldsign-event"];
if (eventType === "Verification") {
res.sendStatus(200);
return;
}
const signature = req.headers["x-boldsign-signature"];
const payload = req.body.toString("utf-8");
// TODO: Update your webhook secret key
const SECRET_KEY = "<<>>";
let isValid = false;
try {
isValid = isFromBoldSign(signature, payload, SECRET_KEY);
} catch (e) {
console.error(e.message);
res.sendStatus(400);
return;
}
if (!isValid) {
res.sendStatus(403);
return;
}
// Handle the event.
console.log("Event received:", eventType);
if (eventType === "Completed") {
const axios = require("axios");
const fs = require("fs");
const path = require("path");
const payloadObject = JSON.parse(payload);
// Make the request to download the document.
axios
.get("https://api.boldsign.com/v1/document/download", {
params: {
"documentId": payloadObject.data.documentId,
},
responseType: "stream",
headers: {
"accept": "application/json",
"X-API-KEY": "{Your API Key}",
},
})
.then((response) => {
// Specify the directory where you want to save the file.
const directory = "{Specify the directory where you want to save the file}";
// If the directory does not exist, create it.
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory);
}
// Set the file path where you want to save the file.
const filePath = path.join(directory, `${payloadObject.data.documentId}.pdf`);
// Create a writable stream to save the file.
const writer = fs.createWriteStream(filePath);
// Pipe the response stream to the file stream.
response.data.pipe(writer);
// Listen for the 'finish' event to know when the file is fully written.
writer.on("finish", () => {
console.log(
`File ${payloadObject.data.documentId}.pdf downloaded and saved successfully.`,
);
});
// Listen for errors.
writer.on("error", (err) => {
console.error(`Error downloading or saving file: ${err}`);
});
})
.catch((error) => {
console.error(`Error downloading document: ${error}`);
});
}
res.sendStatus(200);
});
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Http;
use Exception;
class BoldSignWebhookController extends Controller
{
private const SECRET_KEY = '<<<Secret Key>>>';
private function parseHeader($header) {
if (!is_string($header)) {
return null;
}
$result = [
'timestamp' => -1,
'signatures' => [],
];
$items = explode(",", $header);
foreach ($items as $item) {
$key = explode("=", trim($item));
if ($key[0] === 't') {
$result['timestamp'] = intval($key[1], 10);
}
if (in_array($key[0], ['s0', 's1'])) {
$result['signatures'][] = $key[1];
}
}
return (object) $result;
}
private function secureCompare($a, $b) {
if (strlen($a) !== strlen($b)) {
return false;
}
return hash_equals($a, $b);
}
private function isFromBoldSign($signatureHeader, $payload, $secretKey)
{
$parsed = $this->parseHeader($signatureHeader);
if (!$parsed) {
throw new Exception("BoldSign signatures don't exist");
}
$signatureMatched = false;
foreach ($parsed->signatures as $signature) {
$computedSignature = hash_hmac('sha256', $parsed->timestamp . "." . $payload, $secretKey);
if ($this->secureCompare($computedSignature, $signature)) {
$signatureMatched = true;
break;
}
}
if (!$signatureMatched) {
throw new Exception("Unable to verify the signatures");
}
$tolerance = 300;
$timestampAge = time() - $parsed->timestamp;
if ($tolerance > 0 && $timestampAge > $tolerance) {
throw new Exception("Exceeded allowed tolerance range");
}
return true;
}
public function handleWebhook(Request $request) {
$eventType = $request->header('x-boldsign-event');
if ($eventType == "Verification") {
return response()->json(['status' => 'verified'], 200);
}
$signature = $request->header('x-boldsign-signature');
$payload = $request->getContent();
try {
$isValid = $this->isFromBoldSign($signature, $payload, self::SECRET_KEY);
} catch (Exception $e) {
Log::error($e->getMessage());
return response()->json(['error' => 'Bad Request'], 400);
}
if (!$isValid) {
return response()->json(['error' => 'Forbidden'], 403);
}
// Handle the event.
if ($eventType === "Completed") {
$this->handleCompletedEvent(json_decode($payload, true));
}
return response()->json(['status' => 'success'], 200);
}
private function handleCompletedEvent($payloadObject) {
$documentId = $payloadObject['data']['documentId'];
$apiKey = '{Your API Key}';
$directory = '{Specify the directory where you want to save the file}';
$response = Http::withHeaders([
'accept' => 'application/json',
'X-API-KEY' => $apiKey,
])->get('https://api.boldsign.com/v1/document/download', [
'documentId' => $documentId,
]);
if ($response->successful()) {
if (!is_dir($directory)) {
mkdir($directory, 0755, true);
}
$filePath = $directory . '/' . $documentId . '.pdf';
file_put_contents($filePath, $response->body());
Log::info("File {$documentId}.pdf downloaded and saved successfully.");
} else {
Log::error("Error downloading document: " . $response->body());
}
}
}
Expose your local server with a tunnel to test on your own computer. Our guide on setting up your endpoint to listen for callbacks uses Cloudflare Tunnel for this.
The download document reference lists the optional onBehalfOf and format settings. For a download you start yourself, see our guide on how to download an eSigned document via API.
What should you watch out for in production?
The samples download the file before they reply, which works for a test. In production, reply with status 200 first and download in a background job, since we wait only 10 seconds.
- Store each event ID and skip repeats, since retries and resends can deliver an event twice.
- Expect retries for a failed delivery, spaced from 1 minute up to 24 hours.
- Keep the API key and webhook secret in environment variables instead of code.
- Name each file by its document ID, so a repeat download overwrites the same file.
- Accept calls only from our addresses, as our webhook allow-list guide explains.
After six failed retries, we watch the webhook for 7 days and may disable it. Our post on webhook retries, duplicates and event order covers each case in depth.
Need the audit trail too? Our guide to downloading audit trails with the API uses the same document ID.
Which BoldSign API plan do you need, and what does it cost?
Webhooks and live API requests need the Enterprise API plan, from $30 a month with 40 envelopes as of November 2026. Each extra envelope costs $0.75 on our BoldSign pricing page, and prices are in USD.
To build and test first, use the free sandbox. It needs no credit card, and its documents carry a test watermark and are deleted after 14 days.
Where do you go next with webhook downloads?
Start with one webhook on the Completed event and a test document with two signers.
- Create a free API sandbox account and run one of the samples.
- Book a demo to talk through your signing workflow with our team.
- Open a support ticket when a webhook fails to verify.
Frequently asked questions
What is a webhook callback in BoldSign?
It is a request we send to your server when something happens to a document, such as the last signer finishing. Your server reads it and decides what to do next.
Which webhook event tells me a document is fully signed?
Use the Completed event. It fires once all recipients have signed, while the Signed event fires each time one recipient signs.
How do I check that a webhook really came from BoldSign?
Hash the timestamp and raw request body with your webhook secret using a hash-based message authentication code (HMAC). Compare the result with the s0 or s1 value in the X-BoldSign-Signature header.
How fast must my endpoint answer a webhook?
Within 10 seconds, with status 200. A late or failed reply counts as a failed delivery, and we retry it up to six times.
Can the same Completed event arrive twice?
Yes. Retries and manual resends can deliver an event more than once, so store each event ID and skip the ones you have already handled.
Are there e signature APIs with webhook support and direct database sync to eliminate manual re-entry entirely?
Our API sends a webhook for each document event, and your handler can then download the PDF and save its details in your database. That last step runs in your own code, so you decide what gets stored.
Can I test webhooks without paying?
Yes. A free API sandbox account gives you full API access for testing, with no credit card. Test documents carry a watermark and are deleted after 14 days.
Can I download the audit trail as well as the signed PDF?
Yes. The audit trail has its own download request that takes the same document ID. Call it from the same Completed handler.