Facebook 帆布接入的總結


研究接入facebook也有不短的時間, 上線過幾款產品,這里把接入所有的點 都記錄一下。

1.首先進入facebook的開發者頁面,直接入口在右下角更多里面

然后注冊開發者賬號, 創建APP 選擇Facebook Canvas 

然后得到app編號 和密鑰。

2.配置Canvas 

 

 

這里添加的地址必須是 https的,而且不能是靜態頁面。

 

  <script>
        window.fbAsyncInit = function () {
            FB.init({
                appId: '830298307005763',
                xfbml: true,
                version: 'v2.3'
            });
            FB.login(function (response) {
                if (response.authResponse) {
                    // user sucessfully logged in
                    var accessToken = response.authResponse.accessToken;
                    if (accessToken)
                        window.location.href = "CallBack.aspx?accessToken=" + accessToken + "&userID=" + response.authResponse.userID + "&expiresIn=" + response.authResponse.expiresIn;
                }
            }, { scope: 'email' });
            function onLogin(response) {
                if (response.status == 'connected') {
                    FB.api('/me?fields=first_name', function (data) {
                        var welcomeBlock = document.getElementById('fb-welcome');
                        welcomeBlock.innerHTML = 'Hello, ' + data.first_name + '!';
                    });
                }
            }

            FB.getLoginStatus(function (response) {
                // Check login status on load, and if the user is
                // already logged in, go directly to the welcome message.
                if (response.status == 'connected') {
                    onLogin(response);
                } else {
                    // Otherwise, show Login dialog first.
                    FB.login(function (response) {
                        onLogin(response);
                    }, { scope: 'user_friends, email' });
                }
            });
            // ADD ADDITIONAL FACEBOOK CODE HERE
        };

        (function (d, s, id) {
            var js, fjs = d.getElementsByTagName(s)[0];
            if (d.getElementById(id)) { return; }
            js = d.createElement(s); js.id = id;
            js.src = "//connect.facebook.net/en_US/sdk.js";
            fjs.parentNode.insertBefore(js, fjs);
        } (document, 'script', 'facebook-jssdk'));


</script>
View Code

 

 在Callback頁面 引用fb的 jsSDK,然后使用頁面跳轉的方式 將accessToken傳到服務端。這一步很重要, 因為有了accessToken才可以調用FB接口換取長效證書。

  var url = "https://graph.facebook.com/oauth/access_token?grant_type=fb_exchange_token&client_id=" + app的編號 +                 
                  "&client_secret=" + app的密鑰 +
                  "&fb_exchange_token=" + accessToken;
 string responseFromServer = wc.DownloadString(url);
string access_token = "";
String[] tokens = responseFromServer.Split(new char[] { '&' });
//expires:The number of seconds until this access token expires.
foreach (string t in tokens)
{
if (t.IndexOf("access_token") != -1)
{
access_token = t.Split(new char[] { '=' })[1];
}
}

 

 

使用fb的接口就能換取長效證書,並取出來。

用在下面的代碼中,獲取用戶基本信息

   ////獲取facebook用戶基本信息
                    var url_basic = "https://graph.facebook.com/me?access_token=" + access_token;
                    string responseFromServer_basic = wc.DownloadString(url_basic);
                    string jsonStr_basic = reg.Replace(responseFromServer_basic, delegate(Match m) { return ((char)Convert.ToInt32(m.Groups[1].Value, 16)).ToString(); });

                    ////獲取facebook用戶好友信息
                    var url_friends = "https://graph.facebook.com/me/friends?access_token=" + access_token;
                    string responseFromServer_friends = wc.DownloadString(url_friends);

到這里 ,接入部分的工作基本結束了。

3.支付

可以先看fb提供的 文檔 https://developers.facebook.com/docs/games_payments

首先需要有一個產品信息頁, (我這里只做靜態定價,不做動態定價因為沒有具體需要的業務場景)

這里的內容其實還是動態的, 需要根據支付時所選擇的商品來顯示。

<!DOCTYPE html><html>
 <head prefix=
    "og: http://ogp.me/ns# 
     fb: http://ogp.me/ns/fb# 
     product: http://ogp.me/ns/product#">
