Recipes by Category

App Distribution (2) Bundle logic, interface and services for distribution. App Logic (37) The Apex programming language, workflow and formulas for logic. Collaboration (5) The Salesforce Chatter collaboration platform. Database (29) Data persistence, reporting and analytics. Integration (33) Web Service APIs and toolkits for integration. Security (9) Platform, application and data security. Tools (4) tooling User Interface (36) Visualforce MVC and metadata-drive user interfaces. Web Sites (12) Public web sites and apps with optional user registration and login.
Beta Feedback
Cookbook Home » Accessing DocuSign API from to send Contracts for eSignatures.

Accessing DocuSign API from to send Contracts for eSignatures.

Post by Mike Borozdin  (2010-09-29)

Status: Unverified
Level: intermediate


You want to access the DocuSign API in your / account in order to send an object with a single click of a button.


Before getting started you need to get a free developer account at and a free DocuSign developer account at [url]

1. Start out by adding DocuSign webservices to your authorized endpoints for your developer account. To do this, go to Setup > Security > Remote Sites and add

2. Next, set up a site so you can test rendering pages. There is plenty of documentation on how to get started with VisualForce, so we will leave it up to to explain the best options there. For the purpose of this walkthrough you just need to have a site for testing. You can get to the screen below by clicking Setup > Develop > Sites.

From there you can create a site label. Once the site is created all you need to do is make it active.

3. Now we need to create two pages; one for rendering a contract as a PDF and another that makes a web service call to DocuSign. We will start with the rendering page that we will call RenderContract (Note: the second page is set up in step 8). The code for the rendering page is fairly minimal. As you can see below, it just uses the standard Contract controller class and we are just rendering standard contract details with a couple of signature lines.

<apex:page renderAs="pdf" standardController="Contract">
    <apex:detail relatedList="true" title="true"/>
    <div style='clear:right;margin-top:50px'>
    <div style='float:right'>____________________________________</div>
    <div style='float:right'>By:</div>
    <div style='clear:right;margin-top:50px'>
    <div style='float:right'>____________________________________</div>
    <div style='float:right'>Date Signed:</div>

The page needs to be added to the site to ensure that you can access it for testing. You can accomplish that by going to the site detail and selecting Site VisualForce Pages.

The other setting that has to be adjusted for testing is adding Contracts as something that is accessible from this site. To accomplish this go to Public Access Settings and edit the standard object permission.

4. In order to test the first page and other code in our sample, we will create a test Contract. For simplicity we are going to put a contact in the Customer Signed By field.

At this point in time we have all the test data we need. You can note the Contract object ID in the URL And then use it to test the rendering page by plugging in the ID there:

At this point you should be getting a PDF file.

5. In this step we are going to create a class to access the DocuSign API. For this walkthrough we are just going to get the sending WSDL, which can be found at You should save the WSDL file to your desktop. (Note: For complete set of WSDL files please refer to documentation on DocuSign DevCenter.)

Next go to the Apex Classes and select “Generate from WSDL”. When the class generator asks you to supply a class name, we suggest that you overwrite the class name with DocuSignAPI.

6. Using the new API endpoint, you can create a controller for the second page. In order to do this you need to go to Apex Classes again and create a new class. The code for the controller class is shown below:

