Bitrix24 CRM have webhook functional to add leads (clients) to CRM. All documentation is written on php, but I want to use ASP.NET. Here's how they do it on php:
$queryUrl = 'https://restapi.bitrix24.ru/rest/1/31uhq2q855fk1foj/crm.lead.add.json';
$queryData = http_build_query(array(
'fields' => array(
"TITLE" => "NEW LEAD"
),
'params' => array(
"REGISTER_SONET_EVENT" => "Y"
)
));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_SSL_VERIFYPEER => 0,
CURLOPT_POST => 1,
CURLOPT_HEADER => 0,
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $queryUrl,
CURLOPT_POSTFIELDS => $queryData
));
$result = curl_exec($curl);
curl_close($curl);
$result = json_decode($result, 1);
I'm trying to do the same thing using ASP.NET, but get error 400 as a response. I almost sure that the problem is in the request parameters, line const string data = @"[{""fields"":{""title"":""Test""}}]";
. I've tried tons of combinations, but nothing worked.
const string url = @ "https://companyname.bitrix24.ru/rest/14/31uhq2q855fk1foj/crm.lead.add.json";
const string data = @"[{""fields"":{""title"":""Test""}}]";
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(url);
byte[] cred = Encoding.UTF8.GetBytes("email:password");
client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", Convert.ToBase64String(cred));
client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(data, Encoding.UTF8, "application/json");
HttpResponseMessage messge = client.PostAsync(url, content).Result;
string description;
if (messge.IsSuccessStatusCode) {
string result = messge.Content.ReadAsStringAsync().Result;
description = result;
}
Bitrix24 support are very "happy" with php and does not know about other languages :( After some investigations I found way with anonymous objects and json.net. Your sample should looks like:
var data = new {
fields = new {
TITLE = "NEW LEAD"
},
@params = new {
REGISTER_SONET_EVENT = "Y"
}
};
var contentText = JsonConvert.SerializeObject(data);
var content = new StringContent(contentText, Encoding.UTF8, "application/json");
// and so on with HttpClient
Update Dec 13:
Sometimes you can't (or don't want) put field names directly into anonymous object. So, dictionary may be used:
var data = new
{
ID = someId,
FIELDS = new Dictionary<string, object>()
{
[options.SomeFieldName] = fieldValue,
},
};