将docusign嵌入会话签名到我的应用程序

时间:2016-01-18 11:52:47

标签: java xml docusignapi

我是Docusign的新人。     我想要一个功能,以便任何用户使用我的应用程序,将从我的应用程序中获取一个文档进行签名。签名后,签名文档应返回我的申请表。我不想为此使用任何模板,我想发送自己的文件进行签名。     我使用以下代码。但是当我使用预定义模板时,它会返回URL,通过该URL我可以将我的客户带到docusign页面进行签名,当我想发送ant pdf文档代替模板时,它显示错误。     请帮忙。

Code:

import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class embeddedSigning
{   
    public static void main(String[] args) throws Exception
    {
        String integratorKey = "My Integrator Key";     // integrator key (found on Preferences -> API page)    
        String username = "My User Name";            // account email (or your API userId)
        String password = "My Password";             // account password
        String recipientName = "Signer's Name";          // recipient (signer) name
        String recipientEmail = "Signer's Email";        // recipient (signer) email    
        String templateId = "My Template Id";            // template ID copied from a template in your DocuSign account
        String roleName = "Signer's Name";           // name of the template role for above account template                
        //------------------------------------------------------------------------------------

        // construct the DocuSign authentication header
        String authenticationHeader = 
                    "<DocuSignCredentials>" + 
                        "<Username>" + username + "</Username>" +
                        "<Password>" + password + "</Password>" + 
                        "<IntegratorKey>" + integratorKey + "</IntegratorKey>" + 
                    "</DocuSignCredentials>";

        // additional variable declarations
        String baseURL = "";            // we will retrieve this through the Login API call
        String accountId = "";          // we will retrieve this through the Login API call
        HttpURLConnection conn = null;  // connection object used for each request
        String url = "";                // end-point for each api call
        String body = "";           // request body
        String response = "";           // response body
        int status;             // response status

        //============================================================================
        // STEP 1 - Make the Login API call to retrieve your baseUrl and accountId
        //============================================================================

        url = "https://demo.docusign.net/restapi/v2/login_information";
        body = "";  // no request body for the login call

        // create connection object, set request method, add request headers
        conn = InitializeRequest(url, "GET", body, authenticationHeader);

        // send the request
        System.out.println("Step 1:  Sending Login request...\n");
        status = conn.getResponseCode();
        if( status != 200 ) // 200 = OK
        {
            errorParse(conn, status);
            return;
        }

        // obtain baseUrl and accountId values from response body 
        response = getResponseBody(conn);
        baseURL = parseXMLBody(response, "baseUrl");
        accountId = parseXMLBody(response, "accountId");
        System.out.println("-- Login response --\n\n" + prettyFormat(response, 2) + "\n");

        //============================================================================
        // STEP 2 - Signature Request from Template API Call
        //============================================================================

        url = baseURL + "/envelopes";   // append "/envelopes" to baseUrl for signature request call

        // this example uses XML formatted requests, JSON format is also accepted
        body = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
                "<accountId>" + accountId + "</accountId>" +
                "<status>sent</status>" +   
                "<emailSubject>DocuSign API Call - Signature request from template</emailSubject>" +
                "<templateId>" + templateId + "</templateId>" + 
                "<templateRoles>" + 
                "<templateRole>" + 
                "<email>" + username + "</email>" + 
                "<name>" + recipientName + "</name>" +              
                "<roleName>" + roleName + "</roleName>" + 
                "<clientUserId>1001</clientUserId>" +   // required for embedded sending (value is user-defined) 
                "</templateRole>" + 
                "</templateRoles>" + 
                "</envelopeDefinition>";

        // re-use connection object for second request...
        conn = InitializeRequest(url, "POST", body, authenticationHeader);

        System.out.println("Step 2:  Creating envelope from template...\n");
        status = conn.getResponseCode(); // triggers the request
        if( status != 201 ) // 201 = Created
        {
            errorParse(conn, status);
            return;
        }

        // obtain envelope uri from response body 
        response = getResponseBody(conn);
        String uri = parseXMLBody(response, "uri");
        System.out.println("-- Envelope Creation response --\n\n" + prettyFormat(response, 2));

        //============================================================================
        // STEP 3 - Get the Embedded Signing View
        //============================================================================

        url = baseURL + uri + "/views/recipient";   // append envelope uri + "views/recipient" to url 

        // this example uses XML formatted requests, JSON format is also accepted
        body = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">"  +
                "<authenticationMethod>email</authenticationMethod>" + 
                "<email>" + recipientEmail + "</email>" + 
                "<returnUrl>http://www.docusign.com/devcenter</returnUrl>" + 
                "<clientUserId>1001</clientUserId>" +   //*** must match clientUserId set in Step 2! 
                "<userName>" + recipientName + "</userName>" + 
                "</recipientViewRequest>";

        System.out.print("Step 3:  Generating URL token for embedded signing... ");
        conn = InitializeRequest(url, "POST", body, authenticationHeader);
        status = conn.getResponseCode(); // triggers the request
        if( status != 201 ) // 201 = Created
        {
            errorParse(conn, status);
            return;
        }
        System.out.println("done.");

        response = getResponseBody(conn);
        String urlToken = parseXMLBody(response, "url");
        System.out.println("\nEmbedded signing token created:\n\t" + urlToken);
    } //end main()

    //***********************************************************************************************
    //***********************************************************************************************
    // --- HELPER FUNCTIONS ---
    //***********************************************************************************************
    //***********************************************************************************************
    public static HttpURLConnection InitializeRequest(String url, String method, String body, String httpAuthHeader) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection)new URL(url).openConnection();

            conn.setRequestMethod(method);
            conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader);
            conn.setRequestProperty("Content-Type", "application/xml");
            conn.setRequestProperty("Accept", "application/xml");
            if (method.equalsIgnoreCase("POST"))
            {
                conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
                conn.setDoOutput(true);
                // write body of the POST request 
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
                dos.writeBytes(body); dos.flush(); dos.close();
            }
            return conn;

        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String parseXMLBody(String body, String searchToken) {
        String xPathExpression;
        try {
                // we use xPath to parse the XML formatted response body
            xPathExpression = String.format("//*[1]/*[local-name()='%s']", searchToken);
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (xPath.evaluate(xPathExpression, new InputSource(new StringReader(body))));
        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }   

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String getResponseBody(HttpURLConnection conn) {
        BufferedReader br = null;
        StringBuilder body = null;
        String line = "";
        try {
            // we use xPath to get the baseUrl and accountId from the XML response body
            br = new BufferedReader(new InputStreamReader( conn.getInputStream()));
            body = new StringBuilder();
            while ( (line = br.readLine()) != null)
                body.append(line);
            return body.toString();
        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static void errorParse(HttpURLConnection conn, int status) { 
        BufferedReader br;
        String line;
        StringBuilder responseError;
        try {
            System.out.print("API call failed, status returned was: " + status);
            InputStreamReader isr = new InputStreamReader( conn.getErrorStream() );
            br = new BufferedReader(isr);
            responseError = new StringBuilder();
            line = null;
            while ( (line = br.readLine()) != null)
                responseError.append(line);
            System.out.println("\nError description:  \n" + prettyFormat(responseError.toString(), 2));
            return;
        }
        catch (Exception e) {
            throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String prettyFormat(String input, int indent) { 
        try {
                Source xmlInput = new StreamSource(new StringReader(input));
                StringWriter stringWriter = new StringWriter();
                StreamResult xmlOutput = new StreamResult(stringWriter);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                transformerFactory.setAttribute("indent-number", indent);
                Transformer transformer = transformerFactory.newTransformer(); 
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.transform(xmlInput, xmlOutput);
                return xmlOutput.getWriter().toString();
            } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }
} // end class

1 个答案:

答案 0 :(得分:0)

I am trying other way to create and send a document for signing without using a template. But it is giving the following error 
"errorCode: UNKNOWN_ENVELOPE_RECIPIENT
 message: The recipient you have identified is not a valid recipient of the specified envelope."
Please refer to the code snippet below and please help me.

Code:

import java.io.*;
import java.net.URL;
import java.net.HttpURLConnection;

import javax.xml.transform.*;
import javax.xml.transform.stream.*;
import javax.xml.xpath.*;
import org.xml.sax.InputSource;

public class embeddedSigning
{   
    public static void main(String[] args) throws Exception
    {   
        //------------------------------------------------------------------------------------
        // ENTER VALUES FOR THE FOLLOWING 7 VARIABLES:
        //------------------------------------------------------------------------------------
        String integratorKey = "My Integrator Key";     // integrator key (found on Preferences -> API page)    
        String username = "My User Name";            // account email (or your API userId)
        String password = "My Password";             // account password
        String recipientName = "Signer's Name";          // recipient (signer) name
        String recipientEmail = "Signer's Email";        // recipient (signer) email
        String documentName = "samplepdf.pdf";          // copy file with same name into project directory!
        String docContentType = "application/pdf";  // content type for above document (defaults to pdf)        
        String base64Binary = "Base 64 encoding string of the above mentioned pdf file";

        String authenticationHeader = 
                    "<DocuSignCredentials>" + 
                        "<Username>" + username + "</Username>" +
                        "<Password>" + password + "</Password>" + 
                        "<IntegratorKey>" + integratorKey + "</IntegratorKey>" + 
                    "</DocuSignCredentials>";

        String baseURL = "";            // we will retrieve this through the Login API call
        String accountId = "";          // we will retrieve this through the Login API call
        HttpURLConnection conn = null;  // connection object used for each request
        String url = "";                // end-point for each api call
        String body = "";               // request body
        String response = "";           // response body
        int status;                     // response status

        url = "https://demo.docusign.net/restapi/v2/login_information";
        body = "";

        conn = InitializeRequest(url, "GET", body, authenticationHeader);

        System.out.println("Step 1:  Sending Login request...\n");
        status = conn.getResponseCode();
        if( status != 200 ) // 200 = OK
        {
            errorParse(conn, status);
            return;
        }

        // obtain baseUrl and accountId values from response body 
        response = getResponseBody(conn);
        baseURL = parseXMLBody(response, "baseUrl");
        accountId = parseXMLBody(response, "accountId");
        System.out.println("-- Login response --\n\n" + prettyFormat(response, 2) + "\n");

        //============================================================================
        // STEP 2 - Signature Request from Template API Call
        //============================================================================

        url = baseURL + "/envelopes";   // append "/envelopes" to baseUrl for signature request call

        // this example uses XML formatted requests, JSON format is also accepted
        body = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
                "<accountId>" + accountId + "</accountId>" +
                "<status>sent</status>" +   
                "<emailSubject>DocuSign API Call - Signature request from template</emailSubject>" +
                "<clientUserId>1001</clientUserId>" +

                "<documents>" +
                    "<document>" + 
                        "<documentId>456123789</documentId>" + 
                        "<name>" + documentName + "</name>" + 
                        "<documentBase64>" + base64Binary + "</documentBase64>" +
                    "</document>" + 
                "</documents>" +

                "<tabs>" +
                    "<signHereTabs>" + 
                        "<signHere>" + 
                            "<xPosition>100</xPosition>" + 
                            "<yPosition>100</yPosition>" + 
                            "<pageNumber>1</pageNumber>" + 
                        "</signHere>" +
                    "</signHereTabs>" + 
                "</tabs>" +

                "<recipients>" + 
                    "<signers>" + 
                        "<signer>" + 
                            "<recipientId>123456789</recipientId>" +    
                            "<name>" + recipientName + "</name>" +
                            "<email>" + recipientEmail + "</email>" +
                        "</signer>" + 
                    "</signers>" + 
                "</recipients>" +

                "</envelopeDefinition>";

        // re-use connection object for second request...
        conn = InitializeRequest(url, "POST", body, authenticationHeader);

        System.out.println("Step 2:  Creating envelope from template...\n");
        status = conn.getResponseCode(); // triggers the request

        System.out.println("status " + status);

        if( status != 201 ) // 201 = Created
        {
            errorParse(conn, status);
            return;
        }

        // obtain envelope uri from response body 
        response = getResponseBody(conn);
        String uri = parseXMLBody(response, "uri");
        System.out.println("-- Envelope Creation response --\n\n" + prettyFormat(response, 2));

        //============================================================================
        // STEP 3 - Get the Embedded Signing View
        //============================================================================

        url = baseURL + uri + "/views/recipient";   // append envelope uri + "views/recipient" to url 

        // this example uses XML formatted requests, JSON format is also accepted
        body = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">"  +
                "<authenticationMethod>email</authenticationMethod>" + 
                "<email>" + recipientEmail + "</email>" + 
                "<returnUrl>http://www.docusign.com/devcenter</returnUrl>" + 
                "<clientUserId>1001</clientUserId>" +   //*** must match clientUserId set in Step 2! 
                "<userName>" + recipientName + "</userName>" + 
                "</recipientViewRequest>";

        System.out.print("Step 3:  Generating URL token for embedded signing... ");
        conn = InitializeRequest(url, "POST", body, authenticationHeader);
        status = conn.getResponseCode(); // triggers the request
        if( status != 201 ) // 201 = Created
        {
            errorParse(conn, status);
            return;
        }
        System.out.println("done.");

        response = getResponseBody(conn);
        String urlToken = parseXMLBody(response, "url");
        System.out.println("\nEmbedded signing token created:\n\t" + urlToken);
    } //end main()

    //***********************************************************************************************
    //***********************************************************************************************
    // --- HELPER FUNCTIONS ---
    //***********************************************************************************************
    //***********************************************************************************************
    public static HttpURLConnection InitializeRequest(String url, String method, String body, String httpAuthHeader) {
        HttpURLConnection conn = null;
        try {
            conn = (HttpURLConnection)new URL(url).openConnection();

            conn.setRequestMethod(method);
            conn.setRequestProperty("X-DocuSign-Authentication", httpAuthHeader);
            conn.setRequestProperty("Content-Type", "application/xml");
            conn.setRequestProperty("Accept", "application/xml");
            if (method.equalsIgnoreCase("POST"))
            {
                conn.setRequestProperty("Content-Length", Integer.toString(body.length()));
                conn.setDoOutput(true);
                // write body of the POST request 
                DataOutputStream dos = new DataOutputStream( conn.getOutputStream() );
                dos.writeBytes(body); dos.flush(); dos.close();
            }
            return conn;

        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String parseXMLBody(String body, String searchToken) {
        String xPathExpression;
        try {
                // we use xPath to parse the XML formatted response body
            xPathExpression = String.format("//*[1]/*[local-name()='%s']", searchToken);
            XPath xPath = XPathFactory.newInstance().newXPath();
            return (xPath.evaluate(xPathExpression, new InputSource(new StringReader(body))));
        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }   

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String getResponseBody(HttpURLConnection conn) {
        BufferedReader br = null;
        StringBuilder body = null;
        String line = "";
        try {
            // we use xPath to get the baseUrl and accountId from the XML response body
            br = new BufferedReader(new InputStreamReader( conn.getInputStream()));
            body = new StringBuilder();
            while ( (line = br.readLine()) != null)
                body.append(line);
            return body.toString();
        } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static void errorParse(HttpURLConnection conn, int status) { 
        BufferedReader br;
        String line;
        StringBuilder responseError;
        try {
            System.out.print("API call failed, status returned was: " + status);
            InputStreamReader isr = new InputStreamReader( conn.getErrorStream() );
            br = new BufferedReader(isr);
            responseError = new StringBuilder();
            line = null;
            while ( (line = br.readLine()) != null)
                responseError.append(line);
            System.out.println("\nError description:  \n" + prettyFormat(responseError.toString(), 2));
            return;
        }
        catch (Exception e) {
            throw new RuntimeException(e); // simple exception handling, please review it
        }
    }

    ///////////////////////////////////////////////////////////////////////////////////////////////
    public static String prettyFormat(String input, int indent) { 
        try {
                Source xmlInput = new StreamSource(new StringReader(input));
                StringWriter stringWriter = new StringWriter();
                StreamResult xmlOutput = new StreamResult(stringWriter);
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                transformerFactory.setAttribute("indent-number", indent);
                Transformer transformer = transformerFactory.newTransformer(); 
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.transform(xmlInput, xmlOutput);
                return xmlOutput.getWriter().toString();
            } catch (Exception e) {
                throw new RuntimeException(e); // simple exception handling, please review it
        }
    }
} // end class