Demo

Here is sample code to illustrate pydocusign usage.

To run the demo code, you need a development environment. See Contributing.

Note

The demo can use the same environment variables as tests. See Contributing. If you do not set environment variables, you will be prompted for some configuration.

Embedded signing

#!/usr/bin/env python
# coding=utf-8
"""Sample script that demonstrates `pydocusign` usage for embedded signing.

See also http://iodocs.docusign.com/APIWalkthrough/embeddedSigning

"""
from __future__ import print_function
import hashlib
import os
import uuid

import pydocusign
from pydocusign.test import fixtures_dir

try:
    raw_input
except NameError:
    raw_input = input


def prompt(environ_key, description, default):
    try:
        return os.environ[environ_key]
    except KeyError:
        value = raw_input('{description} (default: "{default}"): '.format(
            default=default, description=description))
        if not value:
            return default
        else:
            return value


# Get configuration from environment or prompt the user...
root_url = prompt(
    'DOCUSIGN_ROOT_URL',
    'DocuSign API URL',
    'https://demo.docusign.net/restapi/v2')
username = prompt(
    'DOCUSIGN_USERNAME',
    'DocuSign API username',
    '')
password = prompt(
    'DOCUSIGN_PASSWORD',
    'DocuSign API password',
    '')
integrator_key = prompt(
    'DOCUSIGN_INTEGRATOR_KEY',
    'DocuSign API integrator key',
    '')
signer_return_url = prompt(
    'DOCUSIGN_TEST_SIGNER_RETURN_URL',
    'Signer return URL',
    '')


# Create a client.
client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=username,
    password=password,
    integrator_key=integrator_key,
)


# Login. Updates API URLs in client.
print("1. GET /login_information")
login_information = client.login_information()
print("   Received data: {data}".format(data=login_information))


# Prepare list of signers. Ordering matters.
signers = [
    pydocusign.Signer(
        email='jean.francais@example.com',
        name=u'Jean Français',
        recipientId=1,
        clientUserId=str(uuid.uuid4()),  # Something unique in your database.
        tabs=[
            pydocusign.SignHereTab(
                documentId=1,
                pageNumber=1,
                xPosition=100,
                yPosition=100,
            ),
        ],
        emailSubject='Voici un sujet',
        emailBody='Voici un message',
        supportedLanguage='fr',
    ),
    pydocusign.Signer(
        email='paul.english@example.com',
        name=u'Paul English',
        recipientId=2,
        clientUserId=str(uuid.uuid4()),  # Something unique in your database.
        tabs=[],  # No tabs means user places tabs himself in DocuSign UI.
        emailSubject='Here is a subject',
        emailBody='Here is a message',
        supportedLanguage='en',
    ),
]


# Create envelope with embedded signing.
print("2. POST {account}/envelopes")
document_path = os.path.join(fixtures_dir(), 'test.pdf')
document_2_path = os.path.join(fixtures_dir(), 'test2.pdf')
with open(document_path, 'rb') as pdf, open(document_2_path, 'rb') as pdf_2:
    envelope = pydocusign.Envelope(
        documents=[
            pydocusign.Document(
                name='document.pdf',
                documentId=1,
                data=pdf,
            ),
            pydocusign.Document(
                name='document_2.pdf',
                documentId=2,
                data=pdf_2,
            ),
        ],
        emailSubject='This is the subject',
        emailBlurb='This is the body',
        status=pydocusign.Envelope.STATUS_SENT,
        recipients=signers,
    )
    client.create_envelope_from_documents(envelope)
print("   Received envelopeId {id}".format(id=envelope.envelopeId))


# Update recipient list of envelope: fetch envelope's ``UserId`` from DocuSign.
print("3. GET {account}/envelopes/{envelopeId}/recipients")
envelope.get_recipients()
print("   Received UserId for recipient 0: {0}".format(
    envelope.recipients[0].userId))
print("   Received UserId for recipient 1: {0}".format(
    envelope.recipients[1].userId))


# Retrieve embedded signing for first recipient.
print("4. Get DocuSign Recipient View")
signing_url = envelope.post_recipient_view(
    envelope.recipients[0],
    returnUrl=signer_return_url)
print("   Received signing URL for recipient 0: {0}".format(signing_url))
signing_url = envelope.post_recipient_view(
    envelope.recipients[1],
    returnUrl=signer_return_url)
print("   Received signing URL for recipient 1: {0}".format(signing_url))


# Download signature documents.
print("5. List signature documents.")
document_list = envelope.get_document_list()
print("   Received document list: {0}".format(document_list))
print("6. Download documents from DocuSign.")
for signed_document in document_list:
    document = envelope.get_document(signed_document['documentId'])
    document_sha = hashlib.sha1(document.read()).hexdigest()
    print("   Document SHA1: {0}".format(document_sha))
