回复

时间:2017-11-12 10:13:50

标签: javascript google-api

在此代码中,第一个响应没有问题,但在此之后缺少刷新令牌。

查看API文档后我找不到问题。

<!DOCTYPE html>
<html>
<head>
<script
    src="https://code.jquery.com/jquery-3.2.1.min.js"
    integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
    crossorigin="anonymous"></script>
<title></title>
</head>
<body>
<button class="google-connect-btn">login</button>
</body>
</html>

 <script>
   function logout() {
   gapi.auth.signOut();
   location.reload();
   }
   function login() {
    var myParams = {
     'clientid': 
 '228716450427-f56942lkoiukffta3b83uokl22nd0urm.apps.googleusercontent.com',
    'cookiepolicy': 'single_host_origin',
    'callback': 'loginCallback',
    'approvalprompt': 'force',
    'scope': 'https://www.googleapis.com/auth/plus.login 
      https://www.googleapis.com/auth/plus.profile.emails.read'                            
   };
      gapi.auth.signIn(myParams);
    }

  function loginCallback(result) {
   var newData = {
    token: result.access_token,
   expires_in: result.expires_in,
  type: 'google',
};

if (result['status']['signed_in']) {
var request = gapi.client.plus.people.get(
{
'userId': 'me'
});
request.execute(function (resp) {

newData.name = resp.displayName;
newData.id = resp.id;
newData.avatar = resp.image.url;
newData.accounts = [];
var refreshData = {
 token : result.code,
id : newData.id,
type : newData.type
};



$.ajax({
url: 'https://www.googleapis.com/oauth2/v4/token',
type: "post",
contentType: "application/x-www-form-urlencoded",
data: {

code:result.code, 
client_id:'228716450427
 -f56942lkoiukffta3b83uokl22nd0urm.apps.googleusercontent.com',
client_secret:'LBirrTxt7373bF61MKik1JUx',
redirect_uri:'postmessage',
   grant_type:'authorization_code',
},
success: function(response){
console.log(JSON.stringify(response));
console.log("Response: " + response);
console.log("AT: " + response['access_token']);
console.log("RT: " + response['refresh_token']);

var access_token = response['access_token'];
var refresh_token = response['refresh_token'];
 }
})
.fail(function(err) {
alert("error" + JSON.stringify(err)); //[Object object]
console.log("error" + err);
 });









 }, function (error) {


});


}

}
function onLoadCallback() {
gapi.client.setApiKey('AIzaSyDU8d6MRQqk6A5z8IEPmsqtN7tprBJYtoo');
gapi.client.load('plus', 'v1', function () {
});
}

</script>


<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript';               
po.async = true;
po.src = 'https://apis.google.com/js/client.js?onload=onLoadCallback';
var s = document.getElementsByTagName('script')[0];                                                              
 s.parentNode.insertBefore(po, s);
 })();
  $(document).on('click' , '.google-connect-btn' , function () {
 login();
 });
 </script>

0 个答案:

没有答案