Paytm Integration - SendOTP API -- 434 bad request error - c#

Working on Integrating Paytm with C# application.
I'm using Auto debit flow for integration purpose.
As part of this flow, SENDOTP API provided by Paytm needs to be invoked for sending the OTP to the customer mobile.
I have used the code which i got from the Paytm developer site.
https://developer.paytm.com/docs/send-otp-api/
.Net Code:
String url = "https://accounts-uat.paytm.com/signin/otp";
Dictionary<String, String> paytmParams = new Dictionary<String, String>();
paytmParams.Add("email", xxxxxxx#xxxxxxx.xxx);
paytmParams.Add("phone", xxxxxxxxxx);
paytmParams.Add("clientId", xxxxxxxx-xxx);
paytmParams.Add("scope", wallet);
paytmParams.Add("responseType", token);
try {
String postData = "JsonData="+ new JavaScriptSerializer().Serialize(paytmParams);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("ContentType", "application/json");
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream())) {
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
string string responseData = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse())) {
responseData = responseReader.ReadToEnd();
}
} catch (Exception ex) {
Response.Write("Exception message: " + ex.Message.ToString());
}
Below is the request format :
JsonData = {
"email":"login2kkr#gmail.com",
"phone":"XXXXXXXXXX",
"clientId":"merchant-ABC",
"scope":"Wallet",
"responseType":"Token"
}
Response:
{
"status":"FAILURE",
"responseCode":"434",
"message":"Bad Request"
}
Regards,
Kishore.

I have tried using the below code and worked for me.
string url = "https://accounts.paytm.com/signin/otp";
Dictionary<string, string> paytmParams = new Dictionary<string, string>();
paytmParams.Add("email", "xxxxxxx#xxxxx.com");
paytmParams.Add("phone", "xxxxxxxxxxx");
paytmParams.Add("clientId", "paytm-web-secure");
paytmParams.Add("scope", "wallet");
paytmParams.Add("responseType", "token");
try
{
string postData = new JavaScriptSerializer().Serialize(paytmParams);
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
webRequest.Headers.Add("ContentType", "application/json");
webRequest.Method = "POST";
using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream()))
{
streamWriter.Write(postData);
streamWriter.Flush();
streamWriter.Close();
}
string responseData = string.Empty;
string statusCode = string.Empty;
string state = string.Empty;
using (StreamReader responseReader = new StreamReader(webRequest.GetResponse().GetResponseStream()))
{
responseData = responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
Response.Write("Exception message: " + ex.Message.ToString());
}

Related

How to create HTTP GET request to google calendar API with c#?

Hello guys I am newbie and I am creating http get request to google calendar api, I just want to get event data with eventid and calendarid
https://developers.google.com/calendar/v3/reference/events/get
this is link of google api, where you can also test API
class Program
{
private static readonly HttpClient _Client = new HttpClient();
private static JavaScriptSerializer _Serializer = new JavaScriptSerializer();
static void Main(string[] args)
{
string CalendarID = "somecalendar#group.calendar.google.com";
string EventID = "someid";
{
string URL = "https://www.googleapis.com/calendar/v3/calendars/"+ CalendarID + "/events/"+ EventID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
request.Method = "GET";
request.ContentType = "application/json";
var cust = new Dictionary<string, string>
{
{"somecalendar#group.calendar.google.com", "someid" }
};
var json = _Serializer.Serialize(cust);
string data = JsonConvert.SerializeObject(cust);
request.ContentLength = data.Length;
StreamWriter requestWriter = new StreamWriter(request.GetRequestStream(), Encoding.ASCII);
requestWriter.Write(data);
requestWriter.Close();
WebResponse webResponse = request.GetResponse();
Stream webStream = webResponse.GetResponseStream();
StreamReader responseReader = new StreamReader(webStream);
string response = responseReader.ReadToEnd();
responseReader.Close();
Console.WriteLine(response);
Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex);
Console.ReadLine();
}
}
in the end console writes this exception:
System.Net.ProtocolViolationException: Cannot send a content-body with
this verb-type.
can someone help?

Login into iCloud via Json Post request

