美文网首页iOS技术专题
google第三方登录

google第三方登录

作者: observerb | 来源:发表于2019-02-18 19:16 被阅读3次

1、创建Google API控制台项目和客户端ID

首先前往Google API 控制台选择或者创建一个项目

选择创建凭据 -> OAuth 客户端 ID -> 网页应用,之后输入 JavaScript 来源、重定向 URI(可以添加开发地址:http://localhost:8085),拿到的客户端ID用于后续操作

创建

G第三方教程

2、自定义登录和注销按钮

<button id="customBtn" type="button">Google登录</button>

<div id="name"></div>

<button type="button" onclick="signOut();">Sign out</button>

<script src="https://apis.google.com/js/api:client.js"></script>

<script>

var googleUser = {};

var startApp = function() {

gapi.load('auth2', function(){

  // Retrieve the singleton for the GoogleAuth library and set up the client.

  auth2 = gapi.auth2.init({

    client_id: 'xxxx', //客户端ID

    cookiepolicy: 'single_host_origin',

    scope: 'profile' //可以请求除了默认的'profile' and 'email'之外的数据

  });

  attachSignin(document.getElementById('customBtn'));

});

};

function attachSignin(element) {

auth2.attachClickHandler(element, {},

    function(googleUser) {

      document.getElementById('name').innerText = "Signed in: " + googleUser.getBasicProfile().getName();

var profile = auth2.currentUser.get().getBasicProfile();

console.log('ID: ' + profile.getId());

console.log('Full Name: ' + profile.getName());

console.log('Given Name: ' + profile.getGivenName());

console.log('Family Name: ' + profile.getFamilyName());

console.log('Image URL: ' + profile.getImageUrl());

console.log('Email: ' + profile.getEmail());

    }, function(error) {

      console.log(JSON.stringify(error, undefined, 2));

    });

}

startApp();

//注销

function signOut() {

var auth2 = gapi.auth2.getAuthInstance();

auth2.signOut().then(function () {

alert('用户注销成功');

});

}

相关文章

网友评论

    本文标题:google第三方登录

    本文链接:https://www.haomeiwen.com/subject/gbezeqtx.html