post an email to a survey using the surveymonkey api - c#

we have a survey in surveymonkey and using c# to try and add the email addresses to the survey using the surveymonkey api. the api works fine for GETS but we have yet to get a POST to work. all we get back is
"docs": "https://developer.surveymonkey.com/api/v3/#error-codes",
"message": "There was an error retrieving the requested resource.",
"id": "1020",
"name": "Resource Not Found",
"http_status_code": 404
all of the id's are correct as we can GET information about the survey but cannot POST to it. we have granted all the scopes so there shouldn't be a limitation or restriction on that side. SurveyMonkey api support might as well not exist as they are a complete waste of time and cannot answer a single question about their api.
the code below is our latest attempt at calling out to the api with a POST. we put the actual ids in the uri instead of {id} I did not include our id's here for the obvious reasons.
using (var client = new HttpClient())
{
var uri = new Uri("https://api.surveymonkey.net/v3/surveys/{id}/collectors/{id}/messages/{id}/recipients-d");
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",ConfigurationManager.AppSettings["SurveyMonkeyAccessToken"]);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var content = new StringContent("{ \"email\": + " + emailAddress + " }", Encoding.UTF8, "application/json");
var response = client.PostAsync(uri,content);
ParseSurveyPostResponses(response)
}
anyone successfully post to a surveymonkey survey using their V3 api?

What exactly are you trying to do? Are you trying to create an email collector? Are you trying to create a new message on that email collector?
Are you trying to add recipients to that email? are you trying to send out the email?
Creating an email collector:
POST /v3/<survey_id>/collectors
{
"type": "email"
}
Adding a message to an email collector:
POST /v3/collectors/<collector_id>/messages
{
"type": "invite"
}
Add recipients to a message:
POST /collectors/<collector_id>/messages/<message_id>/recipients
{
"email": "test#example.com",
"first_name": "Test",
"last_name": "Example",
"custom_fields": {
"1": "First Value",
"2": "Second Value",
"3": "Third Value"
},
"extra_fields": {
"field_name1": "field_value1",
"field_name2": "field_value2"
}
}
NOTE: You can also add recipients in bulk
NOTE2: Custom fields are stored on the associated contact in your contact list, Extra Fields are only stored on the recipient for that message and only accessible through the API.
Sending out the email:
POST /v3/collectors/<collector_id>/messages/<message_id>/send
{
"scheduled_date": "2017-07-18T16:52:22"
}
NOTE: you can exclude the scheduled_date and just send in {} to send the message right away.

Related

Webhook Notification With Authorize.Net

I created an endpoint (Endpoint) for the webhook part in Authorize.Net and when I create subscription for a user from web app, I get the following in the request body (Am using Beeceptor for the endpoint):
{
"notificationId": "79780e46-c62d-4620-b4fb-e8c29366b2ec",
"eventType": "net.authorize.customer.subscription.created",
"eventDate": "2021-05-08T17:23:57.7129026Z",
"webhookId": "3b2fd08b-a7c4-4f29-95b5-8330958d6031",
"payload": {
"name": "AT",
"amount": 3.00,
"status": "active",
"profile": {
"customerProfileId": 1518406781,
"customerPaymentProfileId": 1517676588
},
"entityName": "subscription",
"id": "7397362"
}
}
I followed the link to create the endpoint - Webhook
I believe, am close enough for webhook notifications. But can anyone suggest when the monthly subscription is charged using Authorize.Net, how the response body is passed to endpoint with the webhook like is it jSon data or something similar (Obviously jSon, I believe) or what fields will it return in response (SubscriptionId, Date)? In the documentation, they trigger different event to notify with Webhook. My final goal is to retrieve that a subscriber has been charged for a month and this should be saved in database for future use. Though I just started trying with it, will like to have some feedback on it in advance - Thanks.
N.B: Below image is the output when an event is triggered using Webhook.
For regular transaction, I get the following using webhook notification:
{
"notificationId": "c453f527-8b7c-407d-8ec7-b022188af4a7",
"eventType": "net.authorize.payment.authcapture.created",
"eventDate": "2021-05-08T17:51:20.5783303Z",
"webhookId": "3b2fd08b-a7c4-4f29-95b5-8330958d6031",
"payload": {
"responseCode": 1,
"authCode": "OT3UUE",
"avsResponse": "Y",
"authAmount": 1.00,
"entityName": "transaction",
"id": "60167299547"
}
}
C# sample Code: Web request from C# web app
public string GetNotificationWithWebhook()
{
string response = "";
var url = "beeceptor endpoint here";
var httpRequest = (HttpWebRequest)WebRequest.Create(url);
var httpResponse = (HttpWebResponse)httpRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
response = streamReader.ReadToEnd();
}
return response;
}
Request body and response:
The webhook notification will be almost exactly like a "regular" transaction but a subscription ID will also be included. So it should resemble:
{
"notificationId": "c453f527-8b7c-407d-8ec7-b022188af4a7",
"eventType": "net.authorize.payment.authcapture.created",
"eventDate": "2021-05-08T17:51:20.5783303Z",
"webhookId": "3b2fd08b-a7c4-4f29-95b5-8330958d6031",
"payload": {
"responseCode": 1,
"authCode": "OT3UUE",
"avsResponse": "Y",
"authAmount": 1.00,
"entityName": "transaction",
"id": "60167299547",
"subscriptionId": "1234567890"
}
}
I just tested. The subscriptionId field is not the part of Payload of net.authorize.payment.authcapture.created.
So the solution is to use id(transactionid) to call "Get Transaction Details" API which returns the subscription fields.
Reference: https://community.developer.cybersource.com/t5/Integration-and-Testing/net-authorize-payment-authcapture-created-does-not-have/td-p/63234

Loop through a json response received from facebook graph api in c# and get the latest value. (then, store it in database in dot net core)

