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

Java 将docusign嵌入会话签名到我的应用程序,java,xml,docusignapi,Java,Xml,Docusignapi,我是新来的文档管理员。 我想要一个功能,以便使用我的应用程序的任何用户都可以获得一个从我的应用程序创建的文档,用于签名。签名后,已签名的文档应返回到我的应用程序。我不想为此使用任何模板,我想发送我自己的文档进行签名。 我正在使用以下代码。但是,当我使用预定义模板时,它会返回URL,通过URL,我可以将客户带到docusign页面进行签名,当我想发送ant pdf文档来代替模板时,它会显示错误。 请帮忙 Code: import java.io.*; import java.net.URL; i

我是新来的文档管理员。 我想要一个功能,以便使用我的应用程序的任何用户都可以获得一个从我的应用程序创建的文档,用于签名。签名后,已签名的文档应返回到我的应用程序。我不想为此使用任何模板,我想发送我自己的文档进行签名。 我正在使用以下代码。但是,当我使用预定义模板时,它会返回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
代码:
导入java.io.*;
导入java.net.URL;
导入java.net.HttpURLConnection;
导入javax.xml.transform.*;
导入javax.xml.transform.stream.*;
导入javax.xml.xpath.*;
导入org.xml.sax.InputSource;
公共类嵌入签名
{   
公共静态void main(字符串[]args)引发异常
{
字符串integratorKey=“我的集成器密钥”;//集成器密钥(在首选项->API页面上找到)
字符串username=“我的用户名”;//帐户电子邮件(或您的API用户ID)
String password=“我的密码”;//帐户密码
String recipientName=“签名者姓名”;//收件人(签名者)姓名
String recipientEmail=“签名者的电子邮件”;//收件人(签名者)电子邮件
String templateId=“我的模板Id”;//从DocuSign帐户中的模板复制的模板Id
String roleName=“签名者姓名”;//上述帐户模板的模板角色名称
//------------------------------------------------------------------------------------
//构造DocuSign身份验证头
字符串authenticationHeader=
"" + 
“”+用户名+“”+
“”+密码+“”+
“+integratorKey+”+
"";
//附加变量声明
String baseURL=“;//我们将通过登录API调用检索此内容
String accountId=“;//我们将通过登录API调用检索此值
HttpURLConnection conn=null;//用于每个请求的连接对象
字符串url=”“;//每个api调用的结束点
字符串正文=”“;//请求正文
字符串响应=”“;//响应正文
int status;//响应状态
//============================================================================
//步骤1-进行登录API调用以检索baseUrl和accountId
//============================================================================
url=”https://demo.docusign.net/restapi/v2/login_information";
body=”“;//没有登录调用的请求正文
//创建连接对象,设置请求方法,添加请求头
conn=InitializeRequest(url,“GET”、正文、authenticationHeader);
//发送请求
System.out.println(“步骤1:发送登录请求…\n”);
状态=连接getResponseCode();
如果(状态!=200)//200=OK
{
错误解析(连接,状态);
返回;
}
//从响应正文获取baseUrl和accountId值
响应=GetResponseBy(连接);
baseURL=parseXMLBody(响应,“baseURL”);
accountId=parseXMLBody(响应,“accountId”);
System.out.println(“--Login response--\n\n”+prettyFormat(response,2)+”\n”);
//============================================================================
//步骤2-来自模板API调用的签名请求
//============================================================================
url=baseURL+“/envelopes”;//将“/envelopes”附加到baseURL以进行签名请求调用
//本例使用XML格式的请求,也接受JSON格式
body=“”+
“”+accountId+“”+
“已发送”+
“DocuSign API调用-来自模板的签名请求”+
“”+templateId+“”+
"" + 
"" + 
“”+用户名+“”+
“+recipientName+”+
“+roleName+”+
“1001”+//嵌入式发送需要(值为用户定义)
"" + 
"" + 
"";
//为第二个请求重新使用连接对象。。。
conn=初始化请求(url,“POST”、正文、authenticationHeader);
System.out.println(“步骤2:从模板创建信封…\n”);
status=conn.getResponseCode();//触发请求
如果(状态!=201)//201=已创建
{
错误解析(连接,状态);
返回;
}
//从响应体获取信封uri
响应=GetResponseBy(连接);
字符串uri=parseXMLBody(响应,“uri”);
System.out.println(“--信封创建响应--\n\n”+prettyFormat(响应,2));
//============================================================================
//步骤3-获取嵌入式签名视图
//============================================================================
url=baseURL+uri+“/views/recipient”;//将信封uri+“views/recipient”附加到url
//本例使用XML格式的请求,也接受JSON格式
body=“”+
“电子邮件”+
“”+收件人电子邮件+“”+
"http://www.docusign.com/devcenter" + 
“1001”+/***必须与步骤2中设置的clientUserId匹配!
“+recipientName+”+
"";
System.out.print(“步骤3:生成UR