Docusign - Salesforce Integration


What is Docusign?


DocuSign is a San Francisco- and Seattle-based company that provides electronic signature technology and Digital Transaction Management services for facilitating electronic exchanges of contracts and signed documents




Yes! Let's integrate our Salesforce with Docusign. Before jumping straight into what we are going to achieve today, take a pause and be comfortable with docusign.

Example : A contract company in Australia wants to send contracts to one of their contact named Tim, but sending them is not the problem.
First, they take printout of the documents/pdf, post it to the address of the contact/ mail him the pdf.
Once Tim receives this contract, he agrees to sign the document and scans/posts it back to the Australian company.

Lot of time is wasted in this approach.

The Australian company approaches Radical Team to come up with a solution to save their companies time. Radical team solves this issue by integrating Docusign with Salesforce by simply following the below steps.

Question No 1 : How did they do it ?

We just need to access docusign api to send contracts for e-signatures.



Now let's help the Australian company ! Login into salesforce developer org and start adding docusign web services to your authorized end points of salesforce.com

Setup > Security > Remote site settings  and add https://demo.docusign.net as shown below



Sites - To publicly expose any information stored in our organization for other people to access.Sites are used in our purpose to render pages to the contact person who would be signing the page that we have created in our organization. Cool rite !!!

Setup > Develop > Sites 

First register your domain, this means we are going to create a url basically which would be a unique one. Check your domain for availability and go ahead in accepting the terms and click on register. Have a look in the below image for reference.


After registering the domain, click on new to create our site. Provide the necessary information as we have provided in our the below image -



On clicking on save we are ready with our site. Please do not forget to click on "ACTIVATE" to activate your site. Now lets go ahead in creating some pages. Basically two of them.

Page 1. Rendering our contract objects data 
Page 2. Making a web service call to docusign

Page 1. (Name your page as "RenderContract")

<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>    
    <div style='clear:right;margin-top:50px'>
    <div style='float:right'>____________________________________</div>
    <div style='float:right'>Date Signed:</div>
    </div>  
</apex:page>

We need to add this page to our newly created site profile. By clicking on site label link we can provide public access settings to our page.


Next click on public access settings to provide access to the visualforce page renderContract. (Adding a VF page would be same as we add in any normal profile)

Secondly provide access to Account and Contracts Objects on the same profile.



For testing our "renderContract" page, create a record in contract object as below and add a contact in the "customer signed by" field which has a genuine email id. In the later stages, this record details will be received by the contact as a pdf to provide an e-signature.



Keep the contracts record id which would look something like 
800360000000Rll (15 digit) and append it to your site as shown below - https://integrationskylab-dev-ed--c.na30.visual.force.com/apex/ContractRender?id=800360000000Rll

The output of the above would render a pdf with the details of your created contract id.


Now we would be creating an apex class to access Docusign API. Click on this link https://demo.docusign.net/api/3.0/Schema/dsapi-send.wsdl to use the sending WSDL. Right click on the page and save it to your desktop as shown below.




Next go to Apex Classes on Salesforce and select "Generate from WSDL". Choose the WSDL file and click on "Parse WSDL" and then save the class name as "DocuSignAPI"


There you go! We have generated an apex class named "DocuSignAPI" using the WSDL provided by Docusign for calling their API.

Using our new endpoint, we would be creating a new apex class for our Page 2(which calls docusign). 

Setup > Apex Classes > Click on "new"
Paste the below code 

public with sharing class SendToDocuSignController {
    private final Contract contract;
    
    public String envelopeId {get;set;}
    private String accountId = 'My Account ID';
    private String userId = 'UserID';
    private String password = 'Password';
    private String integratorsKey = 'IntegratorKey';
    private String webServiceUrl 
        = 'https://demo.docusign.net/api/3.0/dsapi.asmx';
    
    public SendToDocuSignController(ApexPages.StandardController controller)
    {
        this.contract = [select Id, CustomerSignedId, AccountId, ContractNumber 
        from Contract where id = :controller.getRecord().Id];
        envelopeId = 'Not sent yet';
        
        SendNow();
    }

    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>();
        dsApiSend.inputHttpHeaders_x.put('X-DocuSign-Authentication', 
            auth);
 
        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');
        pageRef.getParameters().put('id',contract.Id);
        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;
        }
      
    }
}

Login to your Docusign account, click on "Preferences" > Click on "API" at bottom and generate your integrator key.




Provide these values highlighted in the code. Now we are ready for our Page 2.