I'm using the graph API of facebook to get the permalink of facebook posts. But it seems the endpoint always returns an array of all the posted posts.
So, I need to take the response and loop through it and get only the latest value that is always the first pair in the response.
Here is the response I get using the graph explorer. I only need the first pair from data array i.e the permalink_url and the id so that I can store them separately in a database to embed posts in my website using the permalink.
{
"data": [
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/358023508748119/?type=3",
"id": "347775946439542_358023508748119"
},
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/350654269485043/?type=3",
"id": "347775946439542_350654269485043"
},
{
"permalink_url": "https://www.facebook.com/347775946439542/photos/a.348021906414946/350651839485286/?type=3",
"id": "347775946439542_350651839485286"
}
],
"paging": {
"cursors": {
"before": "QVFIUlRGODNTaFZAueEUxQ2VvcHlrMUw1MGE0U0FCblhZAY1hVbFBGUHhHdXlrSkgzSm0tb05pSGpFOXBYVG9EcnN5T21sQTgtYy1jSjhrZAW9WYmg5YmpVMXpQWTRLUkQ3ZA05PcEZAjUTNyV2VuV05hRG8yVlBaa3pia3dFTVRLU05nU0pU",
"after": "QVFIUlBHMG44ZAkxHdUsxb012bVlOQ0ZAfaDhHLUZA6VEt6MHd0QjJYZADlfZAVk2aExSdlJESUU2SlVDaVJsYzI4dnlmUllZASzhKd3Nkb09aa2ZAMRHZAFTGhMVHFoQ1hjNE5zNDJ2aV96UGtVQUpBeHE1b2xUTzk2SHZALLTZA1Y3pZAZAmJOMENS"
}
}
}
I did go through some questions on this that used newtonsoft but couldn't get it to work.
So any help on how to loop through this in C# (razor page) and then return them from a method. Thenafter I need to store both the permalink as well as the id in database.
Here is my method: Here _getPermalink has the endpoint I have to hit.
Also 'str' has the response which is shown below. I have to fetch the permalink and id from that.
public string GetPermalink()
{
WebClient client = new WebClient();
Stream data = client.OpenRead(_getPermalink);
StreamReader reader = new StreamReader(data);
string str = "";
str = reader.ReadLine();
data.Close();
return str;
}
When I call this endpoint from the method:string res = facebook.GetPermalink(); (Here facebook is just a constructor with values required for making the call to endpoint such as page id, access token,etc.)
The same response looks something like this.
{"data":[{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/358023508748119\/?type=3","id":"347775946439542_358023508748119"},{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/350654269485043\/?type=3","id":"347775946439542_350654269485043"},{"permalink_url":"https:\/\/www.facebook.com\/347775946439542\/photos\/a.348021906414946\/350651839485286\/?type=3","id":"347775946439542_350651839485286"}],"paging":{"cursors":{"before":"QVFIUlRGODNTaFZAueEUxQ2VvcHlrMUw1MGE0U0FCblhZAY1hVbFBGUHhHdXlrSkgzSm0tb05pSGpFOXBYVG9EcnN5T21sQTgtYy1jSjhrZAW9WYmg5YmpVMXpQWTRLUkQ3ZA05PcEZAjUTNyV2VuV05hRG8yVlBaa3pia3dFTVRLU05nU0pU
I'm relatively new with the concept of json object/arrays in C# and using newtonsoft. Any help and explanations are appreciated.
(PS: Is there a way to get the permalink and id of the Latest Posts ONLY, using the facebook graph api?)
Given the JSON data you posted, you can get the first permalink URL from it using the following one-liner:
string permalinkUrl = (string)JObject.Parse(json).SelectToken("data[0].permalink_url");
Demo: https://dotnetfiddle.net/SUgz51

LinkedIn signin emailAddress retrieval

Using the below endpoint to retrieve the emailAddress in URN format as per new V2 guidelines:
https://api.linkedin.com/v2/emailAddress?q=members&projection=(elements*(handle~))
Get the response in the format:
{
"elements": [
{
"handle": "urn:li:emailAddress:<id>",
"handle~": {
"emailAddress": "email#provider.com"
}
}
]
}
Using a rest sharp client, we have received the correct response, but how to deserialize(in C#) the response in above format to retrieve only the email address?
Have tried to use the projection : projection=(elements*(handle~(vanityName))) and try to get the field directly : q=members&fields=emailAddress , but get "not enough permissions to access field vanityName for GET /clientAwareEmailAddresses/ not enough permissions to access field emailAddress for GET-members /emailAddress" error
Have used the scope r_liteprofile r_emailaddress in the authorization request.
Try this:
jsonContent = JObject.Parse(content);
var profileEmail = jsonContent["elements"][0]["handle~"]["emailAddress"].ToString();

Updating trigger frequency of Azure Logic App using API

I am trying to update the recurrence frequency and interval of a Logic App using Azure Logic SDK and it is failing with this error message
Microsoft.Rest.Azure.CloudException: The request to patch workflow 'kk-test-logic-app' is not supported.
None of the fields inside the properties object can be patched.
Here is a code snippet showing what I am trying to do.
var workflow = await _client.Value.Workflows.GetAsync(resourceGroupName, workflowName);
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = triggerFrequency, interval = triggerInterval });
await _client.Value.Workflows.UpdateAsync(resourceGroupName, workflowName, workflow);
where _client is Lazy<LogicManagementClient>.
Here is the definition of the trigger I am trying to update (got using Fiddler):
"triggers": {
"When_a_new_email_arrives": {
"recurrence": {
"frequency": "Hour",
"interval": 2
},
"splitOn": "#triggerBody()?.value",
"type": "ApiConnection",
"inputs": {
"host": {
"api": {
"runtimeUrl": "https://logic-apis-southindia.azure-apim.net/apim/office365"
},
"connection": {
"name": "#parameters('$connections')['office365']['connectionId']"
}
},
"method": "get",
"path": "/Mail/OnNewEmail",
"queries": {
"folderPath": "Inbox",
"importance": "Any"
}
}
}
}
Note that I am able to successfully retrieve the workflows, workflowRuns, workflowTriggers etc. Only the update operation is failing. Any ideas on how to update properties of workflows using the SDK?
UPDATE:
As pointed out by Amor-MSFT in the comments below, this is a defect and as a workaround, I am currently using CreateOrUpdateAsync instead of UpdateAsync. A new defect has been created in GitHub to get this to the attention of the SDK development team.
The trigger currently executes every 30s checking if a new mail was received from a certain email address and is working well as expected. I'm trying to change the recurrence frequency from 30s to 2hours using the code I provided.
I created a mail trigger and I can reproduce the issue if I use invoke UpdateAsync method. According to the source code of Azure Logic C# SDK, it send a PATCH request which is not supported according the response message. After changed the HTTP method to PUT, I can update the workflow. Here is the sample code which I used to send the PUT request.
string triggerName = "When_a_new_email_arrives";
string resourceGroupName = "my resourcegroup name";
string workflowName = "my-LogicApp";
string subscriptionID = "my-subscriptionID";
var workflow = await _client.Workflows.GetAsync(resourceGroupName, workflowName);
string url = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Logic/workflows/{2}?api-version=2016-06-01",
subscriptionID, resourceGroupName, workflowName);
HttpClient client = new HttpClient();
HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Put, url);
message.Headers.Add("Authorization", "Bearer put your token here");
message.Headers.Add("Accept", "application/json");
message.Headers.Add("Expect", "100-continue");
dynamic workflowDefinition = workflow.Definition;
workflowDefinition.triggers[triggerName]["recurrence"] = JToken.FromObject(new { frequency = "Minute", interval = 20 });
string s = workflow.ToString();
string workflowString = JsonConvert.SerializeObject(workflow, _client.SerializationSettings);
message.Content = new StringContent(workflowString, Encoding.UTF8, "application/json");
await client.SendAsync(message);

