how to void an envelope using C# / XML? - docusignapi

Can anyone tell me how to fix this code, I just get an 400 error:
public string VoidEnvelope(string envelopeID)
{
string url = baseURL + "/envelopes/" + envelopeID;
string requestBody =
"<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<status>voided</status>" +
"<voidedReason>user aborted</voidedReason>" +
"</envelopeDefinition>";
HttpWebRequest request = initializeRequest(url, "PUT", requestBody, email, password);
string response = getResponseBody(request);
return response;
}

When creating an envelope by doing a POST to the /envelopes URI the outer most XML element is defined as
<envelopeDefinition ...
However when modifying an existing envelope using a PUT, the outer most XML element is defined simply as
<envelope ...
So try something like this:
"<envelope>" +
"<status>voided</status>" +
"<voidedReason>user aborted</voidedReason>" +
"</envelope>";
A great resource that many people (including myself) forget about is the Rest API help page. That is probably your best way of learning the XML request bodies and all the potential nodes (it's also great for JSON!)
https://www.docusign.net/restapi/help

Related

DocuSign Implicit Grant with Salesforce

I am integrating DocuSign with salesforce using Rest API in order to send the envelopes.
Before sending any envelopes I was working on an Implicit grant in order to generate a token but I am not sure what is the right way to get the token.
I am using the GET method but I am getting the response in HTML format.
public class SendDocumentsWithDocuSign {
public void test(){
String accountID = 'a6e74d5a-****-****-****-28f3bec67ccf';
String userName = 'f2326e06-****-****-****-a1aee682da08';
String passWord = 'password#123';
String integrationKey = 'b19b477c-****-****-a8a5-8ff88ea771cc';
String templateID = '5259faf7-****-****-a493-ba19ce5d633c';
String redirectURL='https://www.salesforce.com';
//Request the implicit grant
String TOKEN_URL = 'https://account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id='+integrationKey+'&redirect_uri='+redirectURL;
String authenticationHeader =
'<DocuSignCredentials>' +
'<Username>' + userName+ '</Username>' +
'<Password>' + password + '</Password>' +
'<IntegratorKey>' + integrationKey + '</IntegratorKey>' +
'</DocuSignCredentials>';
HttpRequest httpreq = new HttpRequest();
HttpResponse httpres = new HttpResponse();
Http httpCall = new Http();
httpreq.setEndpoint(TOKEN_URL);
httpreq.setMethod('GET');
//httpreq.setHeader('X-DocuSign-Authentication', authenticationHeader);
httpreq.setHeader('Content-Type', 'application/json');
httpreq.setHeader('Accept', 'application/json');
httpres = httpCall.send(httpreq);
System.debug(httpres.getHeaderKeys());
System.debug(httpres.getHeader('X-DocuSign-TraceToken'));
System.debug(httpres.getHeader('Set-Cookie'));
System.debug(httpres.getBody());
}
}
I am getting the below Output.
[32]|DEBUG|(X-DocuSign-Node, X-Content-Type-Options, X-DocuSign-TraceToken, Pragma, Date, X-Frame-Options, Strict-Transport-Security, Cache-Control, Content-Security-Policy, Set-Cookie, ...)
[33]|DEBUG|4d4cac98-7cc9-4b3e-a1fe-c12e871b7065
[34]|DEBUG|__RequestVerificationToken=ARFea2sGN3iGpAjBGHGwCJcB0; path=/; secure; HttpOnly
[35]|DEBUG|
input name="__RequestVerificationToken" type="hidden" value="ARFea2sGN3iGpAjBGHGwCJcAAAAA0"
I want to fetch the access token to call the REST API as given in the DocuSign document. https://developers.docusign.com/platform/auth/implicit/implicit-get-token
To use the DocuSign APEX toolkit, you need to follow the toolkit's authentication methods since that's the only way to use the (needed) integration key from the APEX toolkit.
See the toolkit's authentication instructions.
If you're not using the APEX toolkit then you need to work within the capabilities of SalesForce. Named Credentials is one approach. Here's another.

Microsoft Face API 1.0 Error Resource Not Found

I am working on a face recognition project with Microsoft Azure Cognitive services. Not quite sure why I am not able to correct my own JSON Malformed syntax I thought I nail this 6 months ago. I want to create a group name, so I call upon 'Person Group API' and everytime I follow MS example I get errors in my code however in the API testing Console no problems here is my code example borrow from MS site :
{ "error": { "code": "ResourceNotFound", "message": "The requested resource was not found." } }
and the code which is run in Console mode :
static async void CreateGroup()
{
string key1 = "YourKey";
// azure the one should work
var client = new HttpClient();
var queryString = HttpUtility.ParseQueryString(string.Empty);
// Request headers
client.DefaultRequestHeaders.Add
("Ocp-Apim-Subscription-Key", key1);
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/
persongroups/{personGroupId}?" + queryString;
HttpResponseMessage response;
// Request body
string groupname = "myfriends";
string body = "{\"name\":\"" + groupname + ","+ "\"}";
// Request body
using (var content = new StringContent
(body, Encoding.UTF8, "application/json"))
{
await client.PostAsync(uri, content)
.ContinueWith(async responseTask =>
{
var responseBody = await responseTask.Result
.Content.ReadAsStringAsync();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Response: {0}", responseBody);
Console.WriteLine("");
Console.WriteLine("Group Created.... ");
Console.WriteLine("Hit ENTER to exit...");
Console.ReadKey();
});
response = await client.PutAsync(uri, content);
Console.WriteLine("what is this {0}", response.ToString());
Console.ReadKey();
}// end of using statement
}// end of CreateGroup
#endregion
I am guess here but I think its my JSON is malformed again and I just don't know what I am doing wrong again this time. According to the site the field name that I require to send over to ms is 'name' : 'userData' is optional.
Faced the similar issue, after adding "/detect" in the uri the issue fixed.
See the below
var uri = "https://westus.api.cognitive.microsoft.com/face/v1.0/detect
Also make sure the subscription key is valid.
Your request url must specify a group ID in place of where you have {personGroupId}. Per the spec the group ID must be:
User-provided personGroupId as a string. The valid characters include
numbers, English letters in lower case, '-' and '_'. The maximum
length of the personGroupId is 64.
Furthermore, the http verb needs to PUT, whereas you've made a client.PostAsync request. So you'll need to change that to client.PutAsync.
Microsoft provides a client library for C# for the Face API where you can find working C# code.
In python, simply this worked for me.
ENDPOINT='https://westcentralus.api.cognitive.microsoft.com'

Bad Request on Embedded Console Sign View

I have gone past 2 stages in the Embedded Signing API which I use in my WCF web service using C#.
The login credentials & the request envelope API calls work & the envelopeID is generated.
The 3rd step is the "get URL for the Embedded Console Sign View"
string reqBody = "<recipientViewRequest xmlns=\"http://www.docusign.com/restapi\">" +
"<authenticationMethod>" + "email" + "</authenticationMethod>" +
"<email>" + "jay.krishnamoorthy#gmail.com" + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<returnUrl>" + "http://www.docusign.com" + "</returnUrl>" + // username can be in email format or an actual ID string
"<clientUserId>" + "1001" + "</clientUserId>" +
"<userName>" + "Jay Krishnamoorthy" + "</userName>" +
"</recipientViewRequest>";
// append uri + "/views/recipient" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create(baseURL + uri + "/views/recipient");
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = reqBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body2 = System.Text.Encoding.UTF8.GetBytes(reqBody);
Stream dataStream2 = request.GetRequestStream();
dataStream2.Write(body2, 0, reqBody.Length);
dataStream2.Close();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();-----> comes back with Bad request
Can some one help with the missing info in my request body which causes the BAD request response.
I'm having trouble making sense of the reqBody value in your question, so instead of commenting on that, I'll just provide a simple example of what a proper POST Recipient View request looks like (in XML format):
POST https://{{env}}.docusign.net/restapi/{{version}}/accounts/{{acctId}}/envelopes/{{envelopeId}}/views/recipient
<recipientViewRequest xmlns="http://www.docusign.com/restapi">
<authenticationMethod>Email</authenticationMethod>
<email>RECIPIENT_EMAIL_ADDRESS</email>
<returnUrl>http://www.google.com</returnUrl>
<clientUserId>CLIENT_USER_ID_VALUE_SPECIFIED_IN_THE_REQUEST</clientUserId>
<userName>RECIPIENT_NAME</userName>
</recipientViewRequest>
I'd suggest that you compare the request URI and request body I've included here with what you're sending, and adjust yours as needed to match.
Additionally, I'd recommend that you use a tool like "Fiddler" or something similar to examine the XML Request and Response as they're being sent over the wire -- i.e., identify problems by examining the raw XML using Fiddler, then update your code to fix the problems (i.e., to generate/send a properly formatted request). Being able to produce a trace of the raw XML Request / Response is a requirement of the DocuSign API Certification process, so you might as well figure that out sooner rather than later, as it's a valuable troubleshooting asset during development as well (when you get a "Bad Request" response like you're getting).
Your request body has all the proper elements and looks to be correct on first glance, however I see what you are doing wrong now. In your request body when you set the authentication method I see that you are setting it to:
"<authenticationMethod>" + "email" + "</authenticationMethod>"
This is incorrect. The value here actually needs to be the string email or Email, you don't enter the recipient's actual email address. The point of the authenticationMethod property is to tell the system what level of authentication you are expecting. If set to email then you are telling the system simply that the email address is the only form of authentication you want for that recipient. So what you want instead is:
"<authenticationMethod>email</authenticationMethod>"

