使用react-native-google-signin获取访问令牌

时间:2020-06-03 12:44:50

标签: react-native google-contacts-api

我需要我的应用程序才能从gmail查找用户联系人。所以我需要使用google contacts api

中的此api
https://www.google.com/m8/feeds/contacts/{userEmail}/full

当我向该网址发送GET请求时,我得到:

{
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

我的问题是如何使用 react-native-google-signin 获取accessToken以请求此api?我已经尝试过了

GoogleSignin.getCurrentUser().then(infos => console.log(infos));

通过此功能,我得到用户信息,例如姓名,照片,电子邮件...,我得到一个字段idToken,但是当我将此令牌添加到标头请求中时,我总是得到代码403,所以我认为这不是't访问令牌。

您能帮我找到访问令牌吗,或者有其他解决方案可以直接使用react-native-google-signin查找联系人

编辑: 也尝试过

GoogleSignin.getTokens().then((res) => { console.log(res); });

但是什么都没记录,我不知道为什么

2 个答案:

答案 0 :(得分:2)

使用GoogleSignIn.getTokens()登录后,可以通过调用GoogleSignIn.signIn()方法来获取accessToken。然后,在向https://www.google.com/m8/feeds/contacts/default/full发送accessToken请求时,可以将返回的Bearer附加到GET标头上。

警告::Google Contacts API 现在已弃用,计划于2021年6月15日停用。应用程序应改用People API。开始使用migration guide。参见official statement

答案 1 :(得分:0)

您可以尝试使用此功能,使其与我一起正常使用

_signIn = async () => {
    try {
        await GoogleSignin.hasPlayServices();
        const userInfo = await GoogleSignin.signIn();

                response: {
                    first_name: userInfo.user.givenName,  
                    social_id: userInfo.user.id, last_name: userInfo.user.familyName, email: userInfo.user.email
                }

            // console.log('_signIn userInfo', userInfo);


    } catch (error) {
        if (error.code === statusCodes.SIGN_IN_CANCELLED) {
            // console.log('_signIn error.code 1', error.code);
            // user cancelled the login flow
        } else if (error.code === statusCodes.IN_PROGRESS) {
            // console.log('_signIn error.code 2 ', error.code);
            // operation (f.e. sign in) is in progress already
        } else if (error.code === statusCodes.PLAY_SERVICES_NOT_AVAILABLE) {
            // console.log('_signIn error.code 3', error.code);
            // play services not available or outdated
        } else {
            // console.log('_signIn else', error);
            // some other error happened
        }
    }
};