Subitting A form to the API not working


#1

Hi,

So I'm having a problem submitting a form to the API.
Using the documentation found here we replicated the provided class in MVC. Everything works great until the request is sent, at which point we receive one of two errors:
a) An error about not having permission to write to the form
b) A 'Payment Required' response (not the case)

Any assistance would be greatly appreciated. For reference the class used is below.

public class HubSpotFormController : Controller
{
private readonly ILog _log;

    public HubSpotFormController(ILog log)
    {
        _log = log;
    }

    [HttpPost]
    public JsonResult SubmitForm(string firstName, string lastName, string email, string upgrade_phone_number, string company, string biggest_challenges)
    {
        // Build dictionary of field names/values (must match the HS field names)
        var dictFormValues = new Dictionary<string, string>
        {
            {"firstname", firstName},
            {"lastname", lastName},
            {"email", email},
            {"upgrade_phone_number", upgrade_phone_number},
            {"company", company},
            {"biggest_challenges", biggest_challenges}
        };

        // Form Variables (from the HubSpot Form Edit Screen)
        const int intPortalID = /*Removed*/; //place your portal ID here
        const string strFormGUID = /*Removed*/; //place your form guid here

        // Tracking Code Variables
        var strHubSpotUTK = Request.Cookies["hubspotutk"].Value;
        var strIpAddress = System.Web.HttpContext.Current.Request.UserHostAddress;

        // Page Variables
        const string strPageTitle = "Upgrade";
        var strPageURL = System.Web.HttpContext.Current.Request.Url.AbsoluteUri;

        // Do the post, returns true/false
        var strError = "";
        var result = Post_To_HubSpot_FormsAPI(intPortalID, strFormGUID, dictFormValues, strHubSpotUTK, strIpAddress, strPageTitle, strPageURL, strError);
        return Json(result);
    }

    /// This helper function sends data to the the HubSpot Forms API
    /// HubSpot Portal ID, or 'HUB ID'
    /// Unique ID for the form
    /// Dictionary containing all of the field names/values
    /// UserToken from the visitor's browser
    /// IP Address of the visitor
    /// Title of the page they visited
    /// URL of the page they visited
    public async Task<bool> Post_To_HubSpot_FormsAPI(int intPortalID, string strFormGUID, Dictionary<string, string> dictFormValues, string strHubSpotUTK, string strIpAddress, string strPageTitle, string strPageURL, string strMessage)
    {

        // Build Endpoint URL
        var strEndpointURL = string.Format("https://forms.hubspot.com/uploads/form/v2/{0}/{1}", intPortalID, strFormGUID);

        // Setup HS Context Object
        var hsContext = new Dictionary<string, string>();
        hsContext.Add("hutk", strHubSpotUTK);
        hsContext.Add("ipAddress", strIpAddress);
        hsContext.Add("pageUrl", strPageURL);
        hsContext.Add("pageName", strPageTitle);

        // Serialize HS Context to JSON (string)
        var strHubSpotContextJSON = JsonConvert.SerializeObject(hsContext);

        // Create string with post data
        var strPostData = "";

        // Add dictionary values
        foreach (var d in dictFormValues)
        {
            strPostData += d.Key + "=" + Server.UrlEncode(d.Value) + "&";
        }

        // Append HS Context JSON
        strPostData += "hs_context=" + Server.UrlEncode(strHubSpotContextJSON);

        //// Create web request object
        //var r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL);

        //// Set headers for POST
        //r.Method = "POST";
        //r.ContentType = "application/x-www-form-urlencoded";
        //r.ContentLength = strPostData.Length;
        //r.KeepAlive = false;

        //// POST data to endpoint
        //using (var sw = new System.IO.StreamWriter(r.GetRequestStream()))
        //{
        //    try
        //    {
        //        sw.Write(strPostData);
        //    }
        //    catch (Exception ex)
        //    {
        //        // POST Request Failed
        //        strMessage = ex.Message;
        //        return false;
        //    }
        //}
        var client = new HttpClient();
        var requestContent = new StringContent(strPostData, Encoding.UTF8, "application/x-www-form-urlencoded");

        var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, strEndpointURL)
        {
            Content = requestContent
        };
        var result = await client.SendAsync(httpRequestMessage).ConfigureAwait(false);
        if (result.IsSuccessStatusCode)
        {
            return true;
        }

        var content = result.Content.ReadAsStringAsync();
        _log.Error(content);
        return false;
    }
}

#2

Hi @matt_rumsey1212,

That's odd; can you give me the raw error(s) you're seeing so that I can take a closer look? It would also be helpful if you could send me your Hub ID and a link to the form you're looking at in HubSpot.