2015年12月30日 星期三

[Qt] JavaScript / Qt 與Facebook Login SDK 使用

在完成這個專案之前,花了很多時間在research Facebook Login SDK,說實話實在是有點難搞懂

畢竟要透過Qt來使用JavaScript,不是這麼多範例可以參考,所以後來就改變策略-------

在html上寫JS然後透過QWebView+QUrl來呼叫網頁達成目的!

需要知道的

1.JavaScript如何轉址

2.JavaScript的FB login SDK流程如何

3.如何取得response與accessToken(最重要!App通行證)

//

第一個網址:

我們需要自動轉址到Facebook Login畫面

第二個網址:

Login成功以後,需要轉址到第二個網址(如果都轉址到第一個網址,會造成無窮迴圈)

取得accessToken

第三個網址:

為了讓Qt取得accessToken我們必須要在網址上面動手腳,

也就是帶accessToken在網址上,因此第二網址再轉址到第三網址


以上為說明
-----------------------------------------------------------------------------------------------------------------------

1.test1.html

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login</title>
<meta charset="UTF-8">
</head>
<body>
<p>測試文字</p>
<script>

var url2 = 'https://www.facebook.com/dialog/oauth?client_id=你的App ID&scope=email,user_birthday&redirect_uri=第二網址';
setTimeout("location.href=url2",1);//轉址目的地,自動轉址秒數
console.log('test2');

</script>
<div id="status">
</div>

</body>
</html>

2.test2.html

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login JavaScript Example</title>
<meta charset="UTF-8">
</head>
<body>
<p>123</p>
<script>

<!--開頭initial-->
var url;


  window.fbAsyncInit = function() {
    // init the FB JS SDK
  FB.init({
    appId      : '你的ID',
    cookie     : true,  // enable cookies to allow the server to access
                        // the session
    xfbml      : true,  // parse social plugins on this page
    version    : 'v2.2' // use version 2.2
  });


  FB.login(function(response) {
  console.log('in FB.login');
    if (response.authResponse) {
     console.log('Welcome!  Fetching your information.... ');
     FB.api('/me', function(response) {
       console.log('Good to see you, ' + response.name + '.');
     });
    } else {
     console.log('User cancelled login or did not fully authorize.');
    }
});

  // This is called with the results from from FB.getLoginStatus().
  function statusChangeCallback(response) {
    console.log('in function: statusChangeCallback');
    console.log(response);
    // The response object is returned with a status field that lets the
    // app know the current login status of the person.
    // Full docs on the response object can be found in the documentation
    // for FB.getLoginStatus().
    if (response.status === 'connected') {
      // Logged into your app and Facebook.
 var uid = response.authResponse.userID;
      var accessToken = response.authResponse.accessToken;
 console.log(accessToken);
 //alert(accessToken);

testAPI(response);
 //document.write(accessToken);
 //testAPI(response);
 document.getElementById('status').innerHTML = 'Entry success';
    } else if (response.status === 'not_authorized') {
      // The person is logged into Facebook, but not your app.
 FB.login();
      document.getElementById('status').innerHTML = 'Please log ' +
        'into this app.';
    } else {
      // The person is not logged into Facebook, so we're not sure if
      // they are logged into this app or not.
 console.log('in unknown');
      document.getElementById('status').innerHTML = 'facebook login failed';
    }
  }

  // This function is called when someone finishes with the Login
  // Button.  See the onlogin handler attached to it in the sample
  // code below.
  function checkLoginState() {
    console.log('in checkLoginState');
    FB.getLoginStatus(function(response) {
      statusChangeCallback(response);
    });
  }

  FB.getLoginStatus(function(response) {
    console.log('in getLoginStatus');
    statusChangeCallback(response);
  });

  };



  // Load the SDK asynchronously
  (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'));

  // Here we run a very simple test of the Graph API after login is
  // successful.  See statusChangeCallback() for when this call is made.

  function testAPI(response) {
  /*
    console.log('Welcome!  Fetching your information.... ');
    FB.api('/me', function(response) {
      console.log('Successful login for: ' + response.name);
      document.getElementById('status').innerHTML =
        'Thanks for logging in, ' + response.name + '!';
    });
*/

var accessToken = response.authResponse.accessToken;
  url = "第三個網址(轉址的)?" + accessToken;
setTimeout("location.href=url",1);
  }

window["checkLoginState()"];
console.log('get login');
</script>



<!--
<script src="http://connect.facebook.net/zh_TW/all.js"></script>
  Below we include the Login Button social plugin. This button uses
  the JavaScript SDK to present a graphical Login button that triggers
  the FB.login() function when clicked.
-->

<!--
<fb:login-button scope="public_profile,email" onlogin="checkLoginState();">
</fb:login-button>
-->
<div id="status">
</div>

</body>
</html>

3.test3.html

<!DOCTYPE html>
<html>
<head>
<title>Facebook Login</title>
<meta charset="UTF-8">
</head>
<body>
<p>test3</p>
<script>
 //URL
    var url = location.href;
   
    //取得問號之後的值
    var temp = url.split("?");

    //將值再度分開
    var vars = temp[1].split("&");

    //一一顯示出來
    for (var i = 0; i < vars.length; i++) {
     alert(vars[i]);
    };

 

</script>
<div id="status">
</div>

</body>
</html>


可以看到test.html是轉址透過

https://www.facebook.com/dialog/oauth?

+

client_id=你申請的App ID(數字)

+

&scope=email,user_birthday(你要的權限有多少)

+

&redirect_uri=轉址一號站


第二部分則是

facebook SDK

:

// Load the SDK asynchronously
  (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'));





大概內容就是三種情況

1.connected : 已經連線,成功登入(取得accessToken)

2.unauthorized: 已經登入,但是沒有允許權限開啟(呼叫login() )

3.unknown:尚未登入(呼叫login() )

如果輸入都正確就會取得accessToken,但這時候要仍然是在網頁上面要怎樣讓Qt去取得呢?

在Qt的QWebView裡面有一個Signal--urlchanged(),這意思是甚麼呢?就是當網址有所變動時(轉

址)會發送信號,因此我們就可以透過這個signal去取得轉址後的網址(當然是有帶accessToken)

如此,就達成目的了!

*******************************************************************************

照這方法做一定會遇到無法轉址的問題

"無法xxxxx,畫布...."之類的錯誤訊息







要把你要轉址的網址(可以超過一個)放在valid OAuth redirect URL這一欄裡面,這樣才能夠正常

運作!

the END

沒有留言:

張貼留言