How to get reviews from Trustpilot API - c#

Attempting to get Trustpilot reviews from a specific product but cannot get anywhere.
Can get the token with success but then the reviews:
Querying https://api.trustpilot.com/v1/private/product-reviews/business-units/{businessUnitId}/reviews would return no results at all but runs without error
AND
Querying https://api.trustpilot.com/v1/product-reviews/business-units/{businessUnitId}/reviews would return an error "Microsoft.VisualStudio.Services.OAuth.AccessTokenResponseProduct review retrieved.{"fault":{"faultstring":"Invalid ApiKey","detail":{"errorcode":"oauth.v2.InvalidApiKey"}}}"
The ApiKey is the same to get the token so do not understand why does not work here. In a desperate attempt added the token to the url (?token={token}) and also not successful.
The sku collection includes all variants. Also tried without sku parameter and nothing is retrieved.
Here is the code:
var ApiKey = "ApiKey";
var SecretKey = "SecretKey";
var Username = "Username";
var Password = "Password";
var serverUrl = "xxx.xxx.xxx.xxx";
var BusinnessUnit = "BusinnessUnit";
var AuthUrl2 = "https://api.trustpilot.com/v1/oauth/oauth-business-users-for-applications/accesstoken";
var ReviewUrl = "https://api.trustpilot.com/v1/private/product-reviews/business-units/"+ bkBusinnessUnit + "/reviews";
var ProductReviewUrl = "https://api.trustpilot.com/v1/product-reviews/business-units/" + bkBusinnessUnit + "/reviews";
var token = "";
// get token
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(AuthUrl2);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = ApiKey + ":" + SecretKey;
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedStr);
var stringPayload = "grant_type=password&username=" + Username + "&password=" + Password;
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(AuthUrl2, httpContent).Result;
var accessTokenResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var accessTokenResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(accessTokenResponseString);
token = accessTokenResponseObject.AccessToken;
Console.WriteLine("Token retrieved. " + token);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}
// get product reviews
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(ProductReviewUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
var authString = ApiKey + ":" + SecretKey;
string encodedStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(authString));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", encodedStr);
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18&token=" + token;
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(ProductReviewUrl, httpContent).Result;
var reviewResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var reviewResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(reviewResponseString);
Console.WriteLine(reviewResponseObject + "Product review retrieved." + reviewResponseString);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}
// get reviews
using (var httpClient = new HttpClient())
{
try
{
httpClient.BaseAddress = new Uri(ReviewUrl);
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18";
var httpContent = new StringContent(stringPayload, Encoding.UTF8, "application/x-www-form-urlencoded");
HttpResponseMessage httpResponseMessage = httpClient.PostAsync(ReviewUrl, httpContent).Result;
var reviewResponseString = httpResponseMessage.Content.ReadAsStringAsync().Result;
var reviewResponseObject = JsonConvert.DeserializeObject<AccessTokenResponse>(reviewResponseString);
Console.WriteLine(reviewResponseObject + "Review retrieved." + reviewResponseString);
}
catch (Exception ex)
{
Console.WriteLine("Failed!" + ex.ToString());
}
}

/v1/private/product-reviews/business-units/{businessUnitId}/reviews endpoint requires token. It could be provided either via header or via query parameters. It works for you as you did it right.
/v1/product-reviews/business-units/{businessUnitId}/reviews endpoint only requires apikey. You could pass it in two ways:
via header
httpClient.DefaultRequestHeaders.Accept.Add("apikey", ApiKey);
via query parameters
var stringPayload = "sku=SK40132-BLK-6,SK40132-BLK-8,SK40132-BLK-10,SK40132-BLK-12,SK40132-BLK-14,SK40132-BLK-16,SK40132-BLK-18&apikey=" + ApiKey;

It was incredible simple it should be a GetAsync instead of a PostAsync.
Thanks anyway for looking at it.

Related

Posting JSON to REST Service