Docusign API - request for signature using Template

I am trying to test the REST API for request a signature on a document referenced through a template using C# in a WCF webservice.
The Step 1 for Login works & returns the accountID & baseURl;
The Step 2 fails with a Bad Request.
Here is my code:
try {
...
string requestBody = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<accountId>" + accountId + "</accountId>" +
"<status>" + "sent" + "</status>" +
"<emailSubject>" + "API Call for Embedded Sending" + "</emailSubject>" +
"<emailBlurb>" + "This comes from C#" + "</emailBlurb>" +
"<templateId>" + "9A535489-0FB6-42B2-82C1-A06DA36025B4" + "</templateId>" +
"<templateRoles>" +
"<email>" + "abc#gmail.com" + "</email>" + // NOTE: Use different email address if username provided in non-email format!
"<name>" + "GRAVITY1003" + "</name>" + // username can be in email format or an actual ID string
"<roleName>" + "GRAVITY1003" + "</roleName>" +
"</templateRoles>" +
"</envelopeDefinition>";
// append "/envelopes" to baseUrl and use in the request
request = (HttpWebRequest)WebRequest.Create(baseURL + "/envelopes");
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = requestBody.Length;
request.Method = "POST";
// write the body of the request
byte[] body = System.Text.Encoding.UTF8.GetBytes(requestBody);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, requestBody.Length);
dataStream.Close();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();------> It fails here
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();
uri = responseText;
}
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);
}
}
}
Can anyone tell me what I am doing wrong ? I looked at the API walkthrough's & coded this accordingly. Not sure why this is happening.
Looks like there was a bug in the Gist you were working off of, the wrong version was mistakenly uploaded. The Gist has been fixed, the issue was just one xml node that was missing.
Since you can have multiple template roles on a given template, there needs to be an extra xml node that separates each role. What you need to do is add singular <templateRole></templateRole> xml nodes in between the <templateRoles></templateRoles> nodes.
So your request body should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<envelopeDefinition xmlns="http://www.docusign.com/restapi">
<accountId>123456</accountId>
<status>sent</status>
<emailSubject>API Call for sending signature request from template</emailSubject>
<emailBlurb>This comes from Java</emailBlurb>
<templateId>EA64D446-3BFA-*********************</templateId>
<templateRoles>
<templateRole>
<email>recipient_email_address</email>
<name>recipient_name</name>
<roleName>template_role_name</roleName>
</templateRole>
</templateRoles>
</envelopeDefinition>

