简体   繁体   English

在phonegap应用程序上使用Twitter登录

[英]Login with Twitter on phonegap app

I'm trying to implement the login action using the twitter acount in my cordova app. 我正在尝试使用我的cordova应用程序中的twitter帐户实现登录操作。 I have found a script using Childbrowser.js file to do it but it's not supported anymore so that I am trying to do it using the inappBrowser plugin instead of the childbrowser. 我找到了一个使用Childbrowser.js文件的脚本来执行此操作,但它不再受支持,因此我尝试使用inappBrowser插件而不是inappBrowser来执行此操作。 I succeeded in opening the login interface but after the login it redirect me to a web page. 我成功打开了登录界面,但登录后它将我重定向到了一个网页。 How can I redirect to my html local page? 如何重定向到我的html本地页面? can I get ignore the redirect url and just get the access token? 我可以忽略重定向网址并获取访问令牌吗? this is the code that I am using: 这是我正在使用的代码:

<!DOCTYPE html>
 <html>
<head>
    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <meta charset="utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
        <script type="text/javascript">

            function onBodyLoad(){
                document.addEventListener("deviceready", onDeviceReady, false);
            }

        function onDeviceReady() {

            var root = this;
            //var cb = new Codebird;
            var cb = window.open();
            if(!localStorage.getItem(twitterKey)){

                $("#loginBtn").show();
                $("#logoutBtn").hide();
            }
            else {
                return ('here test');
                $("#loginBtn").hide();
                $("#logoutBtn").show();
            }

            if (cb != null) {
                cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
                cb.addEventListener('loadstop', function(event) { onOpenExternal();});
                cb.addEventListener('exit', function(event) { onCloseBrowser() });



            }
        }

        function onCloseBrowser() {
            alert('onCloseBrowser');
            console.log("onCloseBrowser!");
        }

        function locChanged(loc) {
            alert('locChanged');
            console.log("locChanged!");
        }

        function onOpenExternal() {
            alert('onOpenExternal');
            console.log("onOpenExternal!");
        }

            </script>
        <!--Below is the code for twitter-->
        <script>
            // GLOBAL VARS
            var oauth; // It Holds the oAuth data request
            var requestParams; // Specific param related to request
            var options = {
                consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
                consumerSecret: 'xxxxxx', // YOUR Twitter CONSUMER_SECRET
                callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
            var twitterKey = "twtrKey"; // This key is used for storing Information related


        var Twitter = {
            init:function(){
                // Apps storedAccessData , Apps Data in Raw format
                var storedAccessData, rawData = localStorage.getItem(twitterKey);
                // here we are going to check whether the data about user is already with us.
                if(localStorage.getItem(twitterKey) !== null){
                    // when App already knows data
                    storedAccessData = JSON.parse(rawData); //JSON parsing
                    //options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
                    options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin

                    // javascript OAuth take care of everything for app we need to provide just the options
                    oauth = OAuth(options);
                    oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
                              function(data) {
                              var entry = JSON.parse(data.text);
                              console.log("USERNAME: " + entry.screen_name);
                              }
                              );
                }
                else {
                    // we have no data for save user
                    oauth = OAuth(options);
                    oauth.get('https://api.twitter.com/oauth/request_token',
                              function(data) {
                              requestParams = data.text;
                              cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text); // This opens the Twitter authorization / sign in page
                              cb.addEventListener('loadstop', function(loc){alert('stop: ' + loc.url);
                                                  //       Twitter.success(loc);
                                                  });
                              },
                              function(data) {
                              console.log("ERROR: "+data);
                              }
                              );
                }
            },
            /*
             When ChildBrowser's URL changes we will track it here.
             We will also be acknowledged was the request is a successful or unsuccessful
             */
            success:function(loc){
                              alert('ok entred');
                // Here the URL of supplied callback will Load

                /*
                 Here Plugin will check whether the callback Url matches with the given Url
                 */
                if (loc.indexOf("http://127.0.0.1:81/?") >= 0) {

                    // Parse the returned URL
                    var index, verifier = '';
                    var params = loc.substr(loc.indexOf('?') + 1);

                    params = params.split('&');
                    for (var i = 0; i < params.length; i++) {
                        var y = params[i].split('=');
                        if(y[0] === 'oauth_verifier') {
                            verifier = y[1];
                        }
                    }

                    // Here we are going to change token for request with token for access

                    /*
                     Once user has authorised us then we have to change the token for request with token of access
                     here we will give data to localStorage.
                     */
                    oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
                              function(data) {
                              var accessParams = {};
                              var qvars_tmp = data.text.split('&');
                              for (var i = 0; i < qvars_tmp.length; i++) {
                              var y = qvars_tmp[i].split('=');
                              accessParams[y[0]] = decodeURIComponent(y[1]);
                              }

                              $('#oauthStatus').html('<span style="color:green;">Success!</span>');
                              $('#stage-auth').hide();
                              $('#stage-data').show();
                              oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);

                              // Saving token of access in Local_Storage
                              var accessData = {};
                              accessData.accessTokenKey = accessParams.oauth_token;
                              accessData.accessTokenSecret = accessParams.oauth_token_secret;

                              // Configuring Apps LOCAL_STORAGE
                              console.log("TWITTER: Storing token key/secret in localStorage");
                              localStorage.setItem(twitterKey, JSON.stringify(accessData));

                              oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
                                        function(data) {
                                        var entry = JSON.parse(data.text);
                                        console.log("TWITTER USER: "+entry.screen_name);
                                        $("#welcome").show();
                                        document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
                                        successfulLogin();
                                        // Just for eg.
                                        app.init();
                                        },
                                        function(data) {
                                        console.log("ERROR: " + data);
                                        }
                                        );

                              // Now we have to close the child browser because everthing goes on track.

                              window.plugins.childBrowser.close();
                              },
                              function(data) {
                              alert('rr');
                              console.log(data);


                              }
                              );
                }
                else {
                    // Just Empty
                }
            },
            tweet:function(){
                var storedAccessData, rawData = localStorage.getItem(twitterKey);

                storedAccessData = JSON.parse(rawData); // Paring Json
                options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
                options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login

                // javascript OAuth will care of else for app we need to send only the options
                oauth = OAuth(options);
                oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
                          function(data) {
                          var entry = JSON.parse(data.text);
                          Twitter.post();
                          }
                          );
            },
            /*
             We now have the data to tweet
             */
            post:function(){
                var theTweet = $("#tweet").val(); // You can change it with what else you likes.

                oauth.post('https://api.twitter.com/1/statuses/update.json',
                           { 'status' : theTweet,  // javascript OAuth encodes this
                           'trim_user' : 'true' },
                           function(data) {
                           var entry = JSON.parse(data.text);
                           console.log(entry);

                           // just for eg.
                           done();
                           },
                           function(data) {
                           console.log(data);
                           }
                           );
            }

        }

        function done(){
            $("#tweet").val('');
        }


        function successfulLogin(){
            $("#loginBtn").hide();
            $("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();

        }

        function logOut(){
            //localStorage.clear();
            window.localStorage.removeItem(twitterKey);
            document.getElementById("welcome").innerHTML="Please Login to use this app";
            $("#loginBtn").show();
            $("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();

        }

            </script>
        <!--Code for Twitter ends here-->
        </head>
<body onload="onBodyLoad()">

    <h4>Oodles Twitter App</h4>

    <table border="1">
        <tr>
            <th>Login using Twitter</th>
            <th>
                <button id="loginBtn" onclick="Twitter.init()">Login</button>
                <button id="logoutBtn" onclick="logOut();">Logout</button>
            </th>
        </tr>
        <tr id="tweetText" style="display:none;">
            <td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
        </tr>
        <tr id="tweetBtn" style="display:none;">
            <td colspan="2" align="right">
                <button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
            </td>
        </tr>
        <tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
    </table>



</body>

Actually there is error in your code you have to fix it: the https://api.twitter.com/1/account/verify_credentials.json?skip_status=true' is no more used change it to 1.1. 实际上你的代码中有错误你必须修复它: https://api.twitter.com/1/account/verify_credentials.json?skip_status=true'https://api.twitter.com/1/account/verify_credentials.json?skip_status=true'不再使用将其更改为1.1。 also change the way you close your inappbrowser. 也改变你关闭inappbrowser的方式。 this code works for me try it: 这段代码适合我试试:

<!DOCTYPE html>
<html>
<head>
    <title></title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no;" />
    <meta charset="utf-8">
        <script type="text/javascript" charset="utf-8" src="cordova.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/jquery-2.1.1.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/codebird.js"></script>
        <script type="text/javascript" charset="utf-8" src="js/jsOAuth-1.3.1.js"></script>
        <script type="text/javascript">

            function onBodyLoad(){
                document.addEventListener("deviceready", onDeviceReady, false);
            }

        function onDeviceReady() {

            var root = this;
            //var cb = new Codebird;
            var cb = window.open();
            if(!localStorage.getItem(twitterKey)){

                $("#loginBtn").show();
                $("#logoutBtn").hide();
            }
            else {
                retiurn ('hhhh');
                $("#loginBtn").hide();
                $("#logoutBtn").show();
            }

            if (cb != null) {
                cb.addEventListener('loadstart', function(event) { onOpenExternal(); });
                cb.addEventListener('loadstop', function(event) { onOpenExternal();});
                cb.addEventListener('exit', function(event) { onCloseBrowser() });



            }
        }

        function onCloseBrowser() {
            alert('onCloseBrowser');
            console.log("onCloseBrowser!");
        }

        function locChanged(loc) {
            alert('locChanged');
            console.log("locChanged!");
        }

        function onOpenExternal() {
            alert('onOpenExternal');
            console.log("onOpenExternal!");
        }

            </script>
        <!--Below is the code for twitter-->
        <script>
            // GLOBAL VARS
            var oauth; // It Holds the oAuth data request
            var requestParams; // Specific param related to request
            var options = {
                consumerKey: 'xxxxx', // YOUR Twitter CONSUMER_KEY
                consumerSecret: 'xxxxx', // YOUR Twitter CONSUMER_SECRET
                callbackUrl: "http://127.0.0.1:81/" }; // YOU have to replace it on one more Place
        var twitterKey = "twtrKey"; // This key is used for storing Information related


        var Twitter = {
            init:function(){
                // Apps storedAccessData , Apps Data in Raw format
                var storedAccessData, rawData = localStorage.getItem(twitterKey);
                // here we are going to check whether the data about user is already with us.
                if(localStorage.getItem(twitterKey) !== null){
                    // when App already knows data
                    storedAccessData = JSON.parse(rawData); //JSON parsing
                    //options.accessTokenKey = storedAccessData.accessTokenKey; // data will be saved when user first time signin
                    options.accessTokenSecret = storedAccessData.accessTokenSecret; // data will be saved when user first first signin

                    // javascript OAuth take care of everything for app we need to provide just the options
                    oauth = OAuth(options);
                    oauth.get('https://api.twitter.com/1/account/verify_credentials.json?skip_status=true',
                              function(data) {
                              var entry = JSON.parse(data.text);
                              console.log("USERNAME: " + entry.screen_name);
                              }
                              );
                }
                else {
                    // we have no data for save user
                    oauth = OAuth(options);
                    oauth.get('https://api.twitter.com/oauth/request_token',
                              function(data) {
                              requestParams = data.text;
                              cb=window.open('https://api.twitter.com/oauth/authorize?'+data.text,'_blank', 'location=no'); // This opens the Twitter authorization / sign in page
                              cb.addEventListener('loadstop', function(loc){//alert('stop: ' + loc.url);
                                                  Twitter.success(loc);
                                                  });
                              },
                              function(data) {
                              console.log("ERROR: "+data);
                              }
                              );
                }
            },
            /*
             When ChildBrowser's URL changes we will track it here.
             We will also be acknowledged was the request is a successful or unsuccessful
             */
            success:function(loc){
               // alert(loc.url);
                // Here the URL of supplied callback will Load

                /*
                 Here Plugin will check whether the callback Url matches with the given Url
                 */
                if (loc.url.indexOf("http://127.0.0.1:81/?") >-1) {



                    // Parse the returned URL
                    var index, verifier = '';
                    var params = loc.url.substr(loc.url.indexOf('?') + 1);

                    params = params.split('&');
                    for (var i = 0; i < params.length; i++) {
                        var y = params[i].split('=');
                        if(y[0] === 'oauth_verifier') {
                            verifier = y[1];
                        }
                    }

                    // Here we are going to change token for request with token for access

                    /*
                     Once user has authorised us then we have to change the token for request with token of access
                     here we will give data to localStorage.
                     */

                    oauth.get('https://api.twitter.com/oauth/access_token?oauth_verifier='+verifier+'&'+requestParams,
                              function(data) {
                              var accessParams = {};
                              var qvars_tmp = data.text.split('&');
                              for (var i = 0; i < qvars_tmp.length; i++) {
                              var y = qvars_tmp[i].split('=');
                              accessParams[y[0]] = decodeURIComponent(y[1]);
                              }
                              // alert(verifier)

                              $('#oauthStatus').html('<span style="color:green;">Success!</span>');
                              $('#stage-auth').hide();
                              $('#stage-data').show();
                              oauth.setAccessToken([accessParams.oauth_token, accessParams.oauth_token_secret]);

                              // Saving token of access in Local_Storage
                              var accessData = {};
                              accessData.accessTokenKey = accessParams.oauth_token;
                              accessData.accessTokenSecret = accessParams.oauth_token_secret;

                              // Configuring Apps LOCAL_STORAGE
                              console.log("TWITTER: Storing token key/secret in localStorage");

                              localStorage.setItem(twitterKey, JSON.stringify(accessData));


                              oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
                                        function(data) {
                                        // alert('key'+twitterKey);
                                        var entry = JSON.parse(data.text);
                                        console.log("TWITTER USER: "+entry.screen_name);
                                        $("#welcome").show();
                                        document.getElementById("welcome").innerHTML="welcome " + entry.screen_name;
                                        successfulLogin();
                                        // Just for eg.
                                        app.init();
                                        },
                                        function(data) {
                                        console.log("ERROR: " + data);
                                        }
                                        );

                              // Now we have to close the child browser because everthing goes on track.

                              cb.close();
                              },
                              function(data) {
                             // alert('rr');
                              console.log(data);


                              }
                              );
                }
                else {
                    // Just Empty
                }
            },
            tweet:function(){
                var storedAccessData, rawData = localStorage.getItem(twitterKey);

                storedAccessData = JSON.parse(rawData); // Paring Json
                options.accessTokenKey = storedAccessData.accessTokenKey; // it will be saved on first signin
                options.accessTokenSecret = storedAccessData.accessTokenSecret; // it will be save on first login

                // javascript OAuth will care of else for app we need to send only the options
                oauth = OAuth(options);
                oauth.get('https://api.twitter.com/1.1/account/verify_credentials.json?skip_status=true',
                          function(data) {
                          var entry = JSON.parse(data.text);
                          Twitter.post();
                          }
                          );
            },
            /*
             We now have the data to tweet
             */
            post:function(){
                var theTweet = $("#tweet").val(); // You can change it with what else you likes.

                oauth.post('https://api.twitter.com/1.1/statuses/update.json',
                           { 'status' : theTweet,  // javascript OAuth encodes this
                           'trim_user' : 'true' },
                           function(data) {
                           var entry = JSON.parse(data.text);
                           console.log(entry);

                           // just for eg.
                           done();
                           },
                           function(data) {
                           console.log(data);
                           }
                           );
            }

        }

        function done(){
            $("#tweet").val('');
        }


        function successfulLogin(){
            $("#loginBtn").hide();
            $("#logoutBtn,#tweet,#tweeter,#tweetBtn,#tweetText").show();

        }

        function logOut(){
            //localStorage.clear();
            window.localStorage.removeItem(twitterKey);
            document.getElementById("welcome").innerHTML="Please Login to use this app";
            $("#loginBtn").show();
            $("#logoutBtn,#tweet,#tweeter,#tweetText,#tweetBtn").hide();

        }

            </script>
        <!--Code for Twitter ends here-->
        </head>
<body onload="onBodyLoad()">

    <h4>Oodles Twitter App</h4>

    <table border="1">
        <tr>
            <th>Login using Twitter</th>
            <th>
                <button id="loginBtn" onclick="Twitter.init()">Login</button>
                <button id="logoutBtn" onclick="logOut();">Logout</button>
            </th>
        </tr>
        <tr id="tweetText" style="display:none;">
            <td colspan="2"><textarea id="tweet" style="display:none;"></textarea></td>
        </tr>
        <tr id="tweetBtn" style="display:none;">
            <td colspan="2" align="right">
                <button id="tweeter" onclick="Twitter.tweet();" style="display:none">Tweet</button>
            </td>
        </tr>
        <tr><td colspan="2"><div id="welcome">Please Login to use this app</div></td></tr>
    </table>



</body>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM