When I post a campaign on Mailchimp using RestSharp, it tells me my API key is missing, but when I click "Get Campaign", it successfully shows me all the campaign data.
Can anyone tell me where I'm going wrong? Here's my code:
public MailChimpPostModel PostCampaign(MailChimpPostModel post)
{
var auth = _userBusinessObject.GetUserWebsiteAuthorizationByWebsite(_userId,
_websiteId,
_linkvanaNetworkSiteId);
ApiBaseUrl = <url> ;
if (auth == null)
throw new RestRequestResponseException { Error = RestErrorsEnum.NotAuthenticated };
var request = new RestRequest(3.0/campaigns, Method.POST);
request.AddParameter("access_token", <Token>);
request.AddParameter("apikey", <Token> + "-" + <dc>);
request.AddHeader("content-type", "application/json");
request.AddBody(post);
var response = Execute<MailChimpPostModel>(request);
return response;
}
// replace usX to match the last 3 of your API
var client = new RestClient("https://usX.api.mailchimp.com/3.0/");
client.Authenticator = new HttpBasicAuthenticator("user", APIKey);
Related
I am currently setting up a web page where users can send event requests to others using the Microsoft Graph api. I would like users to be able to send an online meeting request and then provide the options of ms teams and Skype.
However as soon as I add the property 'isOnlineMeeting' and/or 'onlineMeetingProvider' I will always return an error 400 with a bad request. This is because the property doesn't exist on the /me/events.
(the response)
I have no idea why however, currently I am using the microsoft graph explorer to test the request.
I have made sure that every permission is needed to send an invite:
Calendar.Read
Calendar.Read.Shared
Calendar.ReadWrite
Calendar.ReadWrite.Shared
If a meeting is sent without these properties it works fine. I have created other personal outlook accounts and it works as expected with this property. I have asked other people in my org to try too and theirs works fine.
Does this mean that my ms account is broken in some way? if so how could I fix it in order to send this request.
Try this:
var body= "{email body};
var string = "{\"subject\": \"Join the Teams Meeting\", \"body\": {\"contentType\": \"HTML\", \"content\": \"" + body + "\" }, \"start\": {\"dateTime\": \"2020-09-28T19:30:34\",\"timeZone\": \"Pacific Standard Time\" }, \"end\": { \"dateTime\": \"2020-09-28T20:00:34\", \"timeZone\": \"Pacific Standard Time\"}, \"location\":{ \"displayName\":\"Team meeting\" }, \"attendees\": [ { \"emailAddress\": { \"address\":\"xxxx#in.xxx.com\", \"name\": \"xxxx xxxx\" }, \"type\": \"required\" } ],\"allowNewTimeProposals\": \"true\"}";
client = new RestClient("https://graph.microsoft.com/v1.0/me/events");
request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/json");
request.AddHeader("authorization", "Bearer " + token);
request.AddHeader("accept-language", "en");
request.AddHeader("accept", "application/json");
request.AddParameter("application/json", string, ParameterType.RequestBody);
response = client.Execute(request);
To generate token:
var client = new RestClient("https://login.microsoftonline.com/{tenant-Id}/oauth2/v2.0/token");
var request = new RestRequest(Method.POST);
request.AddHeader("cache-control", "no-cache");
request.AddHeader("content-type", "application/x-www-form-urlencoded");
request.AddHeader("grant_type", "password");
request.AddParameter("application/x-www-form-urlencoded", "grant_type=password&client_id={client-Id}&client_secret={client-secret}&scope={scopeurl}&userName={username}&password={password}", ParameterType.RequestBody);
IRestResponse response = client.Execute(request);
var json = response.Content;
var JSONObject = JObject.Parse(json);
var token = (string)JSONObject["access_token"];
Have been working on creating a custom TFS Service Hook which 'll post (HTTP) notification to Slack.
My requirement is to POST a HTTP call to slack when a Bug workitem's status is changed to Inprogress . (I have Implemented the same with TFS Server side plugin .unfortunately , I had to go for Service Hook over Plugin)
I tried the below code with TFS 2017 onprem with PAT, unfortunately it was breaking. am I doing anything wrong ? I want my code to work in 2015.2 without PAT.
Can someone help please ?
public async static void CreateServiceHook(string collName, string projName, string projId, string AccessToken)
{
try
{
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
string url = "https://" + collName + ".visualstudio.com/DefaultCollection/_apis/projects/" + projName + "?includecapabilities=true&api-version=1.0";
HttpRequestMessage req = new HttpRequestMessage(new HttpMethod("GET"), url);
var response = client.SendAsync(req).Result;
string contents = await response.Content.ReadAsStringAsync();
}
//create service hook
using (HttpClient client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AccessToken);
var request = new
{
publisherId = "tfs",
eventType = "workitem.created",
consumerId = "webHooks",
consumerActionId = "httpRequest",
scope = "project",
publisherInputs = new {
// buildStatus = "",
projectId = projId
},
consumerInputs = new
{
url = "https://slack.api.com/services/XXXXXXXXXX
}
};
var response = client.PostAsync("https://" + collName + ".visualstudio.com/DefaultCollection/_apis/hooks/subscriptions/?api-version=1.0",
new StringContent(JsonConvert.SerializeObject(request).ToString(),
Encoding.UTF8, "application/json"))
.Result;
if (response.IsSuccessStatusCode)
{
dynamic content = JsonConvert.DeserializeObject(
response.Content.ReadAsStringAsync()
.Result);
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
TFS has default slack service hook which can post a message to a channel. So instead of using web hooks consumer, you can use slack consumer. And you can only achieve is posting messages to Slack when a Bug workitem's status is updated.
The API looks like below:
POST http://tfsserver:8080/tfs/DefaultCollection/_apis/hooks/subscriptions?api-version=3.2
Content-Type: application/json
{
"consumerActionId":"postMessageToChannel",
"consumerId":"slack",
"consumerInputs":{
"url":"https://hooks.slack.com/services/xxxxxx"},
"eventType":"workitem.updated",
"publisherId":"tfs",
"publisherInputs":{
"areaPath":"",
"workItemType":"Bug",
"changedFields":"System.State",
"projectId":"77e3c775-dc30-4354-xxxx-xxxxxxxxxxxx"},
"scope":1
}
I am using oauth2/token to authenticate my application and get the access_token. Bellow is the java code which is working fine.
private String getToken() throws Exception {
String access_token = "";
String url = "https://login.windows.net/MyApplication_ID_here/oauth2/token";
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setHeader("Content-Type", "application/x-www-form-urlencoded");
List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
urlParameters.add(new BasicNameValuePair("grant_type", "client_credentials"));
urlParameters.add(new BasicNameValuePair("client_id", "MyApplication_ID_here"));
urlParameters.add(new BasicNameValuePair("client_secret", "MyApplication_secret_here"));
urlParameters.add(new BasicNameValuePair("resource", "https://graph.microsoft.com"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("Sending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
String responseAsString = EntityUtils.toString(response.getEntity());
System.out.println(responseAsString);
try {
access_token = responseAsString.split(",")[6].split("\"")[3]; // get the access_token from response
} catch (Exception e) {
e.printStackTrace();
return null;
}
return access_token;
}
Response :
{"token_type":"Bearer","expires_in":"3599","ext_expires_in":"0","expires_on":"1493011626","not_before":"1493007726","resource":"https://graph.microsoft.com","access_token":"eyJ0e..."}
then I am using access_token to load the memberOf value which is not working and gives me the Access Token missing or malformed error. Bellow is the java code
private void getMemberOf()
{
HttpClient httpclient = HttpClients.createDefault();
try
{
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
URI uri = builder.build();
HttpGet request = new HttpGet(uri);
request.addHeader("Authorization", "Bearer " + access_token);
request.addHeader("Content-Type", "application/json");
HttpResponse response = httpclient.execute(request);
HttpEntity entity = response.getEntity();
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
}
catch (Exception e)
{
e.getMessage();
}
}
Response :
Response Code : 401
{"odata.error":{"code":"Authentication_MissingOrMalformed","message":{"lang":"en","value":"Access Token missing or malformed."},"date":"2017-04-24T04:39:38","requestId":"c5aa2abe-9b37-4611-8db1-107e3ec08c14","values":null}}
Can someone please tell me which part of the above request is wrong? Am I not setting access_token correctly?
According to your code , your access token is for resource "https://graph.microsoft.com"(Microsoft Graph API) ,But the access token is used for "https://graph.windows.net"(AAD Graph API) :
URIBuilder builder = new URIBuilder("https://graph.windows.net/MyApplication_ID_here/users/test#testABC.onmicrosoft.com/memberOf?api-version=1.6");
If you want to call Azure AD graph api , you need to get access token for Azure AD Graph API .
I got this issue while performing the CRUD operation on Azure AD B2C service via AD Graph API for user management.
The idea is to get the access token for the resource "graph.windows.net" instead I was using my tenant App Id URI as it was suggested here.
*might help people who faced the same issue and landed up here
I am attempting to connect to the Twitter API with these instructions
https://dev.twitter.com/docs/auth/application-only-auth
Here is my code:
var baseUrl = "http://api.twitter.com/";
var client = new RestClient(baseUrl);
var request = new RestRequest("/oauth2/token", Method.POST);
var concat = ConfigurationManager.AppSettings["TwitterConsumerKey"] + ":" +
ConfigurationManager.AppSettings["TwitterConsumerSecret"];
string encodeTo64 = concat.EncodeTo64();
request.AddHeader("Authorization", "Basic " + encodeTo64);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
request.AddBody("grant_type=client_credentials");
IRestResponse restResponse = client.Execute(request);
EncodeTo64
static public string EncodeTo64(this string toEncode)
{
byte[] toEncodeAsBytes
= System.Text.ASCIIEncoding.ASCII.GetBytes(toEncode);
string returnValue
= System.Convert.ToBase64String(toEncodeAsBytes);
return returnValue;
}
Response.Content is the following
"{\"errors\":[{\"code\":170,\"label\":\"forbidden_missing_parameter\",\"message\":\"Missing required parameter: grant_type\"}]}"
Is this part wrong?
request.AddBody("grant_type=client_credentials");
I have verified that my credentials are correct (I got that error before, but resolved it, so it should be OK).
The instructions on the Twitter page confused me. "The body of the request must be grant_type=client_credentials."
As for Restsharp, it's not AddBody, but AddParameter.
So:
request.AddParameter("grant_type", "client_credentials");
Can't get the POST working? What's wrong?
Note: This works for a GET with autocomplete
GET works without signing the url
I'm following the Web services steps to Sign the URL with my "API Key"
Docs say"client id" still?
http://code.google.com/apis/maps/documentation/webservices/
2.Try sending the POST data with the signed URL (tried the unsigned signature aswell)
def signedUrl = "https://maps.googleapis.com/maps/api/place/add/json?key=xxxxxkeyxxxxxx&sensor=false&signature=xxxxxxxxxxsignaturexxxxxx"
String postData = "{'location': { 'lat': '-33.8669710','lng': '151.1958750'},'accuracy': '50','name': 'Google Shoes!'}"
URL urlPost = new URL(signedUrl);
URLConnection connection = urlPost.openConnection();
connection.addRequestProperty("Referer", "http://www.mysite.com");
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setRequestProperty("CONTENT-TYPE", "text/json");
connection.setRequestProperty("CONTENT-LENGTH", postData.length() + "");
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write(postData);
out.close();
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while((line = reader.readLine()) != null) {
builder.append(line);
}
JSONObject json = new JSONObject(builder.toString());
println json
Returns a 403
"java.io.IOException: Server returned HTTP response code: 403 for URL:"
Simular to the "Java Access"section under they give an example of a GET
http://code.google.com/apis/websearch/docs/#fonje
Ok solved.
No signing the URL required
postData string was wrong
should have been
String postData = "{\"location\": { \"lat\": -33.8669710,\"lng\": 151.1958750},\"accuracy\": 50,\"name\": \"Google Shoes!\", \"types\":[\"bar\"]}"