Reputation: 85
I am trying to figure how to convert this curl snippet to the .net HttpClient as a Post request. Getting 500 error returned from the server from the image below.
Here is the curl command which is for ConvertKit creating a webhook.
curl -X POST https://api.convertkit.com/v3/automations/hooks
-H 'Content-Type: application/json'\
-d '{ "api_secret": "<your_secret_api_key>",\
"target_url": "http://example.com/incoming",\
"event": { "name": "subscriber.subscriber_activate" } }'
Link for reference: http://developers.convertkit.com/#webhooks
Here is my .net code snippet:
private static async Task<HttpResponseMessage> PostConverkitCreateWebhookSubscription()
{
var client = new HttpClient {BaseAddress = new Uri("https://api.convertkit.com ") };
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
dynamic event1 = new ExpandoObject();
event1.name = "subscriber.subscriber_activate";
var customEvent = JsonConvert.SerializeObject(event1);
var keyValues = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("api_secret", "<your_secret_api_key>"),
new KeyValuePair<string, string>("target_url","http://example.com/incoming"),
new KeyValuePair<string, string>("event", customEvent)
};
var request = new HttpRequestMessage(HttpMethod.Post, "/v3/automations/hooks")
{
Content = new FormUrlEncodedContent(keyValues)
};
return await client.SendAsync(request);
}
Getting error 500, so I am probably recky havoc on their servers.
Could be the JSON object for possible event ... Not sure.. Need help
Upvotes: 0
Views: 2977
Reputation: 39369
FormUrlEncodedContent
encodes key-value pairs similar to a query string. You're basically telling it to send URL-encoded key-value pairs, where the last value is JSON encoded. So your request body will look something like this:
api_secret=<your_secret_api_key>&target_url=http://example.com/incoming&event={"name":"subscriber.subscriber_activate"}
But the API expects the entire payload to be JSON encoded. This modified version should do the trick:
var data = new
{
api_secret = "<your_secret_api_key>",
target_url = "http://example.com/incoming",
@event = new
{
name = "subscriber.subscriber_activate"
}
};
var json = JsonConvert.SerializeObject(data); // json-encode everything, not just event
var client = new HttpClient { BaseAddress = new Uri("https://api.convertkit.com ") };
var content = new StringContent(json, Encoding.UTF8, "application/json");
return await client.PostAsync("/v3/automations/hooks", content);
As a side note, event
is a reserved word in C#; @event
is how you escape it in order to use it as a property name.
Upvotes: 2