You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将旧版JavaScript谷歌注册按钮迁移适配新版Identity SDK

谷歌新版Identity SDK登录回调代码修改方案

新版Google Identity SDK的回调参数和旧版完全不同:旧版传入的是GoogleUser实例,新版回调传入的是包含JWT凭证的响应对象,你需要解码JWT后即可拿到对应的用户信息,修改方案如下:

1. 替换原有onSignIn函数

你可以选择使用第三方jwt-decode库解码,或者使用原生JS解码,无需引入额外依赖:

// 原生JWT解码方法,无需引入第三方库
function parseJwt(token) {
    const base64Url = token.split('.')[1];
    const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
    const jsonPayload = decodeURIComponent(window.atob(base64).split('').map(c => {
        return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
    }).join(''));
    return JSON.parse(jsonPayload);
}

// 修改后的登录回调函数
function onSignIn(response) {
    // 解码凭证获取用户信息
    const userInfo = parseJwt(response.credential);
    // 原有业务逻辑直接替换字段即可
    $("#user").text(userInfo.name);
    $("#email").text(userInfo.email);
    $("#gPhoto").attr("src", userInfo.picture);
}

2. 其他注意事项

  • 你当前的新版按钮HTML代码已经配置了data-callback="onSignIn",和回调函数名完全匹配,不需要修改HTML部分的配置
  • 解码后的用户信息字段和旧版接口的对应关系:
    • userInfo.name 等价于旧版 googleUser.getBasicProfile().getName()
    • userInfo.email 等价于旧版 googleUser.getBasicProfile().getEmail()
    • userInfo.picture 等价于旧版 googleUser.getBasicProfile().getImageUrl()

内容的提问来源于stack exchange,提问作者Egemen Köroğlu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:36:01