<meta property="fb:app_id" content="appid"><!--2.8版后 需要加上appid-->
<meta property="og:type" content="og:product" /> <meta property="og:title" content="Friend Smash Coin" /> <meta property="og:image" content="http://www.friendsmash.com/images/coin_600.png" /> <meta property="og:description" content="Friend Smash Coins to purchase upgrades and items!" /> <meta property="og:url" content="http://www.friendsmash.com/og/coins.html" /> <meta property="product:plural_title" content="Friend Smash Coins" /> <meta property="product:price:amount" content="0.30"/> <meta property="product:price:currency" content="USD"/> <meta property="product:price:amount" content="0.20"/> <meta property="product:price:currency" content="GBP"/> </head> </html>

 

這個頁面其實就是給fb提供用戶購買的商品信息。

然后在游戲頁面的 商城里用戶選擇購買商品以后 調用 fb jsSDK的接口 

 function FacebookCreditsOrder(order_info) {
              var obj = {
                method: 'pay',
                action: 'purchaseitem',
                product: order_info.url,//產品信息頁面的地址
                request_id: order_info.pid//訂單的id,必須是唯一的
                //quantity: 1
              };

              FB.ui(obj, function (data) {

                  if (data) {
                      var parameter = {
                          "amount": data.amount,
                          "currency": data.currency,
                          "payment_id": data.payment_id,
                          "quantity": data.quantity,
                          "signed_request": data.signed_request,
                          "status": data.status
                      };
                      if (data.status == 'completed') {// 這里 只處理了支付狀態為成功的請求,其實還需要處理“等待中”的狀態
                          var url = "https://**********/FaceBookReceiveOrder.ashx?amount=" + data.amount + "&currency=" + data.currency + "&payment_id=" + data.payment_id + "&quantity=" + data.quantity + "&signed_request=" + data.signed_request + "&status=" + data.status;
                          new Request(url, { method: "GET", maxTime: 8000 })
                      .on('complete', function (e) {
                          var return_obj = JSON.parse(e.text);
                          if (return_obj.State == 1) {
                              closeMall();
                          }
                          else if (orderinfo_obj.State != 1) { }
                      }).send();
                      }
                      else { }
                  }
              });
            }

支付頁面處理:

需要使用Nuget 獲取一個 Facebook的 第三方插件。在處理加密時需要

為了安全,url里所包含的訂單信息全不使用, 而使用fb傳過來的signed_request 加密參數。這個參數里包含了訂單所需的全部信息,需要解密。

    

FacebookClient client = new FacebookClient();
client.AppId = "*******";//app編號
client.AppSecret = "*********";//app密鑰

string signed = context.Request.QueryString["signed_request"];
                object obj = new object();
                client.TryParseSignedRequest(signed, out obj);
 if (obj != null)
                {
                    if (((Facebook.JsonObject)(obj)).TryGetValue("algorithm", out objtoken))
                        payInfo.algorithm = Convert.ToString(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("amount", out objtoken))
                        payInfo.amount = Convert.ToString(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("currency", out objtoken))
                        payInfo.currency = Convert.ToString(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("issued_at", out objtoken))
                        payInfo.issued_at = Convert.ToDecimal(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("payment_id", out objtoken))
                        payInfo.payment_id = Convert.ToDecimal(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("quantity", out objtoken))
                        payInfo.quantity = Convert.ToString(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("status", out objtoken))
                        payInfo.status = Convert.ToString(objtoken);
                    if (((Facebook.JsonObject)(obj)).TryGetValue("request_id", out objtoken))
                        payInfo.request_id = Convert.ToString(objtoken);
}

 

 再根據訂單信息 處理添加商品等信息了。

這里可以根據訂單id獲取 訂單的支付情況

具體說明參考文檔 

https://developers.facebook.com/docs/games_payments/fulfillment

到這里fb的接入基本就完成了。

 

 新版的app設置頁面中默認是沒有支付的,需要開發自己添加。 

添加的時候 需要填寫公司信息,和 回調url,也就是產品信息頁的地址。

可以在測試者里添加開發測試的 數字id。這樣就可以不用付款就能測試到支付接口了。  

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM