2016-01-29 87 views
3

twitter登錄由我的應用程序使用ionic framework,我想從twitter獲取電子郵件地址,我已經要求twitter和app現在可以獲取電子郵件地址。如何從twitter獲取電子郵件地址

但以某種方式下面的代碼無法獲得電子郵件地址。

爲此,我創建了一個名爲getTwitterProfileManual的新函數,但它仍然無效。

我也閱讀了由twitter提供的文檔Doc,並建議我也通過include_email params作爲請求查詢。但仍然沒有回覆郵件地址。

serviceModule.factory('TwitterService', function ($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q, AUTH_ID) 
{ 

    var twitterKey = "STORAGE.TWITTER.KEY"; 
    var clientId = AUTH_ID.TWITTER_APP_ID; 
    var clientSecret = AUTH_ID.TWITTER_APP_SEC; 

    function storeUserToken(data) 
    { 
     window.localStorage.setItem(twitterKey, JSON.stringify(data)); 
    } 

    function getStoredToken() 
    { 
     return window.localStorage.getItem(twitterKey); 
    } 

    function createTwitterSignature(method, url, params) 
    { 
     if (!params) { 
      params = {}; 
     } 
     var token = angular.fromJson(getStoredToken()); 

     var oauthObject = { 
      oauth_consumer_key: clientId, 
      oauth_nonce: $cordovaOauthUtility.createNonce(10), 
      oauth_signature_method: "HMAC-SHA1", 
      oauth_token: token.oauth_token, 
      oauth_timestamp: Math.round((new Date()).getTime()/1000.0), 
      oauth_version: "1.0" 
     }; 
     console.log(JSON.stringify(oauthObject)); 
     var signatureObj = $cordovaOauthUtility.createSignature(method, url, oauthObject, params, clientSecret, token.oauth_token_secret); 
     $http.defaults.headers.common.Authorization = signatureObj.authorization_header; 
     console.log(JSON.stringify(signatureObj.authorization_header)); 
    } 

    return { 
     initialize: function() 
     { 
      var deferred = $q.defer(); 
      var token = getStoredToken(); 

      if (token !== null) 
      { 
       deferred.resolve(true); 
      } 
      else 
      { 
       $cordovaOauth.twitter(clientId, clientSecret).then(function (result) 
       { 
        storeUserToken(result); 
        deferred.resolve(true); 
       }, function (error) 
       { 
        deferred.reject(false); 
       }); 
      } 
      return deferred.promise; 
     }, 
     isAuthenticated: function() 
     { 
      return getStoredToken() !== null; 
     }, 
     getHomeTimeline: function() 
     { 
      var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; 
      createTwitterSignature('GET', home_tl_url); 
      return $resource(home_tl_url).query(); 
     }, 
     getTwitterProfile: function() 
     { 
      var tl_url = 'https://api.twitter.com/1.1/account/verify_credentials.json'; 
      createTwitterSignature('GET', tl_url); 
      return $resource(tl_url, {'include_email': true}).query(); 
     }, 
     getTwitterProfileManual: function() { 

      var deferred = $q.defer(); 
      var token = angular.fromJson(getStoredToken()); 

      createTwitterSignature('GET', 'https://api.twitter.com/1.1/account/verify_credentials.json'); 

      //   $http.get("https://api.twitter.com/1.1/account/verify_credentials.json") 

      $http({ 
       method: 'GET', 
       url: "https://api.twitter.com/1.1/account/verify_credentials.json", 
       params : { 'include_email': true } 
      }).success(function (result) 
      { 
       console.log(result); 
       alert('USER TIMELINE: ' + JSON.stringify(result)); 
       deferred.resolve(result); 
      }).error(function (error) 
      { 
       alert("Error: " + JSON.stringify(error)); 
       deferred.reject(false); 
      }); 
      return deferred.promise; 
     }, 
     storeUserToken: storeUserToken, 
     getStoredToken: getStoredToken, 
     createTwitterSignature: createTwitterSignature 
    }; 
}); 

有沒有人遇到過這樣的問題並解決了它,如果是的話請提供一些提示。

+0

任何人有任何想法? –

+1

您爲了獲得twitter電子郵件認證而遵循的過程是什麼? – Webruster

+0

@Webruster感謝您首先發表評論,我所做的只是在https://support.twitter.com/forms/platform上向twitter發送請求,並檢查了我需要訪問特殊權限複選框,並在第二天我的應用程序是允許獲得電子郵件地址 –

回答

3

經過幾天的工作,我終於使它工作。

以下是任何面對此類問題的人的代碼。

代碼:

serviceModule.factory('$twitterHelpers', ['$q', '$http', function ($q, $http) { 

    function createSignature(method, endPoint, headerParameters, bodyParameters, secretKey, tokenSecret) { 
     if (typeof jsSHA !== "undefined") { 
      var headerAndBodyParameters = angular.copy(headerParameters); 
      var bodyParameterKeys = Object.keys(bodyParameters); 
      for (var i = 0; i < bodyParameterKeys.length; i++) { 
       headerAndBodyParameters[bodyParameterKeys[i]] = escapeSpecialCharacters(bodyParameters[bodyParameterKeys[i]]); 
      } 
      var signatureBaseString = method + "&" + encodeURIComponent(endPoint) + "&"; 
      var headerAndBodyParameterKeys = (Object.keys(headerAndBodyParameters)).sort(); 
      for (i = 0; i < headerAndBodyParameterKeys.length; i++) { 
       if (i == headerAndBodyParameterKeys.length - 1) { 
        signatureBaseString += encodeURIComponent(headerAndBodyParameterKeys[i] + "=" + headerAndBodyParameters[headerAndBodyParameterKeys[i]]); 
       } else { 
        signatureBaseString += encodeURIComponent(headerAndBodyParameterKeys[i] + "=" + headerAndBodyParameters[headerAndBodyParameterKeys[i]] + "&"); 
       } 
      } 
      var oauthSignatureObject = new jsSHA(signatureBaseString, "TEXT"); 

      var encodedTokenSecret = ''; 
      if (tokenSecret) { 
       encodedTokenSecret = encodeURIComponent(tokenSecret); 
      } 

      headerParameters.oauth_signature = encodeURIComponent(oauthSignatureObject.getHMAC(encodeURIComponent(secretKey) + "&" + encodedTokenSecret, "TEXT", "SHA-1", "B64")); 
      var headerParameterKeys = Object.keys(headerParameters); 
      var authorizationHeader = 'OAuth '; 
      for (i = 0; i < headerParameterKeys.length; i++) { 
       if (i == headerParameterKeys.length - 1) { 
        authorizationHeader += headerParameterKeys[i] + '="' + headerParameters[headerParameterKeys[i]] + '"'; 
       } else { 
        authorizationHeader += headerParameterKeys[i] + '="' + headerParameters[headerParameterKeys[i]] + '",'; 
       } 
      } 
      return {signature_base_string: signatureBaseString, authorization_header: authorizationHeader, signature: headerParameters.oauth_signature}; 
     } else { 
      return "Missing jsSHA JavaScript library"; 
     } 
    } 

    function createNonce(length) { 
     var text = ""; 
     var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 
     for (var i = 0; i < length; i++) { 
      text += possible.charAt(Math.floor(Math.random() * possible.length)); 
     } 
     return text; 
    } 

    function escapeSpecialCharacters(string) { 
     var tmp = encodeURIComponent(string); 
     tmp = tmp.replace(/\!/g, "%21"); 
     tmp = tmp.replace(/\'/g, "%27"); 
     tmp = tmp.replace(/\(/g, "%28"); 
     tmp = tmp.replace(/\)/g, "%29"); 
     tmp = tmp.replace(/\*/g, "%2A"); 
     return tmp; 
    } 

    function transformRequest(obj) { 
     var str = []; 
     for (var p in obj) 
      str.push(encodeURIComponent(p) + "=" + escapeSpecialCharacters(obj[p])); 
     console.log(str.join('&')); 
     return str.join('&'); 
    } 

    return { 
     createTwitterSignature: function (method, url, bodyParameters, clientId, clientSecret, token) { 
      var oauthObject = { 
       oauth_consumer_key: clientId, 
       oauth_nonce: createNonce(10), 
       oauth_signature_method: "HMAC-SHA1", 
       oauth_token: token.oauth_token, 
       oauth_timestamp: Math.round((new Date()).getTime()/1000.0), 
       oauth_version: "1.0" 
      }; 
      var signatureObj = createSignature(method, url, oauthObject, bodyParameters, clientSecret, token.oauth_token_secret); 
      $http.defaults.headers.common.Authorization = signatureObj.authorization_header; 
      return signatureObj; 
     }, 
     transformRequest: transformRequest 
    }; 
}]); 

serviceModule.factory('TwitterService', function ($cordovaOauth, $cordovaOauthUtility, $http, $resource, $q, AUTH_ID, $twitterHelpers) 
{ 

    var twitterKey = "STORAGE.TWITTER.KEY"; 
    var clientId = AUTH_ID.TWITTER_APP_ID; 
    var clientSecret = AUTH_ID.TWITTER_APP_SEC; 

    function storeUserToken(data) 
    { 
     window.localStorage.setItem(twitterKey, JSON.stringify(data)); 
    } 

    function getStoredToken() 
    { 
     return window.localStorage.getItem(twitterKey); 
    } 

    return { 
     initialize: function() 
     { 
      var deferred = $q.defer(); 
      var token = getStoredToken(); 

      if (token !== null) 
      { 
       deferred.resolve(true); 
      } 
      else 
      { 
       $cordovaOauth.twitter(clientId, clientSecret).then(function (result) 
       { 
        storeUserToken(result); 
        deferred.resolve(true); 
       }, function (error) 
       { 
        deferred.reject(false); 
       }); 
      } 
      return deferred.promise; 
     }, 
     isAuthenticated: function() 
     { 
      return getStoredToken() !== null; 
     }, 
     getHomeTimeline: function() 
     { 
      var home_tl_url = 'https://api.twitter.com/1.1/statuses/home_timeline.json'; 
      createTwitterSignature('GET', home_tl_url); 
      return $resource(home_tl_url).query(); 
     }, 
     getTwitterProfileManual: function() { 

      var deferred = $q.defer(); 
      var token = angular.fromJson(getStoredToken()); 

      $twitterHelpers.createTwitterSignature('GET', 'https://api.twitter.com/1.1/account/verify_credentials.json', { 'include_email' : 'true' }, clientId, clientSecret, token); 

      $http({ 
       method: 'GET', 
       url: "https://api.twitter.com/1.1/account/verify_credentials.json", 
       params: {'include_email': 'true'}, 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function (result) 
      { 
       console.log(result); 
       alert('USER TIMELINE: ' + JSON.stringify(result)); 
       deferred.resolve(result); 
      }).error(function (error) 
      { 
       alert("Error: " + JSON.stringify(error)); 
       deferred.reject(false); 
      }); 
      return deferred.promise; 
     }, 
     storeUserToken: storeUserToken, 
     getStoredToken: getStoredToken 
    }; 
}); 

從上面的代碼使用getTwitterProfileManual這個函數來獲取Twitter的用戶對象回覆的電子郵件地址。

注意:要獲取電子郵件地址,您的twitter應用必須列入白名單才能訪問用戶的電子郵件地址。

相關問題