I am attempting to consume a Data source from Plex a cloud ERP System with Rest. I am receiving a forbidden status code upon sending the PUT
public static string Put(string url,string Body,PCNModel pcn)
{
HttpClient client = new HttpClient();
int timeOutSec = 90;
string accept = "application/json";
string acceptEncoding = "gzip, deflate";
string contentType = "application/json";
var credentials = pcn.UserName + ":" + pcn.Password;
var bytes = Encoding.UTF8.GetBytes(credentials);
var encodedCredentials = Convert.ToBase64String(bytes);
var authorizationHeaderValue = encodedCredentials;
HttpResponseMessage response = new HttpResponseMessage();
client.Timeout = new TimeSpan(0, 0, timeOutSec);
//client.DefaultRequestHeaders.Add("Accept", string.Format(accept));
client.DefaultRequestHeaders.Add("Accept", (accept));
client.DefaultRequestHeaders.Add("Accept-Encoding", string.Format(acceptEncoding));
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(contentType));
client.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", authorizationHeaderValue));
HttpContent httpBody = Body;
httpBody.Headers.ContentType = new MediaTypeHeaderValue(contentType);
response = client.PutAsync(url, httpBody).Result;
var error = response.StatusCode.ToString();
var requestMessage = response.RequestMessage;
var responseContent = response.Content;
var responseReasonPhrase = response.ReasonPhrase;
var responseHeader = response.Headers;
MessageBox.Show(error);
MessageBox.Show(requestMessage.ToString());
//MessageBox.Show(responseContent.ToString());
//MessageBox.Show(responseReasonPhrase.ToString());
//MessageBox.Show(responseHeader.ToString());
var content = response.Content.ReadAsStringAsync().Result;
return content;
}
I am not sure where it is bouncing back at me.
You need to parse body to json before calling PutAsync here is a small code sinppet
client.DefaultRequestHeaders.Add("authKey", authKey);
var json = JsonConvert.SerializeObject(product, Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var content = new StringContent(json, Encoding.UTF8, "application/json");
var response = await client.PutAsync(url, content);
if (response.IsSuccessStatusCode)
{
}
else
{
var result = response.Content.ReadAsStringAsync().Result;
throw new Exception("Error Occured in Update Product" + result);
}
It turns out that the credentials I was provided were incorrect. Which prevented me from processing web services calls to the endpoint.

200 status using refresh token

public async Task NewMethodAsync()
{
try
{
HttpClient objClient = new HttpClient();
Uri requestUri = new Uri("https://approvalbotbeta.azurewebsites.net/api/token");
Dictionary<string, string> pairs = new Dictionary<string, string>();
var client_ID = "<CLIENT ID>";
var client_secret = "<SECRET KEY STRING>";
pairs.Add("grant_type", "client_credentials");
pairs.Add("reply_url", "http://localhost");
FormUrlEncodedContent httpContent = new FormUrlEncodedContent(pairs);
var encordedString = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(client_ID + ":" + client_secret));
objClient.DefaultRequestHeaders.Add("Authorization", "Basic " + encordedString);
HttpResponseMessage respon = await objClient.PostAsync("https://approvalbotbeta.azurewebsites.net/api/token", httpContent);
if (respon.IsSuccessStatusCode)
{
Console.WriteLine(respon.Content.ReadAsStringAsync().Result);
var ww = respon.Content.ReadAsStringAsync().Result;
var response = JsonConvert.DeserializeObject<Response>(ww);
Console.WriteLine(response.access_token);
var acc_tkn = response.access_token;
// Uri requesturi = new Uri("https://approvalbotbeta.azurewebsites.net/api/send");
// Dictionary<string, string> pairs2 = new Dictionary<string, string>();
// pairs2.Add("Content-Type", "application/json");
// FormUrlEncodedContent httpContent2 = new FormUrlEncodedContent(pairs2);
// objClient.DefaultRequestHeaders.Add("Authorization", "Bearer",+ acc_tkn);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I coded this for getting access token, and got it. Now I want to get 200 status using this token and my URL. So what are the coding lines?
respon.StatusCode will get you 200.
If you mean that using this token you want to retrieve data from your API, use this:
using (var client = new HttpClient())
{
var url = "https://approvalbotbeta.azurewebsites.net/api/GetSomething";
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + acc_tkn);
var response = await client.GetStringAsync(url);
// Parse JSON/XML response.
}
GetSomething is the method you want to call.
acc_tkn you got in your posted code.

How to set contributor role after creating a new azure subscription?

I've created a new subscription using the microsoft CREST API with the following code:
WebClient client = new WebClient();
SATokenFormatReseller SA_Token = GetSAResellerToken();
client.Headers[HttpRequestHeader.Accept] = "application/json";
client.Headers[HttpRequestHeader.Authorization] = "Bearer " + SA_Token.access_token;
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.Headers.Add("api-version", ApiVersion);
client.Headers.Add("x-ms-correlation-id", Guid.NewGuid().ToString());
client.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
var reqOrderObj = CreateReqOrderObject(service, mpn);
var reqOrderJson = JsonConvert.SerializeObject(reqOrderObj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
string res = client.UploadString("https://api.cp.microsoft.com/" + TenantId + "/orders", "POST", reqOrderJson);
after creating successfully the subscription, I'm trying to set contributor role for the new subscription using the management azure core api, in this way:
public bool CreateRoleAssignment(string subscriptionId, string tenantId, string principalId)
{
bool roleGranted = false;
var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
string responseContent = String.Empty;
var roleAssignmentId = Guid.NewGuid().ToString();
var correlationId = Guid.NewGuid().ToString();
var request = (HttpWebRequest)HttpWebRequest.Create(string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId));
request.Method = "PUT";
request.Accept = "application/json";
request.ContentType = "application/json";
request.Headers.Add("x-ms-correlation-id", correlationId);
request.Headers.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
request.Headers.Add("Authorization", "Bearer " + azureToken.AccessToken);
string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));
using (var writer = new StreamWriter(request.GetRequestStream()))
{
writer.Write(content);
}
try
{
var response = request.GetResponse();
using (var reader = new StreamReader(response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
roleGranted = true;
}
}
catch (WebException webException)
{
using (var reader = new StreamReader(webException.Response.GetResponseStream()))
{
responseContent = reader.ReadToEnd();
roleGranted = false;
}
}
return roleGranted;
}
but the response is that the subscription does not exist.
After some time, if I run the same piece of code (CreateRoleAssignment), the role is given succesfully to the subscription.
How could I achive this process after creating the subscription?
As #GauravMantri said, using async polling as the sample code below.
var azureToken = GetAzureAuthTokenForCustomerTenant(NativeClientId, PartnerCenterUser, PartnerCenterPassword, tenantId);
string responseContent = String.Empty;
var roleAssignmentId = Guid.NewGuid().ToString();
var correlationId = Guid.NewGuid().ToString();
string url = string.Format("https://management.azure.com/subscriptions/{0}/providers/Microsoft.Authorization/roleAssignments/{1}?api-version=2015-07-01", subscriptionId, roleAssignmentId);
string content = Json.Encode(CreateRoleAssignmentRequestData(subscriptionId, principalId));
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Add("Accept", "application/json");
client.DefaultRequestHeaders.Add("Content-Type", "application/json");
client.DefaultRequestHeaders.Add("x-ms-correlation-id", correlationId);
client.DefaultRequestHeaders.Add("x-ms-tracking-id", Guid.NewGuid().ToString());
client.DefaultRequestHeaders.Add("Authorization", "Bearer " + azureToken.AccessToken);
var response = await client.PutAsync(url, content);
while(!response.IsSuccessStatusCode)
{
response = await client.PutAsync(url, content);
}
Console.WriteLine(response.Content.ReadAsStringAsync().Result);
}

