Calling the SharpSpring API in .NET and posting the data to SharePoint List

 




Your application can connect to Lead Gen & CRM's internal CRM functionality via the API that is provided by SharpSpring Lead Gen & CRM. Through the use of .NET, I want to share data between SharpSpring and a SharePoint list, and vice versa. I want to use the API in Dot-NET. However, SharpSpring Lead Gen & CRM only provides PHP-based API examples. In this article, I will explain how to use the SharpSpring APIs in .NET and how to share data between SharpSpring and SharePoint. Follow the steps below:

  First, navigate to this site: https://help.sharpspring.com/hc/en-us/sections/115000320047-API


  Then, Click on Understanding Lead Gen & CRM Open API: Methods

 

  There are various methods for the SharpSpring Lead Gen & CRM Open API. I have used the “get           opportunities” method as demonstrated below:


  Step 1:  Open the SharpSpring portal and get the Opportunity id






  After selecting the opportunity, a form is opened with the opportunity ID. I will share this form filled with SharePoint using API.

   Step 2: Open Postman and set up the SharpSpring APIs.

Account ID and secret key must be entered in the parameters and we also need to pass an object in the body. To obtain your account ID and secret key, go to Step 3. 




Parameters:

https://api.sharpspring.com/pubapi/v1/?accountID=<Your_accountId>&secretKey=<SecretKey>

Body:

{

"method":"getUserProfiles",

 "params":{

 "where":{

  "id":"320005120"

 },

 "limit":500,

 "offset":0

},

"id":"{{$guid}}"

}

 Step 3:    Open the API settings and create a new Client Key and Client Secret key.




   Step 4: Send the request and get the Array of Objects of SharpSpring.




   Step 5: Create the list columns according to this Opportunity object elements.



  Step 6: Open Visual Studio and Create a new Project. I have chosen Web framework, you can choose the template according to your needs.



  Step 7: Install the necessary Packages for SharePoint and SharpSpring

1)      Newtonsoft.Json - version - 12.0.2

2)      Microsoft.SharePointOnline.CSOM - version - 16.1.23408.12000

3)      Microsoft.SharePoint.Client - version -14.0.4762.1000

4)      Microsoft.Sharepoint.Client.Runtime  - version -  15.0.4711.1000

 


    Step 8: In the web config file, set all the private information



web.config

<appSettings>

  <add key="_sharePointURL" value="<SharepointURL>" />

  <add key="_sharePointSecretAccount" value="<SharePointAccount>" />

  <add key="_sharePointScretKey" value="<SharePointAppCode>" />

  <add key="_SharePointListName1" value="<SharePointListName>" />

  <add key="_sharpSpringBASEPOINT" value="https://api.sharpspring.com/" />

  <add key="_sharpSpringMIDMID" value="pubapi/v1/" />

  <add key="_sharpSpringSecretAccount" value="<SharpSpringAccountId>" />

  <add key="_sharpSpringSecretKey" value="<SharpSpringScreteKey>" />

  </appSettings>

 

Step 9: Create a text box and a submit button, then type the opportunity id into the text field.


Step 10: Create a Model of SharpSping Object. 

 

  public class SharpSpringModel

    {

        public string id { get; set; }

        public string ownerID { get; set; }

        public string dealStageID { get; set; }

        public string accountID { get; set; }

        public string campaignID { get; set; }

       public string campaignAttributionOverride { get; set; }

        public string opportunityName { get; set; }

        public string probability { get; set; }

        public string amount { get; set; }

           …..

           …..

          …..

          Many more elements

}



Step 11: Default.aspx

           Here, write code of HTML and create one text box and button.


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Async="true" Inherits="SharpSpringWebApp._Default" %>

 

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

 

    <div class="jumbotron">

        <h1>ASP.NET</h1>

        <p class="lead">ASP.NET is a free web framework for building great Web sites and Web applications using HTML, CSS, and JavaScript.</p>

        <p><a href="http://www.asp.net" class="btn btn-primary btn-lg">Learn more &raquo;</a></p>

    

    </div>

    

    <div class="row">

        <asp:TextBox runat="server" ID="idsearch"></asp:TextBox> <br />

        <asp:Button Text="Submit" runat="server" OnClick="SharpSpringToSharePoint"/>

    </div>

 

  

