REST Update Recipient Email using PUT Method - api

I am new to REST and keep getting the Bad Request 400 Response with the code below:
I have the standard baseURL and authenticateStr from the other sample...
_recipientID, pNewEmail, pNewName and pNewRoutingOrder are passed in as parameters to the procedures.
string envDef = "<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">" +
"<signers>" +
"<signer>" +
"<recipientId>" + _recipientId + "</recipientId>" +
"<email>" + pNewEmail + "</email>" +
"<name>" + pNewName + "</name>" +
"<routingOrder>" + pNewRoutingOrder + "</routingOrder>" +
"</signer>" +
"</signers>" +
"</envelopeDefinition>";
url = baseURL + "/envelopes/" + pEnvelopeID + "/recipients";
request = (HttpWebRequest)WebRequest.Create(url);
request.Headers.Add("X-DocuSign-Authentication", authenticateStr);
request.ContentType = "application/xml";
request.Accept = "application/xml";
request.ContentLength = envDef.Length;
request.Method = "PUT";
// write the body of the request
byte[] body = System.Text.Encoding.UTF8.GetBytes(envDef);
Stream dataStream = request.GetRequestStream();
dataStream.Write(body, 0, envDef.Length);
dataStream.Close();
// read the response
webResponse = (HttpWebResponse)request.GetResponse();
sr.Close();
responseText = "";
sr = new StreamReader(webResponse.GetResponseStream());
responseText = sr.ReadToEnd();

Ok just figured out how to do this. Here's an XML request body that can be used to update the email and name of a recipient, for instance. I just verified that this works!
<recipients xmlns="http://www.docusign.com/restapi">
<signers>
<signer>
<recipientId>1</recipientId>
<email>email#docusign.com</email>
<name>Joe Mama</name>
</signer>
</signers>
</recipients>

Related

Get trending topics of twitter api with C#

I get "401 Unauthorized" error while trying to get the current trends using the twitter api but the below code work fine if I try to get some other response like user_timeline,available,tweets. Below is my code please tell me where iam wrong.
var oauth_token = "****";
var oauth_token_secret = "****";
var oauth_consumer_key = "****";
var oauth_consumer_secret = "****";
// oauth implementation details
var oauth_version = "1.0";
var oauth_signature_method = "HMAC-SHA1";
// unique request details
var oauth_nonce = Convert.ToBase64String(
new ASCIIEncoding().GetBytes(DateTime.Now.Ticks.ToString()));
var timeSpan = DateTime.UtcNow
- new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
var oauth_timestamp = Convert.ToInt64(timeSpan.TotalSeconds).ToString();
// message api details
var status = "Updating status via REST API if this works";
//var resource_url = "https://api.twitter.com/1.1/statuses/user_timeline.json";
//var resource_url = "https://api.twitter.com/1.1/search/tweets.json";
// var resource_url = "https://api.twitter.com/1.1/trends/place.json";
var resource_url = "https://api.twitter.com/1.1/trends/available.json";
//var screen_name = "screenname";
var query = "india";
var id = "1";
// create oauth signature
//var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
// "&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&screen_name={6}";
//var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
//"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&q={6}";
var baseFormat = "oauth_consumer_key={0}&oauth_nonce={1}&oauth_signature_method={2}" +
"&oauth_timestamp={3}&oauth_token={4}&oauth_version={5}&id={6}";
var baseString = string.Format(baseFormat,
oauth_consumer_key,
oauth_nonce,
oauth_signature_method,
oauth_timestamp,
oauth_token,
oauth_version,
id);
baseString = string.Concat("GET&", Uri.EscapeDataString(resource_url), "&", Uri.EscapeDataString(baseString));
var compositeKey = string.Concat(Uri.EscapeDataString(oauth_consumer_secret),
"&", Uri.EscapeDataString(oauth_token_secret));
string oauth_signature;
using (HMACSHA1 hasher = new HMACSHA1(ASCIIEncoding.ASCII.GetBytes(compositeKey)))
{
oauth_signature = Convert.ToBase64String(
hasher.ComputeHash(ASCIIEncoding.ASCII.GetBytes(baseString)));
}
// create the request header
var headerFormat = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"{1}\", " +
"oauth_timestamp=\"{2}\", oauth_consumer_key=\"{3}\", " +
"oauth_token=\"{4}\", oauth_signature=\"{5}\", " +
"oauth_version=\"{6}\"";
var authHeader = string.Format(headerFormat,
Uri.EscapeDataString(oauth_nonce),
Uri.EscapeDataString(oauth_signature_method),
Uri.EscapeDataString(oauth_timestamp),
Uri.EscapeDataString(oauth_consumer_key),
Uri.EscapeDataString(oauth_token),
Uri.EscapeDataString(oauth_signature),
Uri.EscapeDataString(oauth_version)
);
// make the request
ServicePointManager.Expect100Continue = false;
//var postBody = "screen_name=" + Uri.EscapeDataString(screen_name);
//var postBody = "q=" + Uri.EscapeDataString(query);
var postBody = "id=" + Uri.EscapeDataString(id);
// resource_url += "?" + postBody;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(resource_url);
request.Headers.Add("Authorization", authHeader);
request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
WebResponse response = request.GetResponse();
string responseData = new StreamReader(response.GetResponseStream()).ReadToEnd();
Console.ReadLine();

Invalid signature error with UpgradeableApp API

I am trying to run a code that would allow me to migrate Google Apps Marketplace to upgrade my apps to use OAuth 2.0 authentication for subscribed domains.
Unfortunately, I receive the following error message:
{"error":{"errors":[{"domain":"global","reason":"authError","message":"Invalid OAuth signature","locationType":"header","location":"Authorization"}],"code":401,"message":"Invalid OAuth signature"}}
The code that I run is:
final String consumerKey = "xxx";
final String consumerSecret = "yyy";
final String domain = "example.com";
final String account = "admin#example.com";
OAuthParameters oauthParameters = new OAuthParameters();
oauthParameters.setOAuthConsumerKey(consumerKey);
oauthParameters.setOAuthConsumerSecret(consumerSecret);
OAuthHmacSha1Signer signer = new OAuthHmacSha1Signer();
final String marketPlaceListingId = "xxxx+xxxxxxxxxxxxxxxxxxx";
final String chromeWebStoreItemId = "yyyyyyyyyyyyyyyyyyyyyyyyyyyy";
String requestUrl = "https://www.googleapis.com/appsmarket/v2/upgradableApp/"
+ marketPlaceListingId + "/" + chromeWebStoreItemId + "/" + domain;
String oauth_nonce = OAuthUtil.getNonce();
String oauth_timestamp = OAuthUtil.getTimestamp().toString();
String signatureMethod = "HMAC-SHA1";
oauthParameters.setOAuthType(OAuthType.TWO_LEGGED_OAUTH);
oauthParameters.setOAuthNonce(oauth_nonce);
oauthParameters.setOAuthTimestamp(oauth_timestamp);
oauthParameters.setOAuthSignatureMethod(signatureMethod);
String baseString = "PUT"
+ "&" + OAuthUtil.encode(requestUrl)
+ "&" + OAuthUtil.encode("oauth_consumer_key=" + oauthParameters.getOAuthConsumerKey()
+ "&oauth_nonce=" + oauth_nonce
+ "&oauth_signature_method=" + signatureMethod
+ "&oauth_timestamp=" + oauth_timestamp
+ "&oauth_version=1.0"
+ "&xoauth_requestor_id=" + OAuthUtil.encode(account));
String oauth_signature = signer.getSignature(baseString, oauthParameters);
oauthParameters.setOAuthSignature(oauth_signature);
OAuthHelper oauthHelper = new GoogleOAuthHelper(signer);
String header = oauthHelper.getAuthorizationHeader(requestUrl + "?xoauth_requestor_id=" + OAuthUtil.encode(account), "PUT", oauthParameters);
HttpClient httpClient = new DefaultHttpClient();
HttpPut httpPut = new HttpPut(requestUrl + "?xoauth_requestor_id=" + OAuthUtil.encode(account));
httpPut.addHeader("Authorization", header);
//httpPut.addHeader("Content-Type", "application/x-www-form-urlencoded");
HttpResponse response = null;
try {
response = httpClient.execute(httpPut);
} catch (Exception e) {
System.out.println(e.getMessage());
throw new ServletException(e);
}
Please support.
Thank you,
Evgeny

How can I pass a notification to multiple users with GCM?

I am trying :
private void GcmPushNotification(string deviceId)
{
string message="New post from Admin";
string GoogleAppID = "AIzaSyCYesJ5dCK8-O-tf8ZxADELQx5e05P-l5I";
var SENDER_ID = "854837747831";
var value = message;
WebRequest tRequest;
tRequest = WebRequest.Create("https://android.googleapis.com/gcm/send");
tRequest.Method = "post";
// --- text
tRequest.ContentType = " application/x-www-form-urlencoded;charset=UTF-8";
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + deviceId + "";
tRequest.Headers.Add(string.Format("Authorization: key={0}", GoogleAppID));
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
tReader.Close();
dataStream.Close();
tResponse.Close();
}
If you want to send the same notification to multiple devices (up to 1000 registration IDs), you have to use the JSON request format instead of the URL encoded you are currently using.
For example (taken from here):
Content-Type:application/json
Authorization:key=AIzaSyB-1uEai2WiUapxCs2Q0GZYzPu7Udno5aA
{
"registration_ids" : ["APA91bHun4MxP5egoKMwt2KZFBaFUH-1RYqx..."],
"data" : {
...
},
}