Twitter API invalid or expired token

I'm trying to use the below code but for some reason I'm getting an invalid or expired token it seemed to work once but never again.
Any ideas? (consumerKey and consumerSecret are constants generated in the class.)
public ActionResult Index()
{
string twitterAccount = System.Configuration.ConfigurationManager.AppSettings["twitterAccount"];
JsonDeserializer jsonDeserializer = new JsonDeserializer();
var model = new TwitterVM.LandingModel();
var qs = GetToken();
string oauthToken = qs["oauth_token"];
string oauthTokenSecret = qs["oauth_token_secret"];
RestClient client = new RestClient("https://api.twitter.com/1.1")
{
Authenticator = OAuth1Authenticator.ForProtectedResource(consumerKey, consumerSecret, oauthToken, oauthTokenSecret)
};
RestRequest request = new RestRequest("statuses/user_timeline", Method.GET);
request.Parameters.Add(new Parameter()
{
Name = "screen_name",
Value = twitterAccount,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "count",
Value = 10,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_rts",
Value = true,
Type = ParameterType.GetOrPost
});
request.Parameters.Add(new Parameter()
{
Name = "include_entities",
Value = true,
Type = ParameterType.GetOrPost
});
IRestResponse response = client.Execute(request);
model.Tweets =
jsonDeserializer.Deserialize<List<TwitterVM.Tweet>>(response);
return View(model);
}
private NameValueCollection GetToken()
{
RestClient client = new RestClient("https://api.twitter.com") { Authenticator = OAuth1Authenticator.ForRequestToken(consumerKey, consumerSecret) };
//Do the auth shit...
RestRequest request = new RestRequest("oauth/request_token", Method.POST);
IRestResponse response = client.Execute(request);
return HttpUtility.ParseQueryString(response.Content);
}
Using Twitter's OAuth2 API (https://api.twitter.com/oauth2/token)
See https://dev.twitter.com/oauth/application-only for details....
var client = await CreateHttpClient("....", "....");
//don't dispose this client and use for subsequent API calls
var screenName = "....";
var count = 10;
var include_rts = true;
var url = $"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name={screenName}&include_rts={include_rts}&count={count}";
var json = await client.GetStringAsync(url);
public static async Task<HttpClient> CreateHttpClient(string consumerKey, string consumerSecret)
{
var bearerToken = Convert.ToBase64String(Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret));
string url = "https://api.twitter.com/oauth2/token";
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Basic " + bearerToken);
var resp = await client.PostAsync(url, new StringContent("grant_type=client_credentials", Encoding.UTF8, "application/x-www-form-urlencoded")).ConfigureAwait(false);
resp.EnsureSuccessStatusCode();
var result = await resp.Content.ReadAsStringAsync().ConfigureAwait(false);
var jObj = new JavaScriptSerializer().Deserialize<Dictionary<string,string>>(result);
if (jObj["token_type"] != "bearer") throw new Exception("Invalid Response From Twitter/OAuth");
client.DefaultRequestHeaders.Remove("Authorization");
client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", "Bearer " + jObj["access_token"]);
return client;
}