</asp:Content>

 Step 12: Default.aspx.cs

              Call the SharpSpring function when Clicking on the button;


 protected void SharpSpring(object sender, EventArgs e)

 {

         if (!idsearch.Text.IsNullOrWhiteSpace())

         {

                recordData(idsearch.Text);

          }

  }

 

 

 

Step 13: Here write the code of SharpSpring – (How to call the API Of SharpSpring)


public async void recordDat(string id){

      List<SharpSpringModel> models = new List<SharpSpringModel>();

      try

      {

            Dictionary<string, string> data = new Dictionary<string, string>();

            data.Add("accountID", ConfigurationManager.AppSettings.Get("_sharpSpringSecretAccount"));

            data.Add("secretKey", ConfigurationManager.AppSettings.Get("_sharpSpringSecretKey"));

 

            var client = new HttpClient();

            HttpRequestMessage request = SharpSpringCredentials.requestToPost(ConfigurationManager.AppSettings.Get("_sharpSpringBASEPOINT"), ConfigurationManager.AppSettings.Get("_sharpSpringMIDMID"), data);

            request.Content = SharpSpringCredentials.httpContentString(id);

            var response = client.SendAsync(request).Result;

            response.EnsureSuccessStatusCode();

            var result = await response.Content.ReadAsStringAsync();

            var customerDataObj = JObject.Parse(result);

 

    foreach (var ie in ((Newtonsoft.Json.Linq.JContainer)customerDataObj.Root)["result"]["opportunity"])

            {

                  models.Add(JsonConvert.DeserializeObject<SharpSpringModel>(Convert.ToString(ie)));

            }

            if (models.Count > 0) {

                  bool doneOrNot = SSIntegrateWithSP.SSIntegrateWithSPListQuotingProcess(models);

            }

      }

      catch (Exception ex)

      {

            Console.WriteLine(ex);

      }

}

 


 Step 14 : Write the Code of Sharepoint - Add the SharpSpring record into SharePoint


public static bool SSIntegrateWithSPListQuotingProcess(List<SharpSpringModel> sharpSpringModels)

{

      if(sharpSpringModels != null && sharpSpringModels.Count() > 0)

      {

            try

            {

                  using (ClientContext clientContext = new ClientContext(ConfigurationManager.AppSettings.Get("_sharePointURL")))

                  {

                  clientContext.Credentials = SharePointCredentials.CreateCredentials(ConfigurationManager.AppSettings.Get("_sharePointSecretAccount"), ConfigurationManager.AppSettings.Get("_sharePointScretKey"), sharePointAuthType.SharePointOnline);

                  List oList = clientContext.Web.Lists.GetByTitle(ConfigurationManager.AppSettings.Get("_SharePointListName1"));

                  ListItemCreationInformation listItemCreationInformation = new ListItemCreationInformation();

                  ListItem addListItem = oList.AddItem(listItemCreationInformation);

                  foreach (SharpSpringModel model in sharpSpringModels)

                  {

                        addListItem["EAU"] = model.eau_62b9e2a5346e4;

                        addListItem["CompellingEvent"] = model.customer_s_compelling_event_62ebc1762ac78;

                        addListItem["SOP"] = DateTime.Parse(model.start_of_production_62ebc0e34b235).ToString("MM/dd/yyyy"); 

                        addListItem["ProgramLife_x0028_Years_x0029_"] = model.program_life__years__62b9e45ab5aed;

                        addListItem["Incumbent"] = model.incumbent_or_known_competitors_bidding_62ec25662ce50;

                        addListItem.Update();

                  }

                  clientContext.ExecuteQuery();

                  return true;

                  }

            }

            catch (Exception ex)

            {

                  var data = JsonConvert.SerializeObject(sharpSpringModels);

 

                  var str = data + " \r\n "+ ex.Message;

                  HistiyLog(str);

                  Console.WriteLine(ex);

            }

      }

      return false;

}

 


          SharePointCredentials.cs

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Web;

 

namespace SharpSpringWebApp.Library.Credentials

{

    public class SharePointCredentials

    {

        /// <summary>

        /// SharePoint Authentication

        /// Return the Authentication of SharePoint

        /// </summary>

        public class SharePointAuthentication

        {

            public enum SharePointAuthenticationType

            {

                SharePointOnline,

                SharePointActiveDirectory,

            }

        }