I'm trying to log in into iCloud using a Json Post request in C#. Before trying to implement the code I was studying a little bit the iCloud requests using Chrome Console and using an Ad-on to replicate the requests in order to obtain the same result of the website.
First of All I checked the request directly from iCloud website:
And this is the response:
{
"serviceErrors" : [ {
"code" : "-20101",
"message" : "Il tuo IDĀ Apple o la password non sono corretti."
} ]
}
Using "Advance REST Client" ad Chrome plugin to replicate the request I ve tried the same Json request to the same Url. But I get Empty response:
I Also tried to copy and paste the whole Header (All the settings) and than send the request but the response is the same:
Anyone has an Advice?
UPDATE: I tried to implement A Json request through c# program:
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{accountName: \"briesanji #gmail.com\", password: \"testPassword\", rememberMe: false, trustTokens: []}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
The problem is that Execution breaks when the
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
is hit and it gives me this error: System.Net.WebException: 'Error Remote Server: (400) Request not valid.'
UPDATE: I solved in this way:
void POST(string url, string jsonContent)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
Byte[] byteArray = encoding.GetBytes(jsonContent);
request.ContentLength = byteArray.Length;
request.ContentType = #"application/json";
using (Stream dataStream = request.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
}
long length = 0;
try
{
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
length = response.ContentLength;
}
}
catch (WebException ex)
{
// Log exception and throw as for GET example above
}
}
string GET(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
try
{
WebResponse response = request.GetResponse();
using (Stream responseStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
return reader.ReadToEnd();
}
}
catch (WebException ex)
{
WebResponse errorResponse = ex.Response;
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
String errorText = reader.ReadToEnd();
// log errorText
}
throw;
}
}
Anyways I tested also the Answer and it was good to.. So I check it as valid thanks.
With this i dont get any error and the response content of the second request just tells me that there were too many failed logins for the test account...
private static void ICloud()
{
var cc = new CookieContainer();
var first = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf");
first.Method = "GET";
first.CookieContainer = cc;
var response1 = (HttpWebResponse)first.GetResponse();
using (var streamReader = new StreamReader(response1.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
var second = (HttpWebRequest)WebRequest.Create("https://idmsa.apple.com/appleauth/auth/signin");
second.ContentType = "application/json";
second.Method = "POST";
second.Accept = "application/json";
second.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
second.Referrer = "https://idmsa.apple.com/appleauth/auth/signin?widgetKey=83545bf919730e51dbfba24e7e8a78d2&locale=de_DE&font=sf";
second.Headers.Add("X-Requested-With", "XMLHttpRequest");
second.Headers.Add("X-Apple-Widget-Key", "83545bf919730e51dbfba24e7e8a78d2");
using (var streamWriter = new StreamWriter(second.GetRequestStream()))
{
string json = "{\"accountName\":\"test#icloud.com\",\"password\":\"test\",\"rememberMe\":false,\"trustTokens\":[]}";
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
try
{
var response2 = (HttpWebResponse)second.GetResponse();
using (var streamReader = new StreamReader(response2.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch(WebException we)
{
using (var r = new StreamReader(we.Response.GetResponseStream()))
{
var result2 = r.ReadToEnd();
}
}
}

C# JSON Post using HttpWebRequest

I am new to JSON and C# and trying to write a code that will perform an http web request POST to get a token. Below is my code but I keep getting 400 bad request. Probably my codes just incorrect and I will appreciate for any helps on this. Below is my codes :
static public string GetAuthorizationToken()
{
string token = string.Empty;
string requestUrl = "some URL";
HttpWebRequest httpWebRequest = WebRequest.Create(requestUrl) as HttpWebRequest;
httpWebRequest.Method = "POST";
httpWebRequest.ContentType = "x-www-form-urlencoded";
Dictionary<string, string> postParameters = new Dictionary<string, string>();
postParameters.Add("grant", "some credentials");
postParameters.Add("id", "1234123411");
postParameters.Add("secret", "1234123411");
postParameters.Add("scope", "abcd");
string postData = "";
foreach (string key in postParameters.Keys)
{
postData += WebUtility.UrlEncode(key) + "="
+ WebUtility.UrlEncode(postParameters[key]) + "&";
}
byte[] data = Encoding.ASCII.GetBytes(postData);
httpWebRequest.ContentLength = data.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
requestStream.Write(data, 0, data.Length);
requestStream.Close();
TokenResponse tokenResponse = new TokenResponse();
using (HttpWebResponse response = httpWebRequest.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer responseSerializer = new DataContractJsonSerializer(typeof(TokenResponse));
Stream responseStream = response.GetResponseStream();
object objResponse = responseSerializer.ReadObject(responseStream);
tokenResponse = objResponse as TokenResponse;
response.Close();
if (tokenResponse != null)
{
return tokenResponse.accessToken;
}
}
return token;
}
Here is a precise and accurate example of a POST request and reading the response(though without serializing the JSON data). Only mistake I see so far in your code is an incorrect ContentType also we can't see what url you are trying to send the server(but odds are that it is incorrect). Hope it helps you advance.
using System;
using System.Collections.Generic;
using System.Net;
using System.IO;
namespace SExperiment
{
class MainClass
{
public static void Main(string[] args)
{
try{
string webAddr="http://gurujsonrpc.appspot.com/guru";
var httpWebRequest = WebRequest.CreateHttp(webAddr);
httpWebRequest.ContentType = "application/json; charset=utf-8";
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = "{ \"method\" : \"guru.test\", \"params\" : [ \"Guru\" ], \"id\" : 123 }";
streamWriter.Write(json);
streamWriter.Flush();
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.WriteLine(responseText);
//Now you have your response.
//or false depending on information in the response
}
}catch(WebException ex){
Console.WriteLine(ex.Message);
}
}
}
}
You have set requestUrl to "some URL". Please try with a web address that exists, in addition to changing the content type to "application/json".

oauth/token returns empty body

I am encountering a problem getting the access_token in client application using oauth.
The returned response has empty body though in API I can see the response is not empty.
tokenresponse = {
"access_token":"[ACCESSTOKENVALUE]",
"token_type":"bearer",
"expires_in":"1200",
"refresh_token":"[REFRESHTOKENVALUE]",
"scope":"[SCOPEVALUE]"
}
The method from API that returns the token http://api.sample.com/OAuth/Token:
public ActionResult Token()
{
OutgoingWebResponse response =
this.AuthorizationServer.HandleTokenRequest(this.Request);
string tokenresponse = string.Format("Token({0})", response!=null?response.Body:""));
return response.AsActionResult();
}
The client method that requests the token is:
public string GetAuthorizationToken(string code)
{
string Url = ServerPath + "OAuth/Token";
string redirect_uri_encode = UrlEncode(ClientPath);
string param = string.Format("code={0}&client_id={1}&client_secret={2}&redirect_uri={3}&grant_type=authorization_code",code, ClientId, ClientSecret, redirect_uri_encode);
HttpWebRequest request = HttpWebRequest.Create(Url) as HttpWebRequest;
string result = null;
request.Method = "POST";
request.KeepAlive = true;
request.ContentType = "application/x-www-form-urlencoded";
request.Timeout = 10000;
request.Headers.Remove(HttpRequestHeader.Cookie);
var bs = Encoding.UTF8.GetBytes(param);
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(bs, 0, bs.Length);
}
using (WebResponse response = request.GetResponse())
{
var sr = new StreamReader(response.GetResponseStream());
result = sr.ReadToEnd();
sr.Close();
}
if (!string.IsNullOrEmpty(result))
{
TokenData tokendata = JsonConvert.DeserializeObject<TokenData>(result);
return UpdateAuthorizotionFromToken(tokendata);
}
return null;
}
The result variable is empty.
Please let me know if you have any idea what could cause this. Initially I assumed is because of the cookies so I tried to remove them from request.
Thanks in advance.
Dear just create webclient using following code and you will get json info in tokeninfo.I used it and simply its working perfect.
WebClient client = new WebClient();
string postData = "client_id=" + ""
+ "&client_secret=" + ""
+ "&grant_type=password&username=" + "" //your username
+ "&password=" + "";//your password :)
string soundCloudTokenRes = "https://api.soundcloud.com/oauth2/token";
string tokenInfo = client.UploadString(soundCloudTokenRes, postData);
You can then use substring that contains only token from tokeninfo.
To upload tracks on sound cloud.
private void TestSoundCloudupload()
{
System.Net.ServicePointManager.Expect100Continue = false;
var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
//some default headers
request.Accept = "*/*";
request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
//file array
var files = new UploadFile[] { new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") };
//other form data
var form = new NameValueCollection();
form.Add("track[title]", "Some title");
form.Add("track[sharing]", "public");
form.Add("oauth_token", "");
form.Add("format", "json");
form.Add("Filename", "0.mp3");
form.Add("Upload", "Submit Query");
try
{
using (var response = HttpUploadHelper.Upload(request, files, form))
{
using (var reader = new StreamReader(response.GetResponseStream()))
{
Response.Write(reader.ReadToEnd());
}
}
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

Uploading a file to a web service using POST in C#

The problem with this code is that the file, once it is uploaded, is not the correct format. I'm trying to upload a .zip file.
public string HttpPost(string uri, string parameter)
{
WebRequest webRequest = WebRequest.Create(uri);
NetworkCredential credentials = new NetworkCredential("username", "password");
webRequest.Credentials = credentials;
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameter);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
if (webResponse == null)
{ return null; }
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
return sr.ReadToEnd().Trim();
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error",
MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return null;
}
This example how to upload file in MyBucket
private const string KeyId = "Your KeyId";
private const string AccessKey = "Your AccessKey";
private const string S3Url = "https://s3.amazonaws.com/";
private static void UploadFile()
{
var fileData = File.ReadAllBytes(#"C:\123.zip");
string timeStamp = string.Format("{0:r}", DateTime.UtcNow);
string stringToConvert = "PUT\n" + //Http verb
"\n" + //content-md5
"application/octet-stream\n" + //content-type
"\n" + //date
"x-amz-acl:public-read"+"\n" + //date
"x-amz-date:" + timeStamp + "\n" + //optionall
"/MyBucket/123.zip"; //resource
var ae = new UTF8Encoding();
var signature = new HMACSHA1 {Key = ae.GetBytes(AccessKey)};
var bytes = ae.GetBytes(stringToConvert);
var moreBytes = signature.ComputeHash(bytes);
var encodedCanonical = Convert.ToBase64String(moreBytes);
var url = "https://MyBucket.s3.amazonaws.com/123.zip";
var request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "PUT";
request.Headers["x-amz-date"] = timeStamp;
request.Headers["x-amz-acl"] = "public-read";
request.ContentType = "application/octet-stream";
request.ContentLength = fileData.Length;
request.Headers["Authorization"] = "AWS " + KeyId + ":" + encodedCanonical;
var requestStream = request.GetRequestStream();
requestStream.Write(fileData, 0, fileData.Length);
requestStream.Close();
using (var response = request.GetResponse() as HttpWebResponse)
{
var reader = new StreamReader(response.GetResponseStream());
var data = reader.ReadToEnd();
}
}
Take a look on Amazon S3 REST API

Categories