Paypal IPN cannot send to my MVC 4 controller action

I try to get IPN message from my MVC Controller action but IPN cannot send to my action controller
The following is my controller action :
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(HttpContext.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(Param);
strRequest = strRequest + "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
//req.Proxy = proxy
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED") {
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
} else if (strResponse == "INVALID") {
//log for manual investigation
} else {
//Response wasn't VERIFIED or INVALID, log for manual investigation
}
The following is paypal information I used :
<add key="paypalAccount" value="abc#abc.com" />
<add key="PayPalSubmitUrl" value="https://www.paypal.com/cgi-bin/webscr"/>
<add key="PDTToken" value="asdfwlfti2Rc_Kskwsdfc7uK26FmT1pdAkhSdLb8FvS2kQ-ZQp6VoF2SqYem"/>
<add key="FromMail" value="myat#abc.com"/>
<add key="return_Url" value="http://testing/Purchase/PayPalResult"/>
<add key="cancel_return" value="http://testing/Purchase/Purchase"/>
<add key="notify_url" value="http://testing/Purchase/PayPalPaymentNotification"/>
<add key="Test_Live" value="live"/>
<add key="BCC" value="myat#abc.com"/>
But in paypal IPN message is still retrying and I didn't receive anything
I notice that HttpContext.Request.ContentLength is always 0 and response status for paypal is always is INVALID
So please advice me what should I do?
Thank you
This is my full action to get IPN message
public ActionResult PayPalPaymentNotification()
{
string strLog = "";
string currentTime = "";
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Start IPN request','" + currentTime + "')";
InsertData(strLog);
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strLive);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
byte[] Param = Request.BinaryRead(HttpContext.Request.ContentLength);
string strRequest = Encoding.ASCII.GetString(Param);
strRequest = strRequest + "&cmd=_notify-validate";
req.ContentLength = strRequest.Length;
//for proxy
//Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
//req.Proxy = proxy
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
streamOut.Write(strRequest);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
if (strResponse == "VERIFIED")
{
//check the payment_status is Completed
//check that txn_id has not been previously processed
//check that receiver_email is your Primary PayPal email
//check that payment_amount/payment_currency are correct
//process payment
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Status - Verified','" + currentTime + "')";
InsertData(strLog);
}
else if (strResponse == "INVALID")
{
//log for manual investigation
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Status - Invalid','" + currentTime + "')";
InsertData(strLog);
}
else
{
//Response wasn't VERIFIED or INVALID, log for manual investigation
}
currentTime = DateTime.Now.Day.ToString() + "-" + DateTime.Now.Month.ToString() + "-" + DateTime.Now.Year + "|" + DateTime.Now.TimeOfDay.Hours.ToString() + ":" + DateTime.Now.TimeOfDay.Minutes.ToString() + ":" + DateTime.Now.TimeOfDay.Seconds.ToString();
strLog = "Insert into CPLog(Log,LogTime) values('Finish IPN Request','" + currentTime + "')";
InsertData(strLog);
return View();
}
Your return URL isn't right - the message can never be returned.
Add [AllowAnonymous] above the controller action.
Paypal needs to know the URL of your listener service that indicates where the IPNs need to go. You must review the IPN Notification section on your Paypal account and set the URL.
For this you can review the following section: Paypal developer and set the notifications URL.
After that you must have a payment notification to recieve.
My recomendation is first use the Paypal developer section with Sandbox whis is king of fake account that you can use for testing this application.

HttpWebRequest works. WebClient.UploadFile doesn't

I thought I figured out a way to simplify my code by using WebClient.UploadFile instead of HttpWebRequest, but I end up getting a file on the server end that is a few dozen bytes too short and corrupted. Any idea where the bug lies?
Thanks
Using HttpWebRequest (works fine):
HttpWebRequest req = (HttpWebRequest)HttpWebRequest
.Create("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash);
req.Method = "POST";
req.ContentType = "binary/octet-stream";
req.AllowWriteStreamBuffering = false;
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
int offset = 0;
while (offset < ____)
{
reqStream.Write(bytes, offset, _________);
_______
_______
_______
}
reqStream.Close();
try
{
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
}
catch (Exception e)
{
_____________
}
return safehash;
Using WebClient (corrupt file on server end):
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add(HttpRequestHeader.ContentType, "binary/octet-stream");
client.UploadFile(new Uri("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash), filename);
return safehash;
Server side is a WCF service:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "up/file/{fileName}/{hash}")]
void FileUpload(string fileName, string hash, Stream fileStream);
WebClient.UploadFile sends the data in a multipart/form-data format. What you want to use to have the equivalent to the code using HttpWebRequest is the WebClient.UploadData method:
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
byte[] fileContents = File.ReadAllBytes(filename);
client.UploadData(new Uri("http://" + ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash), fileContents);