print("7. Download signature certificate from DocuSign.")
document = envelope.get_certificate()
document_sha = hashlib.sha1(document.read()).hexdigest()
print("   Certificate SHA1: {0}".format(document_sha))

You can run this code with:

python demo/embeddedsigning.py

Creating envelope using template

#!/usr/bin/env python
# coding=utf-8
"""Sample script that demonstrates `pydocusign` usage for template signing.

See also http://iodocs.docusign.com/APIWalkthrough/requestSignatureFromTemplate

"""
from __future__ import print_function
import hashlib
import os
import uuid

import pydocusign

try:
    raw_input
except NameError:
    raw_input = input


def prompt(environ_key, description, default):
    try:
        return os.environ[environ_key]
    except KeyError:
        value = raw_input('{description} (default: "{default}"): '.format(
            default=default, description=description))
        if not value:
            return default
        else:
            return value


# Get configuration from environment or prompt the user...
root_url = prompt(
    'DOCUSIGN_ROOT_URL',
    'DocuSign API URL',
    'https://demo.docusign.net/restapi/v2')
username = prompt(
    'DOCUSIGN_USERNAME',
    'DocuSign API username',
    '')
password = prompt(
    'DOCUSIGN_PASSWORD',
    'DocuSign API password',
    '')
integrator_key = prompt(
    'DOCUSIGN_INTEGRATOR_KEY',
    'DocuSign API integrator key',
    '')
template_id = prompt(
    'DOCUSIGN_TEST_TEMPLATE_ID',
    'DocuSign Template ID',
    '')
signer_return_url = prompt(
    'DOCUSIGN_TEST_SIGNER_RETURN_URL',
    'Signer return URL',
    '')


# Create a client.
client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=username,
    password=password,
    integrator_key=integrator_key,
)


# Login. Updates API URLs in client.
print("1. GET /login_information")
login_information = client.login_information()
print("   Received data: {data}".format(data=login_information))


# Get the template definition
print("2. GET {account}/templates/{templateId}")
template_definition = client.get_template(template_id)
assert template_definition['recipients']['signers'][0][
    'roleName'] == 'employee'
assert template_definition['recipients']['signers'][0][
    'routingOrder'] == '1'
assert template_definition['recipients']['signers'][1][
    'roleName'] == 'employer'
assert template_definition['recipients']['signers'][1][
    'routingOrder'] == '1'  # Same routingOrder, important for testing


# Prepare list of roles. Ordering matters
roles = [
    pydocusign.Role(
        email='jean.francais@example.com',
        name=u'Jean Français',
        roleName='employer',
        clientUserId=str(uuid.uuid4()),  # Something unique in your database.
    ),
    pydocusign.Role(
        email='paul.english@example.com',
        name=u'Paul English',
        roleName='employee',
        clientUserId=str(uuid.uuid4()),  # Something unique in your database.
    ),
]


# Create envelope with embedded signing.
print("3. POST {account}/envelopes")
envelope = pydocusign.Envelope(
    emailSubject='This is the subject',
    emailBlurb='This is the body',
    status=pydocusign.Envelope.STATUS_SENT,
    templateId=template_id,
    templateRoles=roles,
)
client.create_envelope_from_template(envelope)
print("   Received envelopeId {id}".format(id=envelope.envelopeId))


# Update recipient list of envelope: fetch envelope's ``UserId`` from DocuSign.
print("4. GET {account}/envelopes/{envelopeId}/recipients")
envelope.get_recipients()
print("   Received UserId for recipient 0: {0}".format(
    envelope.recipients[0].userId))
print("   Received UserId for recipient 1: {0}".format(
    envelope.recipients[1].userId))


# Retrieve template signing for first recipient.
print("5. Get DocuSign Recipient View")
signing_url = envelope.post_recipient_view(
    envelope.recipients[0],
    returnUrl=signer_return_url)
print("   Received signing URL for recipient 0: {0}".format(signing_url))
signing_url = envelope.post_recipient_view(
    envelope.recipients[1],
    returnUrl=signer_return_url)
print("   Received signing URL for recipient 1: {0}".format(signing_url))


# Download signature documents.
print("6. List signature documents.")
document_list = envelope.get_document_list()
print("   Received document list: {0}".format(document_list))
print("7. Download document from DocuSign.")
document = envelope.get_document(document_list[0]['documentId'])
document_sha = hashlib.sha1(document.read()).hexdigest()
print("   Document SHA1: {0}".format(document_sha))
print("8. Download signature certificate from DocuSign.")
document = envelope.get_certificate()
document_sha = hashlib.sha1(document.read()).hexdigest()
print("   Certificate SHA1: {0}".format(document_sha))