 Public static ICredentials CreateCredentials(string UserName, string password, SharePointAuthentication.SharePointAuthenticationType sharePointAuthenticationType)

        {

            ICredentials credentials = null;

 

            switch (sharePointAuthenticationType)

            {

                case SharePointAuthentication.SharePointAuthenticationType.SharePointActiveDirectory:

                    credentials = new NetworkCredential(UserName, password);

                    break;

                case SharePointAuthentication.SharePointAuthenticationType.SharePointOnline:

                    System.Security.SecureString securePassword = new System.Security.SecureString();

                    foreach (var passwordChar in password)

                    { securePassword.AppendChar(passwordChar); }

                    credentials = new Microsoft.SharePoint.Client.SharePointOnlineCredentials(UserName, securePassword);

                    break;

            }

 

            return credentials;

        }

    }

}

 

 

SharpSpringCredentials.cs 

   

using Microsoft.Ajax.Utilities;

using Microsoft.AspNetCore.WebUtilities;

using SharpSpringAPI.Model;

using System;

using System.Collections;

using System.Collections.Generic;

using System.Configuration;

using System.Linq;

using System.Net.Http;

using System.Security.Policy;

using System.Web;

 

namespace SharpSpringWebApp.Library.Credentials

{

    public class SharpSpringCredentials

    {

        public static HttpRequestMessage requestToPost(string baseURl, string midPoint, Dictionary<string, string> urlPrms)

        {

            HttpRequestMessage request = new HttpRequestMessage();

            if (!baseURl.IsNullOrWhiteSpace() && !midPoint.IsNullOrWhiteSpace() && urlPrms.Count()>0)

            {

                string url = QueryHelpers.AddQueryString(baseURl + midPoint, urlPrms);

                request = new HttpRequestMessage(HttpMethod.Post, url);

            }

            return request;

        }

        public static StringContent httpContentString(string id)

        {

/              //Write the method here

            return new StringContent("{\r\n\"method\":\"getOpportunities\",\r\n \"params\":{\r\n\r\n \"where\":{\r\n\r\n  \"id\":" + id + " },\r\n \"limit\":500,\r\n \"offset\":0\r\n},\r\n\"id\":\"{{$guid}}\"\r\n}", null, "application/json");

        }

      }

}

 

 

 

Give the Extra SharpSpring Method for reference.

********getUserProfiles********

{

"method":"getUserProfiles",

 "params":{

 "where":{

  "id":"320005120" //ownerID

 },

 "limit":500,

 "offset":0

},

"id":"{{$guid}}"

}

************getOpportunities*********

{

"method":"getOpportunities",

 "params":{

 "where":{

  "id":"15536751619" //Opp ID

 },

 "limit":500,

 "offset":0

},

"id":"{{$guid}}"

}

******************getAccounts******************************

{

"method":"getAccounts",

 "params":{

 "where":{

  "id":"18233736195" //accountID

 },

 "limit":500,

 "offset":0

},

"id":"{{$guid}}"

}

 

*******************updateOpportunities*************************

{

  "method":"updateOpportunities",

  "params":

    {"objects":

      [

        { "id":"15536751619","oppstatus_641979bb19942" : "Done", "oppsoler_641979e71a92b" : "211321321"}

      ]

    },

  "id":"15536751619"

}

 

*******************Get DealStage*******************************

{

"method":"getDealStages",

 "params":{

 

 "where":{

  id": "520135683"

 },

 "limit":500,

 "offset":0

},

"id":"{{$guid}}"

}

 

*******************getOpportunitiesDateRange**************

{

"method":"getOpportunitiesDateRange",

 "params":{

  "startDate" : "2023-04-07 00:00:00",

  "endDate" : "2023-04-07 16:27:13",

  "timestamp" : "update"

},

"id":"{{$guid}}"

}

*******************getDealStagesDateRange****************

{

"method":"getDealStagesDateRange",

 "params":{

  "startDate" : "2023-01-06 00:00:00",

  "endDate" : "2023-04-07 16:27:13",

  "timestamp" : "update"

},

"id":"{{$guid}}"

}

 

 


                                                                                                                      - Arvind


                                                       


 


                 




 





















 



 

Comments

Popular posts from this blog

Introduction to Copilot in PowerApps

Still using Classic SharePoint Sites?

SharePoint Migration