Using Twitter login API - api

I am trying to use https://api.periscope.tv/api/v2/loginTwitter to get a response from the server so that I can obtain a cookie for periscope API calls.
I have all of the required values for the request query, but I continue to get the "Bad Request" error (error code 400). Is anyone able to use the loginTwitter API still?
Request headers:
POST /api/v2/loginTwitter?bundle_id=com.bountylabs.periscope&phone_number=&session_key=xxxxxxxx&session_secret=xxxxxxxx&user_id=xxxxxxxx&user_name=xxxxxxxx&vendor_id=81EA8A9B-2950-40CD-9365-40535404DDE4 HTTP/1.1
Authorization:
OAuth oauth_consumer_key="xxxxxxxx",oauth_nonce="cecf203cda273c845cd5121007232666",oauth_signature="xxxxxxxx%3D",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1474786616",oauth_token="xxxxxxxx",oauth_version="1.0"
Oauth signature:
POST&https%3A%2F%2Fapi.periscope.tv%2Fapi%2Fv2%2FloginTwitter%3Fbundle_id%3Dcom.bountylabs.periscope%26phone_number%3D%26session_key%xxxxxxxx%26session_secret%3xxxxxxxx%26user_id%3xxxxxxxx%26user_name%xxxxxxxx%26vendor_id%3D81EA8A9B-2950-40CD-9365-40535404DDE4&bundle_id%3Dcom.bountylabs.periscope%26oauth_consumer_key%3xxxxxxxx%26oauth_nonce%3Dcecf203cda273c845cd5121007232666%26oauth_signature_method%3DHMAC-SHA1%26oauth_timestamp%3D1474786616%26oauth_token%xxxxxxxx%26oauth_version%3D1.0%26phone_number%3D%26session_key%xxxxxxxxMX%26session_secret%xxxxxxxxt%26user_id%xxxxxxxx4%26user_name%xxxxxxxx%26vendor_id%3D81EA8A9B-2950-40CD-9365-40535404DDE4

I have solved the problem thanks to help from another. The problem was that I was passing the request parameters in the URL without encoding them into json. For any that are looking to resolve this problem, here is the solution I arrived at with c#.
var httpWebRequest = ( HttpWebRequest )WebRequest.Create( "https://api.periscope.tv/api/v2/loginTwitter" );
httpWebRequest.ContentType = "application/json; charset=UTF-8";
httpWebRequest.Method = "POST";
using( var streamWriter = new StreamWriter( httpWebRequest.GetRequestStream() ) ){
string json = "{" +
"\"bundle_id\":\"com.bountylabs.periscope\"," +
"\"phone_number\":\"\"," +
"\"session_key\":\""+final_oauth_token+"\"," +
"\"session_secret\":\""+final_oauth_token_secret+"\"," +
"\"user_id\":\""+user_id+"\"," +
"\"user_name\":\""+screen_name+"\"," +
"\"vendor_id\":\"81EA8A9B-2950-40CD-9365-40535404DDE4\"" +
"}";
streamWriter.Write( json );
streamWriter.Flush();
streamWriter.Close();
}
var httpResponse = ( HttpWebResponse )httpWebRequest.GetResponse();
using( var streamReader = new StreamReader( httpResponse.GetResponseStream() ) ){
var result = streamReader.ReadToEnd();
display.Text = "cookie: "+result;
}
}
The result yields a cookie in the server's response.
Reference for more detail on this process: Twitter login POST request in Periscope API

Related

Getting (401) UnAuthorized error on some requests not all, but most