public with sharing class SendToDocuSignController {
    private final Contract contract;
    public String envelopeId {get;set;}
    private String accountId = '';
    private String userId = '';
    private String password = '';
    private String integratorsKey = '';
    private String webServiceUrl 
        = '';
    public SendToDocuSignController(ApexPages.StandardController controller)
        this.contract = [select Id, CustomerSignedId, AccountId, ContractNumber 
        from Contract where id = :controller.getRecord().Id];
        envelopeId = 'Not sent yet';

    public void SendNow()
        DocuSignAPI.APIServiceSoap dsApiSend 
            = new DocuSignAPI.APIServiceSoap();
        dsApiSend.endpoint_x = webServiceUrl;

        //Set Authentication
        String auth = '<DocuSignCredentials><Username>'+ userId 
            +'</Username><Password>' + password 
            + '</Password><IntegratorKey>' + integratorsKey 
            + '</IntegratorKey></DocuSignCredentials>';
        System.debug('Setting authentication to: ' + auth);
        dsApiSend.inputHttpHeaders_x = new Map<String, String>();
        DocuSignAPI.Envelope envelope = new DocuSignAPI.Envelope();
        envelope.Subject = 'Please Sign this Contract: ' 
            + contract.ContractNumber;
        envelope.EmailBlurb = 'This is my new eSignature service,'+ 
            ' it allows me to get your signoff without having to fax, ' +
            'scan, retype, refile and wait forever';
        envelope.AccountId  = accountId; 

        // Render the contract
        System.debug('Rendering the contract');
        PageReference pageRef = new PageReference('/apex/RenderContract');
        Blob pdfBlob = pageRef.getContent();     

        // Document
        DocuSignAPI.Document document = new DocuSignAPI.Document();
        document.ID = 1;
        document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
        document.Name = 'Contract';
        document.FileExtension = 'pdf';
        envelope.Documents = new DocuSignAPI.ArrayOfDocument();
        envelope.Documents.Document = new DocuSignAPI.Document[1];
        envelope.Documents.Document[0] = document;
        // Recipient
        System.debug('getting the contact');
        Contact contact = [SELECT email, FirstName, LastName 
            from Contact where id = :contract.CustomerSignedId];
        DocuSignAPI.Recipient recipient = new DocuSignAPI.Recipient();
        recipient.ID = 1;
        recipient.Type_x = 'Signer';
        recipient.RoutingOrder = 1;
        recipient.Email = contact.Email;
        recipient.UserName = contact.FirstName + ' ' + contact.LastName;
        // This setting seems required or you see the error:
        // "The string '' is not a valid Boolean value. 
        // at System.Xml.XmlConvert.ToBoolean(String s)" 
        recipient.RequireIDLookup = false;      
        envelope.Recipients = new DocuSignAPI.ArrayOfRecipient();
        envelope.Recipients.Recipient = new DocuSignAPI.Recipient[1];
        envelope.Recipients.Recipient[0] = recipient;
        // Tab
        DocuSignAPI.Tab tab1 = new DocuSignAPI.Tab();
        tab1.Type_x = 'SignHere';
        tab1.RecipientID = 1;
        tab1.DocumentID = 1;
        tab1.AnchorTabItem = new DocuSignAPI.AnchorTab();
        tab1.AnchorTabItem.AnchorTabString = 'By:';

        DocuSignAPI.Tab tab2 = new DocuSignAPI.Tab();
        tab2.Type_x = 'DateSigned';
        tab2.RecipientID = 1;
        tab2.DocumentID = 1;
        tab2.AnchorTabItem = new DocuSignAPI.AnchorTab();
        tab2.AnchorTabItem.AnchorTabString = 'Date Signed:';
        envelope.Tabs = new DocuSignAPI.ArrayOfTab();
        envelope.Tabs.Tab = new DocuSignAPI.Tab[2];
        envelope.Tabs.Tab[0] = tab1;        
        envelope.Tabs.Tab[1] = tab2;        
        System.debug('Calling the API');
        try {
            DocuSignAPI.EnvelopeStatus es 
            = dsApiSend.CreateAndSendEnvelope(envelope);
            envelopeId = es.EnvelopeID;
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            envelopeId = 'Exception - ' + e;

This might seem like a lot of code to understand, but the basics are pretty simple and you can see how a DocuSign envelope is constructed here:

7. In order to use DocuSign API, you need to retrieve your DocuSign API credentials. Go to, sign into your demo account, and then go to Preferences > API. There you will find these values:

  • Integrator's Key: ZORO-a81ec71a-cb17-4af0-b1aa-9513115cbf02
  • API UserName: 0e212ae6-1e12-40c1-8f5a-a57458ccaa63
  • API Password: <your current password>
  • API Account ID: 736e7948-6861-4ef3-ae71-4c56603dc14f

Plug these values into the controller class.

8. The next step is to create the second page, which actually calls SendToDocuSign. You will add this page to the site and hook it up to the custom controller we just developed:

<apex:page standardcontroller="Contract" extensions="SendToDocuSignController">

Your eSignature request is being sent to DocuSign API!

<hr/> <apex:form > <apex:commandButton value="Send Again!" action="{!SendNow}"/> </apex:form> <hr/> <strong>The DocuSign EnvelopeId:</strong>{!envelopeId}<br/> </apex:page>

Now you should be able to test sending of the contract by calling the page with the same ID you used for testing the rendering page:

9. The last step is creating a custom button on the contract object that calls the sending page. Go to Setup > Customize > Contracts > Buttons and Links and create a New button. In the properties, select Detail Page Button and then add the URL with the Contract Id:


Add the button to the page layout for the Contract object. This lets your users click on the button to get their Contracts electronically signed! They don’t need to learn any other systems or follow complicated steps. The logic behind the button does all the work.


Recipe Activity - Please Log in to write a comment


Where you ever able to solve your IO Exception: Read timed out error? I would appreciate any solutions you or the others on the thread have come up with.

Thank you.

by Frank Cabreja  (2012-11-28)

I followed your example, and am getting this error  ( An Error Occurred during anchor tag processing. Invalid document ).  Any idea why that might be happening?

by Jamie Ayer  (2012-03-07)


Great article.  I am particularly interested in implementing this task without a user's click (automatically sending contracts upon 'before insert' of an account).  Is there some way to access the DocuSign API from a trigger and use a precreated template/envelope to send?


by a093000000D8LOz  (2011-08-23)

I have error like: The DocuSign EnvelopeId:Exception - System.CalloutException: Web service callout failed: WebService returned a SOAP Fault: Unspecified_Error faultcode=soap:Server faultactor= Can you tell me 

by Julio Julio  (2011-08-21)

I would really need help in writing the test case for the above controller.

by Sayame  (2011-06-06)

@Sayame - you dont need to render it.  All you need to get is just PDF bytes.

by Mike Borozdin  (2011-06-05)

I already have a PDF document stored under Documents on my salesforce with the contract terms.Therefore i don't need to render any contract from the contract object.
How do i get to access my ready made contract under the Document object since i no longer need the RenderContract page?

by Sayame  (2011-05-25)

How can you get the signed contract pdf attached  back in salesforce Contract?

by Rishi Wadhwani  (2011-05-05)

 I have one requirement where i want to override the behaviour of Documentum Object and Content version object and want to store them on FTP instead of storing it on cloud  because of secret documents.

Can you tell me how to achieve this by overriding the behaviour of these classes?
If you have any sample code, please email me at

Thank you 
Kulveer SIngh

by Kulveer Singh  (2011-04-07)

Hi Nitish!

Sorry it took a while to respond.  I wish there was an e-mail notification when someone posted a question. 

Here is something you can try - can you pull up the second page directly?  You should be able to just pull it up with an ID of the SF objects.  If you have any problems - let me know.

by Mike Borozdin  (2011-01-20)

Hi Nitish!

Sorry it took a while to respond.  I wish there was an e-mail notification when someone posted a question. 

Here is something you can try - can you pull up the second page directly?  You should be able to just pull it up with an ID of the SF objects.  If you have any problems - let me know.

by Mike Borozdin  (2011-01-20)

Hi Mike,

I implemented this logic but getting error like "System.CalloutException: IO Exception: Read timed out", when I call my seconf vf page with my contract id.Please help me regarding the same.

by nitish dharm  (2010-12-08)


Vote to Verify a Recipe

Verifying a recipe is a way to give feedback to others and broaden your own understanding of the capabilities on When you verify a recipe, please make sure the code runs, and the functionality solves the articulated problem as expected.

Please make sure:
  • All the necessary pieces are mentioned
  • You have tested the recipe in practice
  • Have sent any suggestions for improvements to the author

Please Log in to verify a recipe

You have voted to verify this recipe.