Hashing fields for Facebook Conversion API in C#

Viewed 1971

I have successfully called Facebook Conversion API in C# using hardcoded sample data. Code below:

 HttpClient httpClient = new HttpClient();
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer",<MyToken>);

            Int64 unitTimeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
            var fbData= new
            {
                data = new[] {
        new  {
            event_name="Purchase",
            event_time = 1616695650,
            action_source= "email",
            user_data = new
            {
                 em= "7b17fb0bd173f625b58636fb796407c22b3d16fc78302d79f0fd30c2fc2fc068",
                ph= ""
            },
            custom_data = new
            {
                currency= "USD",
                value= "142.52"
            }

        }
            }
            };



            var postResponse = await httpClient.PostAsJsonAsync("https://graph.facebook.com/v10.0/<MyPixelID/events", fbData);

            postResponse.EnsureSuccessStatusCode();

However when using 'real' data, Facebook requires some types to be hashed using SHA-256 (e.g. email):

https://developers.facebook.com/docs/marketing-api/conversions-api/parameters/customer-information-parameters#normalize-and-hash

I cannot work out how to do this in ASP.NET. I've tried using the below function but this didn't seem to work:

 public static string GenerateSHA256(string input)
        {
            var bytes = Encoding.Unicode.GetBytes(input);
            using (var hashEngine = SHA256.Create())
            {
                var hashedBytes = hashEngine.ComputeHash(bytes, 0, bytes.Length);
                var sb = new StringBuilder();
                foreach (var b in hashedBytes)
                {
                    var hex = b.ToString("x2");
                    sb.Append(hex);
                }
                return sb.ToString();
            }
        }

On a side note, how would Facebook read the data if I did hash it using SHA-256 as I understood this to be irreversible?

1 Answers

Issue is with this line

var bytes = Encoding.Unicode.GetBytes(input);

which is UTF16. You should use UTF8.

var bytes = Encoding.UTF8.GetBytes(input);

With regards to your side question, here is what facebook says https://developers.facebook.com/docs/marketing-api/audiences/guides/custom-audiences#hash

As the owner of your business's data, you are responsible for creating and managing this data. This includes information from your Customer Relationship Management (CRM) systems. To create audiences, you must share your data in a hashed format to maintain privacy. See Hashing and Normalizing Data. Facebook compares this with our hashed data to see if we should add someone on Facebook to your ad's audience.

Related