I don't think this is a code issue, but we have a list of hundreds of addresses to process. Some return data and we are able to get Long and Lat but most return (401) UnAuthorized errors. What would cause this to happen? We have tried passing Host Headers and everything else, the REST API seems to work better in our development environment but throws way more errors when deployed to our Job Server. Any help on this issue will be greatly appreciated. We would like to understand why some calls work and others don't, we pass the same apiKey each time so this is really confusing. Thanks
Here is a code snippet using c# (Work in progress):
//GET THE LATITUDE AND LONGITUDE BASED OFF THE PHYSICAL ADDRESS
String clientAddress = clientRow["home_address"].ToString() + ", " + clientRow["home_city"].ToString() + ", " + clientRow["home_state"].ToString() + ", " + clientRow["home_zip"].ToString();
Logger.Debug("CLIENT ADDRESS: {0}", clientAddress);
String geocoderUri = "https://geocode.search.hereapi.com/v1/geocode?q=" + clientAddress + "&apiKey=xxxxxxxxxxxxxxxxxxxxx"; //KEY REMOVED FOR POSTING ON STACK OVERFLOW
var syncClient = new WebClient();
var content = syncClient.DownloadString(geocoderUri);
//CREATE THE JSON SERIALIZER AND PARSE OUR RESPONSE
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(AddressData));
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(content)))
{
var addressData = (AddressData)serializer.ReadObject(ms);
if (addressData.items.Count() > 0)
{
//INSERT THE LATITUDE AND LONGITUDE IN DB
String sLat = addressData.items[0].position.lat.ToString();
String sLong = addressData.items[0].position.lng.ToString();
Logger.Debug("CLIENT GEOLOCATION - Longitude: {0} Latitude: {1}", sLong, sLat);
insertLatLong(sLat, sLong, clientRow["clientID"].ToString(), 1);
}
}
Would you please try to use RestSharp lib for rest api?
Please see below sample code.
var client = new RestClient("https://geocode.search.hereapi.com/v1/geocode?q="+ clientAddress);
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Authorization", "Bearer YOUR TOKEN");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

c# console application returning no results

This code runs fine in my windows form application using .net framework 4.6.2 but when I go to make it a console application so it can be ran from the task scheduler I get no results. I think I am losing something in translation.
RestClient restClient = new RestClient("https://api.vault.com");
string refreshToken = #"abc";
string encodedClientIdSecret = Base64Encode("AP-123");
string responseStr = "";
string url = "/v1/OAuth";
dynamic jsonObj = "";
RestRequest request = new RestRequest(url, Method.POST);
request.AddHeader("Authorization", encodedClientIdSecret);
request.AddParameter("grant_type", "refresh_token");
request.AddParameter("refresh_token", refreshToken);
IRestResponse response;
restClient.Execute(request);
response = restClient.Execute(request);
Console.WriteLine(response.Content + " || " + encodedClientIdSecret);
Console.ReadKey();
jsonObj = JsonConvert.DeserializeObject(response.Content);
responseStr = jsonObj.access_token;
return responseStr;
It basically tells me the value cannot be null, and when I look at response.Content I get nothing and the status code comes back as "0". Any thoughts?
Just added:
//Required For SSL/TLS Error Start
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
//Required For SSL/TLS Error End
and I got my results. Hope this helps someone else!

C# "The request was aborted: Could not create SSL/TLS secure channel." - happening occasionally