You can run this code with:

python demo/templates.py

Managing accounts

#!/usr/bin/env python
# coding=utf-8
"""Sample script that demonstrates `pydocusign` usage for managing accounts.

See also http://iodocs.docusign.com/#tabEndpoint6

"""
import os

import pydocusign

try:
    raw_input
except NameError:
    raw_input = input


def prompt(environ_key, description, default):
    try:
        return os.environ[environ_key]
    except KeyError:
        value = raw_input('{description} (default: "{default}"): '.format(
            default=default, description=description))
        if not value:
            return default
        else:
            return value


# Get configuration from environment or prompt the user...
root_url = prompt(
    'DOCUSIGN_ROOT_URL',
    'DocuSign API URL',
    'https://demo.docusign.net/restapi/v2')
username = prompt(
    'DOCUSIGN_USERNAME',
    'DocuSign API username',
    '')
password = prompt(
    'DOCUSIGN_PASSWORD',
    'DocuSign API password',
    '')
integrator_key = prompt(
    'DOCUSIGN_INTEGRATOR_KEY',
    'DocuSign API integrator key',
    '')
distributor_code = prompt(
    'DOCUSIGN_TEST_DISTRIBUTOR_CODE',
    'DocuSign API distributor code',
    '')
distributor_password = prompt(
    'DOCUSIGN_TEST_DISTRIBUTOR_PASSWORD',
    'DocuSign API distributor password',
    '')
signer_return_url = prompt(
    'DOCUSIGN_TEST_SIGNER_RETURN_URL',
    'Signer return URL',
    '')
account_email = prompt(
    'DOCUSIGN_TEST_ACCOUNT_EMAIL',
    'Subsidiary account email',
    '')
account_password = prompt(
    'DOCUSIGN_TEST_ACCOUNT_PASSWORD',
    'Subsidiary account password',
    '')
plan_id = prompt(
    'DOCUSIGN_TEST_PLAN_ID',
    'DocuSign Plan ID',
    '')


# Create a client.
client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=username,
    password=password,
    integrator_key=integrator_key,
)


# Login. Updates API URLs in client.
print("1. GET /login_information")
login_information = client.login_information()
print("   Received data: {data}".format(data=login_information))


# Get main account information.
print("2. GET /accounts/{accountId}".format(accountId=client.account_id))
account_information = client.get_account_information(client.account_id)
print("   Received data: {data}".format(data=account_information))


# Create a subsidiary account.
print("3. POST /accounts")
account_input = {
    "accountName": "Pydocusign Test Account",
    "accountSettings": [],
    "addressInformation": {
        "address1": "Somewhere",
        "address2": "",
        "city": "Paris",
        "country": "France",
        "fax": "",
        "phone": "",
        "postalCode": "75010",
        "state": "",
    },
    "creditCardInformation": None,
    "distributorCode": distributor_code,
    "distributorPassword": distributor_password,
    "initialUser": {
        "email": account_email,
        "firstName": "John",
        "lastName": "Doe",
        "middleName": "Jean",
        "password": account_password,
        "suffixName": "",
        "title": "M",
        "userName": account_email,
        "userSettings": [],
    },
    "planInformation": {
        "planId": plan_id,
    },
    "referralInformation": None,
    "socialAccountInformation": None,
}
account_data = client.post_account(account_input)
print("   Received data: {data}".format(data=account_data))

raw_input("Please activate account {} and type RET".format(account_email))

# Get subsidiary account information.
print("4. GET /accounts/{accountId}".format(
    accountId=account_data['accountId']))
account_information = client.get_account_information(client.account_id)
print("   Received data: {data}".format(data=account_information))


# In order to delete subsidiary account, we have to log in with this account.
subsidiary_client = pydocusign.DocuSignClient(
    root_url=root_url,
    username=account_data['userId'],
    password=account_password,
    integrator_key=integrator_key,  # Use the same key as main account!
)

# Login. Updates API URLs in client.
print("5. LOGIN WITH SUBSIDIARY ACCOUNT")
account_login_information = subsidiary_client.login_information()
print("   Received data: {data}".format(data=account_login_information))


# Delete subsidiary account.
print("6. DELETE /accounts/{accountId}".format(
    accountId=subsidiary_client.account_id))
deleted = subsidiary_client.delete_account(subsidiary_client.account_id)
print("   Received data: {data}".format(data=deleted))

You can run this code with:

python demo/accounts.py