Skip to content

Cookbook

Archive signed documents to Google Drive

Upload the signed PDF to a Google Drive folder when a deliverable is generated, using a service account and the Drive API v3.

Keep a copy of every signed document in a Google Drive folder. When deliverable.generated arrives, the handler downloads the signed PDF and uploads it with the Drive API v3.

What you need

  • A webhook endpoint subscribed to deliverable.generated (set up webhooks).
  • A Google Cloud service account with the Drive API enabled, and a Drive folder shared with the service account’s email address as an editor.
  • SIGNATUREAPI_KEY, SIGNATUREAPI_WEBHOOK_SECRET, DRIVE_FOLDER_ID, and GOOGLE_APPLICATION_CREDENTIALS pointing at the service account key file.

The handler

Node.js
// npm install express standardwebhooks googleapis
import { Readable } from "node:stream";
import express from "express";
import { Webhook } from "standardwebhooks";
import { google } from "googleapis";

const drive = google.drive({
  version: "v3",
  auth: new google.auth.GoogleAuth({
    scopes: ["https://www.googleapis.com/auth/drive"],
  }),
});

const app = express();

app.post("/webhooks/signatureapi", express.raw({ type: "application/json" }), async (req, res) => {
  let event;
  try {
    event = new Webhook(process.env.SIGNATUREAPI_WEBHOOK_SECRET).verify(
      req.body.toString("utf8"),
      req.headers,
    );
  } catch {
    return res.sendStatus(400);
  }
  if (event.type !== "deliverable.generated") return res.sendStatus(200);

  const { object_id: deliverableId, envelope_id: envelopeId } = event.data;
  const name = `${envelopeId}_${deliverableId}.pdf`;
  const folderId = process.env.DRIVE_FOLDER_ID;

  // A retried event must not create a second copy.
  const existing = await drive.files.list({
    q: `name = '${name}' and '${folderId}' in parents and trashed = false`,
    fields: "files(id)",
    supportsAllDrives: true,
    includeItemsFromAllDrives: true,
  });
  if (existing.data.files.length > 0) return res.sendStatus(200);

  // The link in the event expires after 1 hour, so fetch a fresh one.
  const api = await fetch(`https://api.signatureapi.com/v1/deliverables/${deliverableId}`, {
    headers: { "X-API-Key": process.env.SIGNATUREAPI_KEY },
  });
  const { url } = await api.json();
  const pdf = await fetch(url);

  await drive.files.create({
    requestBody: { name, parents: [folderId] },
    media: { mimeType: "application/pdf", body: Readable.fromWeb(pdf.body) },
    fields: "id",
    supportsAllDrives: true,
  });
  res.sendStatus(200);
});

app.listen(3000);
Python
# pip install flask standardwebhooks requests google-api-python-client google-auth
import io
import os

import google.auth
import requests
from flask import Flask, request
from googleapiclient.discovery import build
from googleapiclient.http import MediaIoBaseUpload
from standardwebhooks import Webhook

creds, _ = google.auth.default(scopes=["https://www.googleapis.com/auth/drive"])
drive = build("drive", "v3", credentials=creds)

app = Flask(__name__)


@app.post("/webhooks/signatureapi")
def handle():
    try:
        event = Webhook(os.environ["SIGNATUREAPI_WEBHOOK_SECRET"]).verify(
            request.get_data(), dict(request.headers)
        )
    except Exception:
        return "", 400
    if event["type"] != "deliverable.generated":
        return "", 200

    deliverable_id = event["data"]["object_id"]
    name = f'{event["data"]["envelope_id"]}_{deliverable_id}.pdf'
    folder_id = os.environ["DRIVE_FOLDER_ID"]

    # A retried event must not create a second copy.
    existing = drive.files().list(
        q=f"name = '{name}' and '{folder_id}' in parents and trashed = false",
        fields="files(id)",
        supportsAllDrives=True,
        includeItemsFromAllDrives=True,
    ).execute()
    if existing["files"]:
        return "", 200

    # The link in the event expires after 1 hour, so fetch a fresh one.
    api = requests.get(
        f"https://api.signatureapi.com/v1/deliverables/{deliverable_id}",
        headers={"X-API-Key": os.environ["SIGNATUREAPI_KEY"]},
    )
    pdf = requests.get(api.json()["url"])

    media = MediaIoBaseUpload(io.BytesIO(pdf.content), mimetype="application/pdf", resumable=True)
    drive.files().create(
        body={"name": name, "parents": [folder_id]},
        media_body=media,
        fields="id",
        supportsAllDrives=True,
    ).execute()
    return "", 200
  • Verify the signature over the raw body, as in verify the signature. A failed upload should return a non-2XX status so SignatureAPI retries, for up to 48 hours.
  • The same event can arrive more than once. The handler checks for the file name in the folder first. The name combines the envelope id and the deliverable id, because an envelope can have several deliverables.
  • The sample downloads the file into memory and uploads inline for brevity. For large volumes, acknowledge the event and move the upload to a job.
  • The sample uses the drive scope, as Google’s own folder upload sample does. Google describes drive.file as access to files your app creates or opens. Its docs do not say whether that covers a folder shared with a service account, so test it before narrowing the scope.
  • Set supportsAllDrives (and includeItemsFromAllDrives on list calls) when the folder lives in a shared drive. Google requires both flags on a search in a shared drive folder.
  • Google recommends resumable uploads for files over 5 MB, which is why the Python sample sets resumable=True.