This is a request to GoCardless test API from a Dynamics CRM plugin. I receive "The request was aborted: Could not create SSL/TLS secure channel." error. It only happens on the first request after some time without sending one. If I send it again, it will be OK. I would appreciate a lot your help.
Here is my code:
//I have tried all the following lines in comment without success
//ServicePointManager.ServerCertificateValidationCallback += ValidateRemoteCertificate;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
//ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
//ServicePointManager.Expect100Continue = true;
//ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
// Create a new WebClient instance.
string baseURL = "https://api-sandbox.gocardless.com/";
WebClient client = new WebClient();
client.Headers.Add("Content-Type", "application/json");
client.Headers.Add("Authorization", "Bearer " + t);
client.Headers.Add("GoCardless-Version", "2015-07-06");
client.Headers.Add("Accept", "application/json");
Customers model = new Customers();
customer.country_code = "GB";
model.customers = customer;
MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Customers));
ser.WriteObject(stream1, model);
stream1.Position = 0;
StreamReader sr = new StreamReader(stream1);
// Apply ASCII Encoding to obtain the string as a byte array.
byte[] byteArray = Encoding.ASCII.GetBytes(sr.ReadToEnd());
ReturnedCustomers result = new ReturnedCustomers();
//Upload the input string using the HTTP 1.0 POST method.
try
{
byte[] responseArray = client.UploadData(baseURL + "customers", "POST", byteArray);
string responseText = Encoding.ASCII.GetString(responseArray);
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(ReturnedCustomers));
using (Stream s = GenerateStreamFromString(responseText))
{
result = (ReturnedCustomers)serializer.ReadObject(s);
}
}
catch (WebException exception)
{
}
From the Microsoft documentation (https://msdn.microsoft.com/en-us/library/gg334752.aspx) are the following limitations:
Only the HTTP and HTTPS protocols are allowed.
Access to localhost (loopback) is not permitted.
IP addresses cannot be used. You must use a named web address that requires DNS name resolution.
Anonymous authentication is supported and recommended.
5.There is no provision for prompting the logged on user for credentials or saving those credentials.
The error may be due to seguneti things:
The certificate is invalid
The certification authority is not public
Could you check what is the value of ServicePointManager.Expect100Continue and ServicePointManager.SecurityProtocol attributes in your environment?

How do I add just a username within an authentication header in stripe-payments?

I'm trying to get a simple post request to work to create a customer via the Stripe.js API.
https://stripe.com/docs/api/java#authentication
I'm doing this in vb.net and don't want to use the stripe.net library.
I keep getting authorization failed. All I have to pass is the username in the header, or in this case the username is my test api key.
Here's a chunk of the code:
Dim asPostRequest As HttpWebRequest = WebRequest.Create(String.Format(ApiEndpoint))
Dim as_ByteArray As Byte() = Encoding.UTF8.GetBytes(stripeccw.ToString)
asPostRequest.Method = "POST"
asPostRequest.ContentType = "application/json"
'asPostRequest.Headers("Authorization") = "Basic" + apikey
'asPostRequest.Credentials("bearer", apikey)
'asPostRequest.Headers.Add("Authorization") = apikey
'asPostRequest.Credentials("Username") = apikey
'asPostRequest.Credentials = New NetworkCredential(apikey, "")
asPostRequest.ContentLength = as_ByteArray.Length
Dim as_DataStream As Stream = asPostRequest.GetRequestStream()
as_DataStream.Write(as_ByteArray, 0, as_ByteArray.Length)
as_DataStream.Close()
Where I've commented out... those are different ways that I've tried. I know some are just stupid attempts, but just getting frustrated. I know for a fact my api key is correct. I can verify this by navigating to https://api.stripe.com/v1/customers and entering it in for my username only.
Hoping someone can spot something simple :)
Thank you!
If I were in your shoes, the first thing I'd do is take a look at how Stripe.Net does it. Even if you don't want to use that library yourself, that doesn't mean you can't use the source code as a reference.
From Requestor.cs:
internal static WebRequest GetWebRequest(string url, string method, string apiKey = null, bool useBearer = false)
{
apiKey = apiKey ?? StripeConfiguration.GetApiKey();
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
if(!useBearer)
request.Headers.Add("Authorization", GetAuthorizationHeaderValue(apiKey));
else
request.Headers.Add("Authorization", GetAuthorizationHeaderValueBearer(apiKey));
request.Headers.Add("Stripe-Version", StripeConfiguration.ApiVersion);
request.ContentType = "application/x-www-form-urlencoded";
request.UserAgent = "Stripe.net (https://github.com/jaymedavis/stripe.net)";
return request;
}
private static string GetAuthorizationHeaderValue(string apiKey)
{
var token = Convert.ToBase64String(Encoding.UTF8.GetBytes(string.Format("{0}:", apiKey)));
return string.Format("Basic {0}", token);
}
private static string GetAuthorizationHeaderValueBearer(string apiKey)
{
return string.Format("Bearer {0}", apiKey);
}
So it seems there are two ways to do it. You can either use "Bearer" format, which is:
asPostRequest.Headers.Add("Authorization", "Bearer " & apiKey)
or you can use "Basic" format which is:
asPostRequest.Headers.Add("Authorization", _
"Basic " & Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey & ":")))

SMS integration web api consume by XML via HTTP RAW POST in c#.net

I need to integrate send sms api using like this URL. but I am getting the message XML is incorrect format.
http://<url>/action?application=msg&action=sendmsg&responsetype=xml
I am sending XML code like this
<data>
<phone> 1234567890 </phone>
<api_key 1234567890 </api_key>
<message_body> This is message text </message_body>
</data>
My code is
HttpWebRequest httpWReq =
(HttpWebRequest)WebRequest.Create(#"http:\\domain.com\page.asp");
ASCIIEncoding encoding = new ASCIIEncoding();
string postData = "username=user";
postData += "&password=pass";
byte[] data = encoding.GetBytes(postData);
httpWReq.Method = "POST";
httpWReq.ContentType = "application/x-www-form-urlencoded";
httpWReq.ContentLength = data.Length;
using (Stream stream = httpWReq.GetRequestStream())
{
stream.Write(data,0,data.Length);
}
HttpWebResponse response = (HttpWebResponse)HttpWReq.GetResponse();
string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Please suggest how to resolve.strong text
Looks like just a typo.
Add > to end of the front api_key and the balance XML needs will work.