当前位置: 首页 > 知识库问答 >
问题:

尝试创建带有多个文档的DocuSign信封

东郭自强
2023-03-14

我试图使用DocuSign REST API创建一个包含多个文档的信封,我创建了一个C#控制台应用程序,并以JSON格式在请求中写入了信封参数。我得到了错误代码“信封不完整”,我试图将我的请求与REST API Docusign指南中的请求进行比较,但我看不到我遗漏了什么。下面是我的示例代码:

public class RequestSignature
    {
        // Enter your info here:
        static string email = "email";
        static string password = "password";
        static string integratorKey = "key";    

        public static void Main()
        {
            string url = "https://demo.docusign.net/restapi/v2/login_information";
            string baseURL = "";    // we will retrieve this
            string accountId = "";  // will retrieve

            var objectCredentials = new { Username = email, Password = password, IntegratorKey = integratorKey };

            string jSONCredentialsString = JsonConvert.SerializeObject(objectCredentials);

            // 
            // STEP 1 - Login
            //
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                // request.Headers.Add("X-DocuSign-Authentication", authenticateStr);

                request.Headers.Add("X-DocuSign-Authentication", jSONCredentialsString);
                request.Accept = "application/json";
                request.Method = "GET";


                HttpWebResponse webResponse = (HttpWebResponse)request.GetResponse();
                StreamReader sr = new StreamReader(webResponse.GetResponseStream());
                string responseText = sr.ReadToEnd();

                //  close stream reader
                sr.Close();
                JsonTextReader reader = new JsonTextReader(new StringReader(responseText));
                JObject jObject = JObject.Parse(responseText);

                // get the first User Account data
                JToken jUserAccount = jObject["loginAccounts"].First;
                // read values from JSON
                accountId = (string)jUserAccount["accountId"];
                baseURL = (string)jUserAccount["baseUrl"];

                //
                // STEP 2 - Send Envelope with Information
                //

                // construct an outgoing JSON request body that create the envelope
                string formDataBoundary = String.Format("{0:N}", Guid.NewGuid());
                StringBuilder requestBody = new StringBuilder();

                string header = string.Format("--{0}\r\nContent-Type: application/json\r\nContent-Disposition: form-data\r\n\r\n", formDataBoundary);

                // Documents list to send in the envelope
                List<Document> envelopeDocuments = new List<Document>();

                Document currentDocument = new Document(1, "ABC.pdf", "C:/Documents/ABC.pdf");
                envelopeDocuments.Add(currentDocument);

                DocuSignDocument[] documentsArray = (from doc in envelopeDocuments
                                                    select new DocuSignDocument()
                                                    {
                                                        documentId = doc.DocumentID.ToString(),
                                                        name = doc.Name
                                                    }).ToArray();

                //currentDocument = new Document(2, "ABC.pdf", "D:/Documents/ABC.pdf");
                //envelopeDocuments.Add(currentDocument);

                // creaqte recipients
                Recipient firstRecipient = new Recipient()
                                           {
                                               email = "email",
                                               name = "name",
                                               recipientId = 1.ToString(),
                                               routingOrder = 1.ToString(),
                                               tabs = new Tabs()
                                                      {
                                                          signHereTabs = new List<Tab>()
                                                                         {  new Tab()
                                                                            {
                                                                                documentId = 1.ToString(),
                                                                                pageNumber = 1.ToString(),
                                                                                //recipientId = 1.ToString(),
                                                                                xPosition = 100.ToString(),
                                                                                yPosition = 100.ToString()
                                                                            }
                                                                         }  
                                                      }
                                           };

                List<Recipient> recipients = new List<Recipient>();
                recipients.Add(firstRecipient);
                // api json attributes setting by developer

                // setting attributes for the envelope request 

                var envelopeAttributes = new
                    {
                        //allowReassign = false,
                        emailBlurb = "EMAIL BODY HERE OK OK",
                        emailSubject = "EMAIL SUBJECT HERE IS MANDATORY",
                        // enableWetSign = false,
                        // messageLock = true,

                        // notification attributes                 
                        /*notifications = new
                            {
                                useAccountDefaults = true,

                                // reminder configuration attributes
                                reminders = new object[]
                                                {
                                                    new 
                                                    { 
                                                        reminderEnabled = true,
                                                        reminderDelay = 3,
                                                        reminderFrequency = 3
                                                    }
                                                },
                                // end reminder configuration attributes

                                // expiration configuration attributes
                                expirations = new object[] 
                                                  {
                                                      new 
                                                      {
                                                          expirationEnabled = true,
                                                          expirationAfter = 30,
                                                          expirationWarn = 5
                                                      }
                                                  }
                            }, */
                        // end notification attributes
                        status = "sent",

                        // start documents section
                        documents = documentsArray,
                        recipients = new 
                            {
                                signers = recipients
                            }

                    };

                // append "/envelopes" to baseURL and use in the request
                request = (HttpWebRequest)WebRequest.Create(baseURL + "/envelopes");
                request.Headers.Add("X-DocuSign-Authentication", jSONCredentialsString);
                request.ContentType = "multipart/form-data; boundary=" + formDataBoundary;
                request.Accept = "application/json";
                request.Method = "POST";
                request.KeepAlive = true;
                request.Credentials = System.Net.CredentialCache.DefaultCredentials;
                string requestBodyStartStr = header;

                requestBodyStartStr += JsonConvert.SerializeObject(envelopeAttributes);
                requestBodyStartStr += "\r\n--" + formDataBoundary + "\r\n";
                // Write the body of the request
                byte[] bodyStart = System.Text.Encoding.UTF8.GetBytes(requestBodyStartStr);

                MemoryStream streamBufferData = new MemoryStream();
                streamBufferData.Write(bodyStart, 0, bodyStart.Length);

                // Read the file contents and write them to the request stream
                byte[] buf = new byte[4096];
                int length;
                FileStream fileStream;

                string mixedHeaderBoundary = String.Format("{0:N}", Guid.NewGuid());
                // add multipart mixed header
                string mixedHeader = "Content-Disposition: form-data\r\n";
                mixedHeader += "Content-Type: multipart/mixed; boundary=" + mixedHeaderBoundary + "\r\n\r\n";

                byte[] bodyMixedHeader = System.Text.Encoding.UTF8.GetBytes(mixedHeader);
                streamBufferData.Write(bodyMixedHeader, 0, bodyMixedHeader.Length);

                foreach (Document document in envelopeDocuments)
                {
                    fileStream = null;
                    // load file from location
                    fileStream = File.OpenRead(document.PathName);

                    // write header of pdf
                    string headerOfDocumentStr = "--" + mixedHeaderBoundary + "\r\n" + 
                           "Content-Type: application/pdf\r\n" +
                        "Content-Disposition: file; filename=\"" + document.Name + "\";documentId=\"" + document.DocumentID + "\"\r\n\r\n";

                    byte[] headerDocBytes = System.Text.Encoding.UTF8.GetBytes(headerOfDocumentStr);
                    streamBufferData.Write(headerDocBytes, 0, headerDocBytes.Length);

                    length = 0;
                    while ((length = fileStream.Read(buf, 0, 4096)) > 0)
                    {
                        streamBufferData.Write(buf, 0, length);
                    }

                    fileStream.Close();

                    //byte[] bottomMixedBoundaryForFDocument = System.Text.Encoding.UTF8.GetBytes("\r\n--" + mixedHeaderBoundary + "\r\n");
                    //streamBufferData.Write(bottomMixedBoundaryForFDocument, 0, bottomMixedBoundaryForFDocument.Length);

                }

                string requestBodyEndStr = "--" + mixedHeaderBoundary + "--\r\n";

                byte[] requestBodyEndBytes = System.Text.Encoding.UTF8.GetBytes(requestBodyEndStr);
                streamBufferData.Write(requestBodyEndBytes, 0, requestBodyEndBytes.Length);

                // write end boundary
                requestBodyEndStr = "--" + formDataBoundary + "--";


                requestBodyEndBytes = System.Text.Encoding.UTF8.GetBytes(requestBodyEndStr);
                streamBufferData.Write(requestBodyEndBytes, 0, requestBodyEndBytes.Length);

                // pass temporary buffer data to WebRequestStream
                request.ContentLength = streamBufferData.Length;

                Stream dataStream = request.GetRequestStream();
                byte[] byteArrayToSend = new byte[streamBufferData.Length];

                streamBufferData.Seek(0, SeekOrigin.Begin);
                streamBufferData.Read(byteArrayToSend, 0, (int)streamBufferData.Length);

                dataStream.Write(byteArrayToSend, 0, (int)streamBufferData.Length);

                streamBufferData.Close();

                // read the response
                webResponse = (HttpWebResponse)request.GetResponse();
                responseText = "";
                sr = new StreamReader(webResponse.GetResponseStream());
                responseText = sr.ReadToEnd();

                // display results
                Console.WriteLine("Response of Action Create Envelope with Two Documents --> \r\n " + responseText);
                Console.ReadLine();
            }
            catch (WebException e)
            {
                using (WebResponse response = e.Response)
                {
                    HttpWebResponse httpResponse = (HttpWebResponse)response;
                    Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                    using (Stream data = response.GetResponseStream())
                    {
                        string text = new StreamReader(data).ReadToEnd();
                        Console.WriteLine(text);
                    }
                }
                Console.ReadLine();
            }
        } 
    } 
