发布于 2026-01-06 8 阅读
0

如何在 React 或 Vue 项目中使用 Google One Tap?

如何在 React 或 Vue 项目中使用 Google One Tap?

大家好,
我将向您展示如何在您的项目中使用 Google One Tap。为此,我使用了我自己的 npm 包google-one-tap

替代文字

获取您的 Google API 客户端 ID

打开Google API 控制台的“凭据”页面
创建或选择一个 Google API 项目。如果您已有 Google 登录按钮,请使用现有项目和 Web 客户端 ID。

1. 将软件包安装到您的项目中。



npm install google-one-tap


Enter fullscreen mode Exit fullscreen mode

或者



yarn add google-one-tap


Enter fullscreen mode Exit fullscreen mode

2. 之后,导入包。



import googleOneTap from 'google-one-tap';


Enter fullscreen mode Exit fullscreen mode

3. 使用带有选项的 googleOneTap 方法。



const options = {
    client_id: '___CLIENT_ID___', // required
    auto_select: false, // optional
    cancel_on_tap_outside: false, // optional
    context: 'signin' // optional
};

googleOneTap(options, (response) => {
    // Send response to server
    console.log(response);
});


Enter fullscreen mode Exit fullscreen mode

Vue.js 完整代码示例



import googleOneTap from 'google-one-tap';
export default {
    mounted() {
        const options = {
            client_id: '___CLIENT_ID___', // required
            auto_select: false, // optional
            cancel_on_tap_outside: false, // optional
            context: 'signin', // optional
        };
        googleOneTap(options, (response) => {
            // Send response to server
            console.log(response);
        });
    },
};


Enter fullscreen mode Exit fullscreen mode

完成以上步骤后,您必须向服务器发送响应。

Node.js 服务器示例



const { OAuth2Client } = require('google-auth-library');
const client = new OAuth2Client(CLIENT_ID);
async function verify() {
    const ticket = await client.verifyIdToken({
        idToken: token,
        audience: CLIENT_ID, // Specify the CLIENT_ID of the app that accesses the backend
        // Or, if multiple clients access the backend:
        //[CLIENT_ID_1, CLIENT_ID_2, CLIENT_ID_3]
    });
    const payload = ticket.getPayload();
    const userid = payload['sub'];
    // If request specified a G Suite domain:
    // const domain = payload['hd'];
}
verify().catch(console.error);


Enter fullscreen mode Exit fullscreen mode

感谢阅读😊

文章来源:https://dev.to/burakgur/how-to-use-google-one-tap-in-your-react-or-vue-project-3jbb