Category / Section
How to save completed documents to Google Drive using Google Apps Script?
Published:
4 mins read
With BoldSign, you can automatically save completed documents to a specific Google Drive folder by using the Completed webhook event in Google Apps Script.
Follow the steps below to set up the integration.
Step 1: Creating a webhook endpoint in Google Apps Script
- Open your Google Spreadsheet.
- Click
Extensions
and chooseApps Script
to open the script editor. - In the Apps Script editor, click
Deploy
and selectNew deployment
.
-
The popup window will open. In the popup window:
- Click the
Settings
icon and selectWeb app
as the deployment type.
- After selecting
Web app
, a new popup window will open. Add a description. - Set Execute as:
Me
. - Set who has access:
Anyone
orAnyone with a Google account
.
- Click the
- Click
Deploy
. - The Web App URL and Deployment ID will be displayed in a new window.
- Copy the
Web App URL
shown after deployment. This will be used as the webhook endpoint in BoldSign.
Step 2: Setting up the webhook in BoldSign
- Log in to your BoldSign account.
- Navigate to the
API
section and clickWebhooks
. It will take you to the webhook dashboard. - Click
Add Webhook
.
- The popup window will open.
-
In the popup:
- Choose the callback level:
App
orAccount
. - Select the environment:
Live
,Sandbox
, orboth
.
- Enter a name for the webhook.
- Paste the Apps Script Web App URL into the
URL to publish
field. - Click
Verify
. A 200 OK response confirms the webhook is reachable.
- Select the desired Team user events and document events (e.g., Sent, Completed).
- Click
Save
.
- Choose the callback level:
Step 3: Handle the Webhook in Apps Script
- Add the following
doPost(e) function
to your Apps Script project. - This function handles webhook events from BoldSign and saves the completed document to Google Drive.
function doPost(e) {
try {
var payload = JSON.parse(e.postData.contents);
var eventId = payload.event;
// Check if the event is 'Document Completed'
if (eventId.eventType == "Completed")
{
const documentId = payload.data.documentId;
saveSignedDocument(documentId,payload.data);
}
return ContentService.createTextOutput(
JSON.stringify({ status: "success" })
).setMimeType(ContentService.MimeType.JSON);
} catch (error) {
Logger.log("Error: " + error.message);
return ContentService.createTextOutput(
JSON.stringify({ status: "error", message: error.message })
).setMimeType(ContentService.MimeType.JSON);
}
}
Step 4: Save the completed document to Google Drive
- Use the following code snippet to download the signed document and save it to a specific Google Drive folder.
- To retrieve the completed document, call the Download Document API (/v1/document/download) during the webhook’s
Completed
event. This API returns the signed document file in the response.
function saveSignedDocument(completeddocumentId,data) {
var documentId = completeddocumentId;
var apiKey = '{Your API Key}'; // Replace with your actual API key
var url = ' https://api.boldsign.com/v1/document/download?documentId=' + documentId;
var options = {
method: 'get',
headers: {
'accept': 'application/json',
'X-API-KEY': apiKey
},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options);
var blob = response.getBlob(); // Here, you will get the completed document file blob
const
name = data.signerDetails?.[0]?.signerName ||
'Unknown';
var propertiesOutput = JSON.parse(getDocumentProperties(documentId));
var companyName = propertiesOutput[0].companyName;
var position = propertiesOutput[0].position;
var completedDate = propertiesOutput[0].completedAt;
Logger.log("Company Name: " + companyName);
Logger.log("Position: " + position);
Logger.log("Completed Date: " + completedDate);
const finalName = `Signed ${position} copy of
${name} of ${companyName} dated ${completedDate}
.pdf`;
const
folderId = '1lyEexxQvRo'; // Replace with your google drive folder id
const folder = DriveApp.getFolderById(folderId);
const
file = folder.createFile(blob.setName(finalName));
// Save the file to Google Drive
Logger.log('File saved to Drive: ' + file.getUrl());
}
Step 5: Retrieve document properties to generate a completed file name with signer details
- To include signer details in the saved file name, retrieve the signer-filled form field values and the document’s completion date by calling the Properties API (/v1/document/properties) during the webhook’s
Completed
event. - Use the following code snippet to get the required values:
function getDocumentProperties(documentId) {
var apiKey = 'Your API Key'; // Replace with your actual API key
var url = ' https://api.boldsign.com/v1/document/properties?documentId=' + documentId;
var options = {
method: 'get',
headers: {
'accept': 'application/json',
'X-API-KEY': apiKey
},
muteHttpExceptions: true
};
var response = UrlFetchApp.fetch(url, options);
var result = JSON.parse(response.getContentText());
Logger.log(result);
var signerDetails = result.signerDetails || [];
var documentHistory = result.documentHistory || [];
var output = signerDetails.map(signer => {
var formFields = signer.formFields || [];
// Extract specific field values by ID
var companyName = formFields.find(field => field.id === 'CompanyName')?.value || '';
var position = formFields.find(field => field.id === 'Position')?.value || '';
var completedEvent = documentHistory.find(event =>
event.email === signer.signerEmail && event.action === "Completed"
);
var completedTimestamp = completedEvent
? new Date(completedEvent.timestamp * 1000).toISOString()
: null;
return {
completedAt: completedTimestamp,
companyName: companyName,
position: position
};
});
Logger.log(JSON.stringify(output, null, 2));
return JSON.stringify(output, null, 2);
}
- Once a document is signed and marked as completed, the webhook will automatically trigger.
- The signed document will then be downloaded and saved to your specified Google Drive folder, with a filename that includes the signer’s details such as company name, position, and date of completion.