public class Tab
{
    public int documentId { get; set; }
    public int pageNumber { get; set; }
    public int recipientId { get; set; }
    public int xPosition { get; set; }
    public int yPosition { get; set; }
    public string name { get; set; }
    public string tabLabel { get; set; }
}

public class Tabs
{
    public List<Tab> signHereTabs { get; set; }    
}


public class Recipient
{
    public string email { get; set; }
    public string name { get; set; }
    // public int recipientId { get; set; }
    public int routingOrder { get; set; }

    public Tabs tabs { get; set; } 
}

POST https://demo.docusign.net/restapi/v2/accounts/295724/envelets http/1.1 x-docusign-身份验证:{“username”:“email”,“password”:“username”,“integratorkey”:“key”}内容-类型:multipart/form-data;boundary=C17EFB7771A64F688508187FEE57C398 Accept:Application/JSON主机:demo.docusign.net内容-长度:147201 Expect:100-继续

--C17EFB7771A64F688508187FEE57C398内容-类型:应用程序/JSON内容-处置:表单-数据

{“emailblurb”:“电子邮件正文在此OK OK”,“emailsubject”:“电子邮件主题在此强制”,“状态”:“已发送”,“文档”:[{“documentid”:1,“名称”:“abc.pdf”}],“收件人”:{“签名者”:[{“email”:“dn@brenock.com”,“名称”:“dubhe”,“收件人”:“1”,“例程顺序”:“1”,“选项卡”:{“signheretabs”:[{“documentid”:“1”,“pagenumber”:“1”,“xposition”:“100”,71A64F688508187FEE57C398内容-配置:表单-数据内容-类型:多部分/混合;边界=B670EC35BD824DFF8C0EEFE62035E0B2

--B670EC35BD824DFF8C0EEFE62035E0B2内容-类型:应用程序/PDF内容-处置:文件;filename=“abc.pdf”;文档=1

--B670EC35BD824DFF8C0EEFE62035E0B2---C17EFB7771A64F688508187FEE57C398-

共有1个答案

戎亦
2023-03-14

我认为问题出在您发送的JSON上。它是有效的JSON格式,但是recipientId的值被删除或没有设置。收件人有以下内容:

"recipientId": null,

若要解决此问题,请将其设置为

"recipientId": "1",

或者您想为它设置的任何值,因为它是用户可配置的。例如,如果需要,可以将其设置为“4321”。

"signHereTabs": [
    {
        "documentId": "1",
        "pageNumber": "1",
        "xPosition": "100",
        "yPosition": "100"
    }
]
CRLF (\r\n)

性格。这是它需要的格式:

--AAA
Content-Type: application/json
Content-Disposition: form-data

<YOUR VALID JSON GOES HERE>
--AAA
Content-Disposition: form-data
Content-Type: multipart/mixed; boundary=BBB

--BBB
Content-Type:application/pdf
Content-Disposition: file; filename=\”document1.pdf"; documentid=1

<PDF Bytes for first document>
--BBB
Content-Type:application/pdf
Content-Disposition: file; filename=\”document2.pdf"; documentid=2

<PDF Bytes for second document>
--BBB--
--AAA--

如果您只发送一个文档,那么您的间距需要完全如下所示:

--AAA
Content-Type: application/json
Content-Disposition: form-data

<YOUR VALID JSON GOES HERE>
--AAA
Content-Type:application/pdf
Content-Disposition: file; filename="document.pdf"; documentid=1 

<DOCUMENT BYTES GO HERE>
--AAA--
 类似资料:
  • 我正在将accesstoken与文档数据一起发送,但收到此错误。我发送单据数据的顺序是否正确

  • 问题内容: 我正在将Spring MVC(3.0)与注释驱动的控制器一起使用。我想为资源创建REST-FUL网址,而且能够 不 要求(但仍可选允许)的URL的末尾文件扩展名(但如果没有扩展假设HTML内容类型)。只要文件名部分中没有点(句点/句号),它就可以与Spring MVC一起使用。 但是,我的某些URL要求名称中带有点的标识符。例如: 在这种情况下,Spring会为扩展寻找内容类型,但没有

  • 我知道在最新版本的Mongoose中,您可以将多个文档传递给create方法,在我的例子中,甚至可以传递一个文档数组。 我的问题是数组的大小是动态的,所以在回调中创建一个对象数组会很有帮助。 文档中没有,但这样做可能吗?

  • 问题内容: 假设我有一个名为root的集合 我可以在一次调用中创建带有其子集合的文档吗? 我的意思是,如果我这样做: 那会在一瞬间创造出结构吗?老实说,我尝试了一下,doc1的标题为斜体,我认为仅适用于已删除的文档 问题答案: 您共享的代码不会创建实际的文档。它仅“保留”其中的文档ID ,然后在其下创建带有实际文档的集合。 在Firestore控制台中以斜体显示文档名称表示该位置没有物理文档,但是

  • 使用C#、DocuSign API SDK 4.5.2。 我在同一个信封里寄出三份文件供签名。每个文档将使用相同的服务器模板(它只是使用锚标记将签名元素放置在文档上)。我可以寄出信封,然后从DocuSign收到电子邮件,查看/签署文件。 我遇到的问题是,当我去签名时,我必须在每个文档上签名3次--总共9次--然后才允许单击Finish按钮。每个文件只有一个地方可以签名,但我必须点击签名按钮3次才能