ServiceStack - Switch off Snapshot

I've followed instructions on how creating a ServiceStack here at:
https://github.com/ServiceStack/ServiceStack/wiki/Create-your-first-webservice
I'm sure I have followed it to the letter, but as soon as I run the web application. I get a 'Snapshot' view of my response. I understand this happens when I don't have a default view/webpage. I set up the project as a ASP.net website, not a ASP.net MVC website. Could that be the problem?
I also wrote a test console application with the following C# code. It got the response as a HTML webpage rather than as a plain string e.g. "Hello, John".
static void sendHello()
{
string contents = "john";
string url = "http://localhost:51450/hello/";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
request.ContentLength = contents.Length;
request.ContentType = "application/x-www-form-urlencoded";
// SEND TO WEBSERVICE
using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(contents);
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string result = string.Empty;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
result = reader.ReadToEnd();
}
Console.WriteLine(result);
}
How can I switch off the 'snapshot' view? What am I doing wrong?
The browser is requesting html so ServiceStack is returning the html snapshot.
There are a couple of ways to stop the snapshot view:
First is to use the ServiceClient classes provided by servicestack. These also have the advantage of doing automatic routing and strongly typing the response DTOs.
Next way would be to set the Accept header of the request to something like application/json or application/xml which would serialize the response into json or xml respectively. This is what the ServiceClients do internally
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Accept = "application/json";
...
Another method would be to add a query string parameter called format and set it to json or xml
string url = "http://localhost:51450/hello/?format=json";
Putting the specific format requesting is the practical way to do this
string url = "http://localhost:51450/hello/?format=json";
I suggest simply deleting this feature.
public override void Configure(Container container)
{
//...
this.Plugins.RemoveAll(p => p is ServiceStack.Formats.HtmlFormat);
//...
}
Now all requests with the Content-Type=text/html will be ignored.

Resources