Webiant Logo Webiant Logo
  1. No results found.

    Try your search with a different keyword or use * as a wildcard.

FacebookConversionsHttpClient.cs

using System.Text;
using Newtonsoft.Json;
using Nop.Core;
using Nop.Plugin.Widgets.FacebookPixel.Domain;

namespace Nop.Plugin.Widgets.FacebookPixel.Services;

/// 
/// Represents the HTTP client to request Facebook Conversions API
/// 
public class FacebookConversionsHttpClient
{
    #region Fields

    protected readonly HttpClient _httpClient;

    #endregion

    #region Ctor

    public FacebookConversionsHttpClient(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    #endregion

    #region Methods

    /// 
    /// Send event through conversions api
    /// 
    /// Facebook pixel configuration object
    /// Conversions api event object
    /// 
    /// A task that represents the asynchronous operation
    /// The task result contains the asynchronous task whose result contains the response details
    /// 
    public async Task SendEventAsync(FacebookPixelConfiguration facebookPixelConfiguration, ConversionsEvent conversionsEvent)
    {
        var urlString = string.Join($"/",
        [
            FacebookPixelDefaults.FbConversionsApiBaseAddress,
            FacebookPixelDefaults.FbConversionsApiVersion,
            facebookPixelConfiguration.PixelId,
            FacebookPixelDefaults.FbConversionsApiEventEndpoint
        ]) + $"?access_token=" + facebookPixelConfiguration.AccessToken;

        var jsonString = JsonConvert.SerializeObject(conversionsEvent, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
        var requestContent = new StringContent(jsonString, Encoding.UTF8, MimeTypes.ApplicationJson);
        var response = await _httpClient.PostAsync(urlString, requestContent);

        return await response.Content.ReadAsStringAsync();
    }

    #endregion
}