Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sample C# code to create a lead with the Zoho CRM API.
/*
* Sample C# code to create a lead with the Zoho CRM API.
* ajh 2012-08-23
*/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Dynamic;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;
using System.Xml.Linq;
using EasyHttp.Http;
using log4net;
namespace Sample.Web
{
public class ZohoCrm
{
static string ZohoApiBaseUrl = "https://crm.zoho.com/crm/private/xml/Leads/insertRecords";
static string ZohoApiKey = ConfigurationManager.AppSettings["ZohoApiKey"];
public static bool CreateLead(BLL.SampleLead sl)
{
ILog _log = log4net.LogManager.GetLogger("ZohoCrm/CreateLead");
XDocument xmlData = new XDocument(
new XElement("Leads",
new XElement("row", new XAttribute("no", "1"),
new XElement("FL", new XAttribute("val", "Lead Source"), "Trial Signup"),
new XElement("FL", new XAttribute("val", "Company"), sl.CompanyName),
new XElement("FL", new XAttribute("val", "Last Name"), sl.Name),
new XElement("FL", new XAttribute("val", "Email"), sl.EMail)
)));
string url = string.Format("{0}?authtoken={1}&scope=crmapi&newFormat=1&xmlData={2}",
ZohoApiBaseUrl, ZohoApiKey,
HttpUtility.UrlEncode(xmlData.ToString()));
var http = new HttpClient
{
Request = { Accept = HttpContentTypes.ApplicationXml }
};
dynamic emptyPost = new ExpandoObject();
EasyHttp.Http.HttpResponse response;
try
{
response = http.Post(url, emptyPost, HttpContentTypes.ApplicationXml);
}
catch (WebException ex)
{
_log.ErrorFormat("Error: WebException - {0}", ex.Message);
return false;
}
if (response.StatusCode != HttpStatusCode.OK)
{
_log.InfoFormat("Response = {0} - {1}", response.StatusCode, response.StatusDescription);
_log.Info(response.RawText);
return false;
}
XDocument xdoc;
try
{
xdoc = XDocument.Parse(response.RawText);
}
catch (XmlException ex)
{
_log.ErrorFormat("Error: XmlException parsing API response - {0}", ex.Message);
_log.Info(response.RawText);
return false;
}
string msg;
try
{
msg = xdoc.Descendants("result").First().Element("message").Value;
}
catch (Exception ex)
{
_log.ErrorFormat("Error: Exception reading from API response - {0}", ex.Message);
_log.Info(response.RawText);
return false;
}
if (msg != "Record(s) added successfully")
{
_log.InfoFormat("Unexpected XML result: {0}", msg);
_log.Info(response.RawText);
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment