Tuesday, September 16, 2014

Docusign integration with Salesforce

VF Page :

<apex:page standardController="Apttus_Proposal__Proposal__c" extensions="DocusignTestPageController" action="{!Send}">
<apex:pageMessages ></apex:pageMessages>
<apex:form >
<apex:iframe src="{!envelopeId}" scrolling="true"/>
</apex:form>
</apex:page>


Controller

public with sharing class DocusignTestPageController {
    public string quotename {get;set;}
    public Apttus_Proposal__Proposal__c quote {get;set;}
    public String envelopeId {get;set;}
    private String accountId = ' '; // Docusign account id
    private String userId = ' '; //Docusign user id
    private String password = ' '; // docusign password;
    private String integratorsKey = ''; docusign key
    private String webServiceUrl = 'https://demo.docusign.net/api/3.0/dsapi.asmx';
    
    public DocusignTestPageController(ApexPages.StandardController controller) {
        quote=(Apttus_Proposal__Proposal__c)controller.getrecord();
        quote=[Select Id,Name from Apttus_Proposal__Proposal__c where Id=:quote.Id];
        quotename=quote.Id;
    }
    
    public pagereference send()
    {
        DocusignWSDL.DSAPIServiceSoap dsApiSend = new DocusignWSDL.DSAPIServiceSoap();
        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);
 
        DocusignWSDL.Envelope envelope = new DocusignWSDL.Envelope();
        envelope.Subject    = 'Please Sign this Quote ';
        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  = '4c65053a-b5b7-4a37-ba89-073f7275b556'; 
        

        // Render the contract
        System.debug('Rendering the contract');
        PageReference pageRef = new PageReference('/apex/Template');
        pageRef.getParameters().put('id',quotename);
        Blob pdfBlob = pageRef.getContent();  
        
        // Document
        DocusignWSDL.Document document = new DocusignWSDL.Document();
        document.ID = 1;
        document.pdfBytes = EncodingUtil.base64Encode(pdfBlob);
        document.Name = 'Contract';
        document.FileExtension = 'pdf';
        envelope.Documents = new DocusignWSDL.ArrayOfDocument();
        envelope.Documents.Document = new DocusignWSDL.Document[1];
        envelope.Documents.Document[0] = document;
        
        // Recipient
        System.debug('Building up the recipient');
        DocusignWSDL.Recipient recipient1 = new DocusignWSDL.Recipient();
        recipient1.ID = 1;
        recipient1.Type_x = 'Signer';
        recipient1.RoutingOrder = 1;
        recipient1.Email = ''; // recipient1 email id
        recipient1.UserName = 'SP Sign';
        DocusignWSDL.RecipientCaptiveInfo captiveinfo=new DocusignWSDL.RecipientCaptiveInfo();
        captiveinfo.ClientUserId='2482343';
        recipient1.CaptiveInfo=captiveinfo;
        // This setting seems required or you see the error:
        // "The string '' is not a valid Boolean value. at System.Xml.XmlConvert.ToBoolean(String s)" 
        recipient1.RequireIDLookup = false;      
        
        
        /*DocusignWSDL.Recipient recipient2 = new DocusignWSDL.Recipient();
        recipient2.ID = 1;
        recipient2.Type_x = 'Signer';
        recipient2.RoutingOrder = 2;
        recipient2.Email = ''; recipient2 email id
        recipient2.UserName = 'EBM Counter Sign';
            
        // This setting seems required or you see the error:
        // "The string '' is not a valid Boolean value. at System.Xml.XmlConvert.ToBoolean(String s)" 
        recipient2.RequireIDLookup = false;      
        */
        envelope.Recipients = new DocusignWSDL.ArrayOfRecipient();
        envelope.Recipients.Recipient = new DocusignWSDL.Recipient[1];
        envelope.Recipients.Recipient[0] = recipient1;
        //envelope.Recipients.Recipient[1] = recipient2;
        
        // Tab
        DocusignWSDL.Tab tab1 = new DocusignWSDL.Tab();
        tab1.Type_x = 'SignHere';
        tab1.RecipientID = 1;
        tab1.DocumentID = 1;
        tab1.AnchorTabItem = new DocusignWSDL.AnchorTab();
        tab1.AnchorTabItem.AnchorTabString = 'By:';
        tab1.AnchorTabItem.XOffset = 100;

        
        DocusignWSDL.Tab tab2 = new DocusignWSDL.Tab();
        tab2.Type_x = 'DateSigned';
        tab2.RecipientID = 1;
        tab2.DocumentID = 1;
        tab2.AnchorTabItem = new DocusignWSDL.AnchorTab();
        tab2.AnchorTabItem.AnchorTabString = 'Date Signed:';
        
       /* envelope.Tabs = new DocusignWSDL.ArrayOfTab();
        envelope.Tabs.Tab = new DocusignWSDL.Tab[1];
        envelope.Tabs.Tab[0] = tab1;        
        envelope.Tabs.Tab[0] = tab2;        
        */
        
        System.debug('Calling the API');
        try {
            DocusignWSDL.EnvelopeStatus es = dsApiSend.CreateAndSendEnvelope(envelope);
            DocusignWSDL.ArrayOfRecipientStatus arrayofrecieps=new DocusignWSDL.ArrayOfRecipientStatus();
            arrayofrecieps=es.RecipientStatuses;
            List<DocusignWSDL.RecipientStatus> reciepstatus=new List<DocusignWSDL.RecipientStatus>();
            reciepstatus=arrayofrecieps.RecipientStatus;
            
            
            DocusignWSDL.RequestRecipientTokenAuthenticationAssertion assertion = new DocusignWSDL.RequestRecipientTokenAuthenticationAssertion();
            assertion.AssertionID = '1983';
            assertion.AuthenticationInstant = DateTime.Now();
            assertion.AuthenticationMethod = 'Password';
            assertion.SecurityDomain = 'Request Recipient Token Test';
            // Construct the URLs based on username
            DocusignWSDL.ArrayOfRecipient recipient = envelope.Recipients;
            DocusignWSDL.RequestRecipientTokenClientURLs urls = new DocusignWSDL.RequestRecipientTokenClientURLs();
            String urlBase = 'https://demo.docusign.net/';
            urls.OnSigningComplete = urlBase + '?event=SignComplete&uname=' + reciepstatus[0].UserName;
            urls.OnViewingComplete = urlBase + '?event=ViewComplete&uname=' + reciepstatus[0].UserName;
            urls.OnCancel = urlBase + '?event=Cancel&uname=' + reciepstatus[0].UserName;
            urls.OnDecline = urlBase + '?event=Decline&uname=' + reciepstatus[0].UserName;
            urls.OnSessionTimeout = urlBase + '?event=Timeout&uname=' + reciepstatus[0].UserName;
            urls.OnTTLExpired = urlBase + '?event=TTLExpired&uname=' + reciepstatus[0].UserName;
            urls.OnIdCheckFailed = urlBase + '?event=IDCheck&uname=' + reciepstatus[0].UserName;
            urls.OnAccessCodeFailed = urlBase + '?event=AccessCode&uname=' + reciepstatus[0].UserName;
            urls.OnException = urlBase + '?event=Exception&uname=' + reciepstatus[0].UserName;
            string URL=dsApiSend.RequestRecipientToken(es.envelopeId,reciepstatus[0].ClientUserId,reciepstatus[0].UserName,reciepstatus[0].Email,assertion,urls);
            envelopeId = URL;
            System.debug('Returned successfully, envelope id = ' + envelopeId );
            return null;
            //return (new pagereference('https://demo.docusign.net/Member/EmailStart.aspx?m='+envelopeId));
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            envelopeId = 'Exception - ' + e;
            ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.ERROR,e.getMessage());
            ApexPages.addMessage(myMsg);
            return null;
        }
        
    }
}