Using a token to search on Twitter with OAuth2

Before Twitter switched to OAuth2, I was using the following query:
string atomTweetSearchURL = string.Format("http://search.twitter.com/search.atom?q={0}", searchText);
This no longer works, so now I'm trying to switch to OAuth2. I manage to successfully retrieve a token, but once I've got this, I seem to be unable to actually perform the search. Here's the latest incarnation of what I've tried:
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}&access_token={1}&token_type={2}", srchStr, twitAuthResponse.access_token, twitAuthResponse.token_type);
WebRequest srchRequest = WebRequest.Create(searchUrl);
using (var response2 = await srchRequest.GetResponseAsync())
{
Stream stream = response2.GetResponseStream();
using (StreamReader sr = new StreamReader(stream))
{
string jsonResponse = await sr.ReadToEndAsync();
}
}
This gives me a 400 - bad request.
I've also tried building the request like this:
System.Net.Http.HttpClient srchRequest = new System.Net.Http.HttpClient();
string authHdr = string.Format(srchHeaderFormat, twitAuthResponse.token_type, twitAuthResponse.access_token);
srchRequest.DefaultRequestHeaders.Add("Authorization", authHdr);
There's a massive quantity of articles out there detailing how to do this, but none of them seem to work correctly with WinRT. Can anyone point me in the right direction?
EDIT
Here's my code to get the token:
var oAuthConsumerKey = key;
var oAuthConsumerSecret = secret;
var oAuthUri = new Uri("https://api.twitter.com/oauth2/token");
var authHeaderFormat = "Basic {0}";
var authHeader = string.Format(authHeaderFormat,
Convert.ToBase64String(Encoding.UTF8.GetBytes(Uri.EscapeDataString(oAuthConsumerKey)
+ ":" +
Uri.EscapeDataString((oAuthConsumerSecret)))
));
var req = new HttpClient();
req.DefaultRequestHeaders.Add("Authorization", authHeader);
HttpRequestMessage msg = new HttpRequestMessage(new HttpMethod("POST"), oAuthUri);
msg.Content = new HttpStringContent("grant_type=client_credentials");
msg.Content.Headers.ContentType = new Windows.Web.Http.Headers.HttpMediaTypeHeaderValue("application/x-www-form-urlencoded");
HttpResponseMessage response = await req.SendRequestAsync(msg);
TwitAuthenticateResponse twitAuthResponse;
using (response)
{
string objectText = await response.Content.ReadAsStringAsync();
twitAuthResponse = JSonSerialiserHelper.Deserialize<TwitAuthenticateResponse>(objectText);
}
With the 1.1 API you don't pass the access token as part of the url, you need to include it as the Authorization header as "Bearer access_token" so you were almost there!
EDIT
To do this in the Windows.Web.Http namespace the following works:
private static async Task SearchTweets(AuthenticationResponse twitAuthResponse)
{
string srchStr = "tweet";
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Authorization = new HttpCredentialsHeaderValue("Bearer", twitAuthResponse.AccessToken);
var response2 = await client.GetAsync(uri);
string content = await response2.Content.ReadAsStringAsync();
}
Or with System.Net.Http use the following:
This code will run the search for srchStr using the access token you already acquired as you showed in the first example:
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", twitAuthResponse.access_token));
HttpResponseMessage response = await client.GetAsync(uri);
Task<string> content = response.Content.ReadAsStringAsync();
EDIT
This is a strange one, I tested your code and you're right it does throw an exception when attempting to add the Auth header, however the code I had used for grabbing the Access Token is almost identical but uses the System.Net.Http methods rather than the Windows.Web.Http ones that you use and it works, so I'll provide my code here, maybe this is a bug in the framework, or someone else can provide some more insight! This also uses the JSON.NET library which can be found on NuGet.
private static async Task SearchTweets(AuthenticationResponse twitAuthResponse)
{
string srchStr = "tweet";
var client = new HttpClient();
var searchUrl = string.Format("https://api.twitter.com/1.1/search/tweets.json?q={0}", srchStr);
var uri = new Uri(searchUrl);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Bearer {0}", twitAuthResponse.AccessToken));
HttpResponseMessage response2 = await client.GetAsync(uri);
string content = await response2.Content.ReadAsStringAsync();
}
private async void GetAuthenticationToken()
{
var client = new HttpClient();
var uri = new Uri("https://api.twitter.com/oauth2/token");
var encodedConsumerKey = WebUtility.UrlEncode(TwitterConsumerKey);
var encodedConsumerSecret = WebUtility.UrlEncode(TwitterConsumerSecret);
var combinedKeys = String.Format("{0}:{1}", encodedConsumerKey, encodedConsumerSecret);
var utfBytes = System.Text.Encoding.UTF8.GetBytes(combinedKeys);
var encodedString = Convert.ToBase64String(utfBytes);
client.DefaultRequestHeaders.Add("Authorization", string.Format("Basic {0}", encodedString));
var data = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("grant_type", "client_credentials")
};
var postData = new FormUrlEncodedContent(data);
var response = await client.PostAsync(uri, postData);
AuthenticationResponse authenticationResponse;
using (response)
{
if (response.StatusCode != System.Net.HttpStatusCode.OK)
throw new Exception("Did not work!");
var content = await response.Content.ReadAsStringAsync();
authenticationResponse = JsonConvert.DeserializeObject<AuthenticationResponse>(content);
if (authenticationResponse.TokenType != "bearer")
throw new Exception("wrong result type");
}
await SearchTweets(authenticationResponse);
}
}
class AuthenticationResponse
{
[JsonProperty("token_type")]
public string TokenType { get; set; }
[JsonProperty("access_token")]
public string AccessToken { get; set; }
}

Categories

Resources