2014-06-17 94 views
3

我越來越「webView:didFailLoadWithError -1004:無法連接到服務器」錯誤,同時接受谷歌加認證之前獲取配置文件數據。這些代碼在以前正常工作。現在我面臨着這些錯誤。不知道爲什麼我無法connect.Please幫助我擺脫這些錯誤。下面是我的代碼爲iPhone集成谷歌加Phonegap(3.4.0)爲iOS。webView:didFailLoadWithError -1004:無法連接到服務器,而連接谷歌plus在Phonegap ios

var googleapi = { 
     //alert('ready'); 
     authorize: function(options) { 
      var deferred = $.Deferred(); 

     //Build the OAuth consent page URL 
     var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({ 
      client_id: options.client_id, 
      redirect_uri: options.redirect_uri, 
      response_type: 'code', 
      scope: options.scope 
     }); 

     //Open the OAuth consent page in the InAppBrowser 
     var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=yes'); 


     $(authWindow).on(' ', function(e) { 
      var url = e.originalEvent.url; 
      var code = /\?code=(.+)$/.exec(url); 
      var error = /\?error=(.+)$/.exec(url); 

      if (code || error) { 
       //Always close the browser when match is found 
       authWindow.close(); 
      } 

      if (code) { 
       //Exchange the authorization code for an access token 
       $.post('https://accounts.google.com/o/oauth2/token', { 
        code: code[1], 
        client_id: options.client_id, 
        client_secret: options.client_secret, 
        redirect_uri: options.redirect_uri, 
        grant_type: 'authorization_code' 
       }).done(function(data) { 
        deferred.resolve(data); 

        $("#loginStatus").html('Name: ' + data.given_name); 
       }).fail(function(response) { 
        deferred.reject(response.responseJSON); 
       }); 
      } else if (error) { 
       //The user denied access to the app 
       deferred.reject({ 
        error: error[1] 
       }); 
      } 
     }); 

     return deferred.promise(); 
    } 
    }; 



    var accessToken; 


    function callGoogle() 

    { 

    alert('starting'); 
    googleapi.authorize({ 
         client_id: 'CLIENT_ID', 
         client_secret: 'CLIENT_SECRET', 
         redirect_uri: 'http://localhost', 
         scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' 
         }).done(function(data) { 
           accessToken=data.access_token; 
           alert(accessToken); 
           // $loginStatus.html('Access Token: ' + data.access_token); 
           console.log(data.access_token); 

           getDataProfile(); 


           }); 

} 
function getDataProfile() 
{ 
    var term=null; 
    //accessToken=null; 
    //alert("getting user data="+accessToken); 
    $.ajax({ 
      url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken, 
      type:'GET', 
      data:term, 
      dataType:'json', 
      error:function(jqXHR,text_status,strError){ 
      }, 
      success:function(data) 
      { 
      var item; 
      var dat=data.properties; 
      alert("first name="+data.given_name+" last name="+data.family_name+" gender="+data.gender+" email="+data.email); 
      console.log(data); 

      } 
      }); 

} 
+0

即使我在谷歌加iOS登錄相同的問題。如果你得到它,請發佈解決方案。 – Rayon

+0

試試這個答案http://stackoverflow.com/questions/23930744/how-to-use-google-login-api-with-cordova-phonegap/23931392#23931392 –

回答

1

