如何在 C# 中获取 facebook 签名的请求

本文关键字:请求 facebook 获取 | 更新日期: 2023-09-27 18:32:57

我是Facebook应用程序的新手。我正在尝试创建一个MVC 4应用程序,并将Facebook应用程序作为我的项目模板。我正在尝试捕获创建页面选项卡的页面ID,并且以某种方式得到了它。我的问题是当有人访问我的应用程序时,我想知道他们查看页面选项卡的页面 ID。我已经搜索了很多,我知道我必须为此使用FacebookSignedRequest。但是这门课对我来说不可用。

提前感谢任何帮助。

如何在 C# 中获取 facebook 签名的请求

如果只是尝试从 Facebook 解析 signed_request 参数,则可以使用以下 C# 代码执行此操作。

此代码还使用您自己的app_secret参数验证哈希,以确保signed_request源自 Facebook。

public static string DecodeSignedRequest(string signed_request)
{
    try
    {
        if (signed_request.Contains("."))
        {
            string[] split = signed_request.Split('.');
            string signatureRaw = FixBase64String(split[0]);
            string dataRaw = FixBase64String(split[1]);
            // the decoded signature
            byte[] signature = Convert.FromBase64String(signatureRaw);
            byte[] dataBuffer = Convert.FromBase64String(dataRaw);
            // JSON object
            string data = Encoding.UTF8.GetString(dataBuffer);
            byte[] appSecretBytes = Encoding.UTF8.GetBytes(app_secret);
            System.Security.Cryptography.HMAC hmac = new System.Security.Cryptography.HMACSHA256(appSecretBytes);
            byte[] expectedHash = hmac.ComputeHash(Encoding.UTF8.GetBytes(split[1]));
            if (expectedHash.SequenceEqual(signature))
            {
                return data;
            }
        }
    }
    catch
    {
        // error
    }
    return "";
}
private static string FixBase64String(string str)
{
    while (str.Length % 4 != 0)
    {
        str = str.PadRight(str.Length + 1, '=');
    }
    return str.Replace("-", "+").Replace("_", "/");
}

我所要做的就是创建一个Facebook客户端对象,并使用应用程序密钥调用ParseSignedRequest方法。

var fb = new FacebookClient();
dynamic signedRequest = fb.ParseSignedRequest(appSecret, Request.Form["signed_request"]);

这返回了一个 Json 对象,我们必须使用 JObject.Parse 解析该对象