Google服务注册

https://console.cloud.google.com/apis/credentials?pr

创建OAuth客户端ID

入口
image.png

web准备

教程:https://developers.google.com/identity/sign-in/web/reference#googleauthcurrentuserget

权限:https://developers.google.com/identity/protocols/oauth2/javascript-implicit-flow#js-client-library_1

  1. GoogleUser.getBasicProfile()
  1. <script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>

初始化

  1. /**
  2. * @description: 配置初始化-加载auth2的库
  3. * @param {*}
  4. * @return {*}
  5. */
  6. function onInitGoogle() {
  7. let baseOptions = {
  8. client_id:
  9. "你申请的client_id",
  10. cookiepolicy: "single_host_origin",
  11. };
  12. gapi.load("auth2", function () {
  13. console.log("%c%s", "color: #00e600", "auth2-ready");
  14. gapi.auth2
  15. .init(baseOptions)
  16. .then((res) => {
  17. console.log("google init complete...", res);
  18. window.getAuthInstance = gapi.auth2.getAuthInstance(); //获取GoogleAuth对象
  19. let isSignedIn = getAuthInstance.isSignedIn.get(); //存储登录状态
  20. let GoogleUser = getAuthInstance.currentUser.get(); //这个方法获取返回的响应对象
  21. if (isSignedIn) {
  22. console.log(
  23. "%c%s",
  24. "color: #00a3cc",
  25. "window.getAuthInstance",
  26. GoogleUser
  27. );
  28. }
  29. })
  30. .catch((err) => console.log(err));
  31. });
  32. }

登录

  1. /**
  2. *google登录
  3. */
  4. function googleSignIn() {
  5. return getAuthInstance.signIn()
  6. }

登出

  1. function googleSignOut() {
  2. getAuthInstance
  3. .signOut()
  4. .then((res) => {
  5. console.log(res, "退出登录");
  6. getAuthInstance.disconnect();
  7. })
  8. .catch((err) => console.log(err));
  9. }

官方实例代码

  1. <script>
  2. var GoogleAuth;
  3. var SCOPE = 'https://www.googleapis.com/auth/drive.metadata.readonly';
  4. function handleClientLoad() {
  5. // Load the API's client and auth2 modules.
  6. // Call the initClient function after the modules load.
  7. gapi.load('client:auth2', initClient);
  8. }
  9. function initClient() {
  10. // In practice, your app can retrieve one or more discovery documents.
  11. var discoveryUrl = 'https://www.googleapis.com/discovery/v1/apis/drive/v3/rest';
  12. // Initialize the gapi.client object, which app uses to make API requests.
  13. // Get API key and client ID from API Console.
  14. // 'scope' field specifies space-delimited list of access scopes.
  15. gapi.client.init({
  16. 'apiKey': 'YOUR_API_KEY',
  17. 'clientId': 'YOUR_CLIENT_ID',
  18. 'discoveryDocs': [discoveryUrl],
  19. 'scope': SCOPE
  20. }).then(function () {
  21. GoogleAuth = gapi.auth2.getAuthInstance();
  22. // Listen for sign-in state changes.
  23. GoogleAuth.isSignedIn.listen(updateSigninStatus);
  24. // Handle initial sign-in state. (Determine if user is already signed in.)
  25. var user = GoogleAuth.currentUser.get();
  26. setSigninStatus();
  27. // Call handleAuthClick function when user clicks on
  28. // "Sign In/Authorize" button.
  29. $('#sign-in-or-out-button').click(function() {
  30. handleAuthClick();
  31. });
  32. $('#revoke-access-button').click(function() {
  33. revokeAccess();
  34. });
  35. });
  36. }
  37. function handleAuthClick() {
  38. if (GoogleAuth.isSignedIn.get()) {
  39. // User is authorized and has clicked "Sign out" button.
  40. GoogleAuth.signOut();
  41. } else {
  42. // User is not signed in. Start Google auth flow.
  43. GoogleAuth.signIn();
  44. }
  45. }
  46. function revokeAccess() {
  47. GoogleAuth.disconnect();
  48. }
  49. function setSigninStatus() {
  50. var user = GoogleAuth.currentUser.get();
  51. var isAuthorized = user.hasGrantedScopes(SCOPE);
  52. if (isAuthorized) {
  53. $('#sign-in-or-out-button').html('Sign out');
  54. $('#revoke-access-button').css('display', 'inline-block');
  55. $('#auth-status').html('You are currently signed in and have granted ' +
  56. 'access to this app.');
  57. } else {
  58. $('#sign-in-or-out-button').html('Sign In/Authorize');
  59. $('#revoke-access-button').css('display', 'none');
  60. $('#auth-status').html('You have not authorized this app or you are ' +
  61. 'signed out.');
  62. }
  63. }
  64. function updateSigninStatus() {
  65. setSigninStatus();
  66. }
  67. </script>
  68. <button id="sign-in-or-out-button"
  69. style="margin-left: 25px">Sign In/Authorize</button>
  70. <button id="revoke-access-button"
  71. style="display: none; margin-left: 25px">Revoke access</button>
  72. <div id="auth-status" style="display: inline; padding-left: 25px"></div><hr>
  73. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
  74. <script async defer src="https://apis.google.com/js/api.js"
  75. onload="this.onload=function(){};handleClientLoad()"
  76. onreadystatechange="if (this.readyState === 'complete') this.onload()">
  77. </script>

备注 该API 2023年将废弃

image.png

image.png 说明网站: https://developers.google.com/identity/gsi/web 迁移方案 https://www.yuque.com/docs/share/516c88cc-e68c-4c79-b87c-ab1dd955f437?#