Page 2 : This page calls our newly created controller. Do not forget to add this page in the site's profile. Name this page as "CallDocusign"

<apex:page standardcontroller="Contract" extensions="SendToDocuSignController">
<h1>Your eSignature request is being sent to DocuSign API!</h1>
<hr/>
<apex:form >
<apex:commandButton value="Send Again!" action="{!SendNow}"/>
</apex:form>
<hr/>
<strong>The DocuSign EnvelopeId:</strong>{!envelopeId}<br/>
</apex:page>

Quickly lets create a custom button on contract object and add it to the contract layout. This is to send any newly created records to our contacts for their e-signatures.


We are done ! Yippee !!! Lets test our effort. 

Output :


On clicking of the send contract button, we see a pop window with below message that the document has been forwarded to Docusign.


An email is sent to the contact's email id for providing an e-signature

Draw your signature and its done.




Happy coding, eagerly waiting for your feedback.







 






Docusign - Salesforce Integration Docusign - Salesforce Integration Reviewed by dasfrogpractice on 01:40 Rating: 5

19 comments:

  1. Hi,

    This is cool. But is this API a paid service or free.

    ReplyDelete
    Replies
    1. Hi Amit Sahu, this is a free service, you can enjoy by creating a Docusign sandbox for yourself and see your e-signature popping up... please convey and share this message to your friends.... Happy coding!

      Delete
  2. This is great!

    Till date, we were shuttling them to-and-fro with signature and then then finally storing the scanned copies in the salesforce content.

    Truly helpful! Thanks salesforce radical team!!!

    ReplyDelete
  3. contd...

    Would you be available part-time on a variable effort basis? The requirement is only short-term as of now. We can discuss the rates.

    ReplyDelete
  4. Hi, If i need to send only documents attached to record instead rendering page as pdf? how can it be done

    ReplyDelete
    Replies
    1. Hello Vissu, give it a try.
      document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
      document.Name = 'Contract';
      document.FileExtension = 'pdf';
      in the above code, extension of the document is all that is required to change the file type. doc,pdf etc...

      Delete
  5. Hi Sai,

    Thanks for the reply. I already tried it and working as expected..

    Attachment att = [SELECT Id, Name, Body, ContentType FROM Attachment WHERE Parentid = :contract.Id LIMIT 1];
    System.debug('Rendering the contract' +att.Body);
    Blob pdfBlob = att.Body;

    // Document
    DocuSignAPI.Document document = new DocuSignAPI.Document();
    document.ID = 1;
    document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
    document.Name = 'Contract';
    document.FileExtension = 'docx';

    ReplyDelete
  6. Can you please help me to write back data into salesforce from Signed Document. ?

    ReplyDelete
  7. Hi do you have an example for REST api? I am looking to use Docusign REST api to createAndSendEnvelope.

    ReplyDelete
  8. how to attach the Docu sign envelop record to the contract object

    ReplyDelete
  9. Hi, do you know which licence is necessary to work in production?

    ReplyDelete
  10. How to implement docusign for custom objects instead of standard objects ?

    ReplyDelete
  11. Fabulous share. Loved reading your blog. Very informative and useful. Keep up with this work in future. salesforce contracts.

    ReplyDelete
  12. Good Post. I like your blog. Thanks for Sharing
    Salesforce Course in Gurgaon

    ReplyDelete
  13. Hi Sai Krishna,
    we implemented the same solution using your approach , it works great ,but we also need to store the signed document inside an object how this can be done , please explain.
    Thank You.

    ReplyDelete
  14. Great Blog! This post gives a better idea. Thanks for sharing useful information
    Salesforce Implementation Services

    ReplyDelete
  15. Great Article!

    Thank you for sharing this valuable blog about free e sign software. Everything has clearly described about electronic signature providers with appropriate images. It's really good for those who don't know how to make e signature in word.

    ReplyDelete
  16. Thank you for the valuable information

    Being a free electronic signature software provider, I usually recommend to all the modern generation for creating an online signature for their business, enterprises, real estate business and so on. Don't wait for any person. You can use this application on your devices. Search WeSignature on Google and try it free of cost. It is a best e signature software for small business, electronic signature real estate contracts, electronic signature for insurance and so on industries.
    Must Try this - A Free Electronic Signature Software WeSignature.

    ReplyDelete

Theme images by mariusFM77. Powered by Blogger.
Youtube Channel Image
Dasfrog Subscribe To watch more Salesforce Training
Subscribe