Google第三方登录(JavaScript SDK)

网页使用google账号实现第三方登录

 

详细Demo下载

 

本demo示例利用JavaScript SDK实现了Facebook、google、LinkedIn第三方登录,可以获取用户的基本信息,并且同时包括官方登录按钮和自定义登录按钮代码示例。

 

 

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

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

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

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('用户注销成功');
		});
	}
</script>

注意:Google帐户的电子邮件地址可能会更改,因此请勿使用它来标识用户。相反,请使用帐户的ID,您可以在客户端上获取ID, 在ID标记getBasicProfile().getId()sub声明中使用该ID。

 

 

 

评论 29
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zh_rey

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值