將此代碼添加到一個js文件幷包含在您的項目中。當你想在按鈕上訪問谷歌登錄API點擊呼叫function callGoogle()休息將由此代碼完成。不要忘記添加您的客戶端ID和Client_Secret密鑰。它爲我工作很好。你需要inappbrowser cordova插件。

 var googleapi = { 
     authorize: function(options) { 
      var deferred = $.Deferred(); 

      //Build the OAuth consent page URL 
      var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({ 
       client_id: options.client_id, 
       redirect_uri: options.redirect_uri, 
       response_type: 'code', 
       scope: options.scope 

      }); 

      //Open the OAuth consent page in the InAppBrowser 
      var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no'); 

      //The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob" 
      //which sets the authorization code in the browser's title. However, we can't 
      //access the title of the InAppBrowser. 
      // 
      //Instead, we pass a bogus redirect_uri of "http://localhost", which means the 
      //authorization code will get set in the url. We can access the url in the 
      //loadstart and loadstop events. So if we bind the loadstart event, we can 
      //find the authorization code and close the InAppBrowser after the user 
      //has granted us access to their data. 
      $(authWindow).on('loadstart', function(e) { 
       var url = e.originalEvent.url; 
       var code = /\?code=(.+)$/.exec(url); 
       var error = /\?error=(.+)$/.exec(url); 

       if (code || error) { 
        //Always close the browser when match is found 
        authWindow.close(); 
       } 

       if (code) { 
        //Exchange the authorization code for an access token 
        $.post('https://accounts.google.com/o/oauth2/token', { 
         code: code[1], 
         client_id: options.client_id, 
         client_secret: options.client_secret, 
         redirect_uri: options.redirect_uri, 
         grant_type: 'authorization_code' 
        }).done(function(data) { 
         deferred.resolve(data); 

         $("#loginStatus").html('Name: ' + data.given_name); 
        }).fail(function(response) { 
         deferred.reject(response.responseJSON); 
        }); 
       } else if (error) { 
        //The user denied access to the app 
        deferred.reject({ 
         error: error[1] 
        }); 
       } 
      }); 

      return deferred.promise(); 
     } 
    }; 
    var accessToken; 
    var UserData=null; 

    function callGoogle() 
    { 

    // alert('starting'); 
     googleapi.authorize({ 
          client_id: 'client_id', 
          client_secret: 'Client_Secret', 
          redirect_uri: 'http://localhost', 
          scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email' 
          }).done(function(data) { 
            accessToken=data.access_token; 
            // alert(accessToken); 
            // $loginStatus.html('Access Token: ' + data.access_token); 
            console.log(data.access_token); 
    console.log(JSON.stringify(data)); 
            getDataProfile(); 


            }); 

    } 
    // This function gets data of user. 
    function getDataProfile() 
    { 
     var term=null; 
     // alert("getting user data="+accessToken); 
     $.ajax({ 
       url:'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token='+accessToken, 
       type:'GET', 
       data:term, 
       dataType:'json', 
       error:function(jqXHR,text_status,strError){ 
       }, 
       success:function(data) 
       { 
       var item; 

       console.log(JSON.stringify(data)); 
// Save the userprofile data in your localStorage. 
       localStorage.gmailLogin="true"; 
       localStorage.gmailID=data.id; 
       localStorage.gmailEmail=data.email; 
       localStorage.gmailFirstName=data.given_name; 
       localStorage.gmailLastName=data.family_name; 
       localStorage.gmailProfilePicture=data.picture; 
       localStorage.gmailGender=data.gender; 
       } 
       }); 
    disconnectUser(); 
    } 
    function disconnectUser() { 
     var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token='+accessToken; 

     // Perform an asynchronous GET request. 
     $.ajax({ 
     type: 'GET', 
     url: revokeUrl, 
     async: false, 
     contentType: "application/json", 
     dataType: 'jsonp', 
     success: function(nullResponse) { 
      // Do something now that user is disconnected 
      // The response is always undefined. 
      accessToken=null; 
      console.log(JSON.stringify(nullResponse)); 
      console.log("-----signed out..!!----"+accessToken); 
     }, 
     error: function(e) { 
      // Handle the error 
      // console.log(e); 
      // You could point users to manually disconnect if unsuccessful 
      // https://plus.google.com/apps 
     } 
     }); 
    } 
+0

男人...我找了一個工作腳本,因爲天 - 很多很多謝謝! 但是我如何繼續並從管理api中檢索ID和屬性?我想獲得實時用戶。但是我需要id和propertys,而不是用變量替換analytics.api中的鏈接。 – Sithys

1

您可以使用下面的代碼獲取訪問令牌和用戶配置文件數據。 只需將您的按鈕事件附加到「onGooglePlusLogin」功能並替換client_id和screte_id即可。

我已經在PhonePhone 3.4.0項目的iPhone和Android設備上進行了測試。

乾杯!