Google+ Moments:Insert AddActivity generic error

I'm trying to publish an app moment for Google+. The app successfully completes the authentication process and receives the access token. The problem happens when I try to call the Moment.Insert API on "https://www.googleapis.com/plus/v1/people/me/moments/vault", always returns this unspecified error message
{
"error": {
"errors": [
{
"domain": "global",
"reason": "invalid",
"message": "Invalid Value"
}
],
"code": 400,
"message": "Invalid Value"
}
}
The API steps I'm following are the ones listed here https://developers.google.com/+/api/latest/moments/insert and the request looks like this
{
"target": {
"kind": "plus#itemScope",
"name": "Sample Test for Google Plus REST API",
"id": "88370F18-81A4-47F5-BC2F-19EDBE326A20",
"url": "http://schema.org/Thing"
},
"type": "http://schemas.google.com/AddActivity",
"kind": "plus#moment"
}
I also add the access token to the request header & the api key to the url as a parameter.
I don't know if I'm missing something here but it may worth saying that I receive the exact same error message when using the API explorer in Google Dev. Console.
Thanks in advance for any insights
This is the moment declaration that worked for me. For some reason, the description field is required and not adding it would produce this strange error message.
var client = new RestClient();
var moment = new
{
kind = "plus#moment",
type = "https://schemas.google.com/AddActivity",
target = new
{
kind = "plus#itemScope",
id = "GENERATE-A-POST-ID-HERE",
type = "https://schemas.google.com/AddActivity",
name = "SOMTHING-TO-POST",
description = "SOMTHING-TO-POST"
}
};
var request = new RestRequest(string.Format("{0}?key={1}", GOOGLE_POST_URL, GOOGLE_APP_ID), Method.POST);
request.AddHeader("authorization", "BEARER-ACCESS-TOKEN-RECEIVED-BEFORE");
request.AddBody(moment);
client.ExecuteAsync(request, OnPostCompleted);
I'm using RestSharp library to handle the REST operations.
Hope this would help.

Categories