var GoogleLogin = function (id, secret) { 
    var clientId = id; 
    var clientSecret = secret; 
    var accessToken = {}; 
    var authWindow = null; 
    var endSignin = {}; 

    var openAuthWindow = function() { 
     var urlAuth = "https://accounts.google.com/o/oauth2/auth?" + "scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&" + "redirect_uri=http://localhost&" + "response_type=code&" + "client_id=" + clientId; 


     // Open InAppBrowser to get authorization code 
     authWindow = window.open(urlAuth, '_blank', 'location=yes,closebuttoncaption=Done'); 
     authWindow.addEventListener('loadstart', parseRedirectUrl); 

    }; 

    var parseRedirectUrl = function (e) { 
     var url = e.url; 
     var thereIsCode = url.indexOf("code="); 
     var thereIsError = url.indexOf("error="); 

     if (thereIsCode != -1) { 
      authWindow.close(); 
      var toMatch = "code=([^&#]*)"; 
      var regex = new RegExp(toMatch); 
      var result = regex.exec(url); 
      if (result != null) { 
       var code = result[1]; 
       exchangeCodeForTokens(code); 
      } 
     } else if (thereIsError != -1) { 
      authWindow.close(); 
      localStorage["accessToken"] = null; 
      endSignin(-1); 
     } 
    }; 

    var exchangeCodeForTokens = function (code) { 
     var dataQuery = "code=" + code + "&" + "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "redirect_uri=http://localhost&" + "grant_type=authorization_code"; 

     requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackTokens); 
    }; 

    var callBackTokens = function (resp) { 
     var tokensResp = eval('(' + resp + ')'); 

     if (tokensResp.access_token) { 
      localStorage["accessToken"] = tokensResp.access_token; 
      localStorage["refreshToken"] = tokensResp.refresh_token; 
      localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in; 

      accessToken = tokensResp.access_token; 
      endSignin(accessToken); 
     } else { 
      accessToken = null; 
      localStorage["accessToken"] = null; 
      endSignin(-1); 
     } 
    }; 

    var getAccessToken = function (refreshToken) { 
     var dataQuery = "client_id=" + clientId + "&" + "client_secret=" + clientSecret + "&" + "refresh_token=" + refreshToken + "&" + "grant_type=refresh_token"; 

     requestTokens("https://accounts.google.com/o/oauth2/token", dataQuery, callBackRefreshToken); 
    }; 

    var callBackRefreshToken = function (resp) { 
     var tokensResp = eval('(' + resp + ')'); 

     if (tokensResp.access_token) { 
      localStorage["accessToken"] = tokensResp.access_token; 
      localStorage["refreshTime"] = (new Date()).getTime() + 1000 * tokensResp.expires_in; 

      accessToken = tokensResp.access_token; 
      endSignin(accessToken); 
     } else { 
      accessToken = null; 
      localStorage["accessToken"] = null; 
      endSignin(-1); 
     } 
    }; 

    var requestTokens = function (url, data, callback) { 
     var xmlreq = new XMLHttpRequest(); 

     xmlreq.onreadystatechange = function() { 
      if (xmlreq.readyState == 4) { 
       callback(xmlreq.responseText); 
      } 
     }; 
     xmlreq.open("POST", url, true); 
     xmlreq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
     xmlreq.send(data); 
    }; 

    var isLoggedIn = function (callback) { 
     endSignin = callback; 
     accessToken = localStorage["accessToken"]; 

     if (accessToken == "null") { 
      accessToken = null; 
     } 

     if (accessToken !== null && typeof (accessToken) !== 'undefined') { 
      var refreshTime = localStorage["refreshTime"]; 
      var refreshToken = localStorage["refreshToken"]; 
      var currentTime = (new Date()).getTime(); 

      if (currentTime < refreshTime) { 
       endSignin(accessToken); 
      } else { 
       getAccessToken(refreshToken); 
      } 
     } else { 
      endSignin(-1); 
     } 
    }; 

    var startSignin = function (callbackEnd) { 
     endSignin = callbackEnd; 
     openAuthWindow(); 
    }; 

    var logOut = function() { 
     accessToken = null; 
     localStorage["accessToken"] = null; 
     localStorage["refreshToken"] = null; 
    }; 

    return { 
     startSignin: startSignin, 
     isLoggedIn: isLoggedIn, 
     logOut: logOut 
    }; 
}; 

function onGooglePlusLogin() { 
    var clientId = "YOUR_CLIENT_ID"; 
    var clientSecret = "SECRET_ID"; 

    // Create login object and initialize it with your app client id and secret 
    var gl = new GoogleLogin(clientId, clientSecret); 
    gl.startSignin(endLogin); 
} 

function endLogin(result) { 
    if (result === -1) { 
     // Login was not successful :(
     alert('Google Login failed!'); 
    } else { 
     // If successful login, use access_token to get profile name 
     getProfileData(result); 
    } 
} 

function getProfileData(result) { 
    if (result !== null && typeof (result) !== 'undefined') { 
     var urlAPI = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + result; 

     var xmlreq = new XMLHttpRequest(); 
     xmlreq.onreadystatechange = function() { 
      if (xmlreq.readyState == 4 && xmlreq.status == 200) { 
       var response = eval('(' + xmlreq.responseText + ')'); 
       if (response && response.email && response.id) { 
        // Profile data 
        alert(JSON.stringify(response)); 
       } else { 
        alert("Google Login failed!"); 
       } 
      } 
     }; 
     xmlreq.open("GET", urlAPI, true); 
     xmlreq.send(); 
    } 
} 
+0

謝謝Mayur,我也遭受同樣的問題,你的答案解決了這個問題。感謝代碼片段。 – Solution