我正在尝试从在我的 firebase 云函数 (nodejs) 项目中使用整个 googleapis 包转变为仅使用我需要的子包。
这是我目前有效的:
const {google} = require('googleapis');
const oAuth2Client = new google.auth.OAuth2(
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
// Do some stuff with oAuth2Client
这就是我正在尝试做的事情,但没有成功。我已经运行了 npm i @googleapis/oauth2。 我正在得到
错误:无法从源加载函数定义:无法 从函数源生成清单:TypeError:OAuth2 不是 构造函数
const { OAuth2 } = require('@googleapis/oauth2');
const oAuth2Client = new OAuth2 (
CLIENT_ID,
CLIENT_SECRET,
REDIRECT_URI
);
oAuth2Client.setCredentials({ refresh_token: REFRESH_TOKEN });
// Do some stuff with oAuth2Client
我还尝试了新的 OAuth2.auth.OAuth2(1) 和 OAuth2.OAuth2(2) 并得到:
(1)
错误:无法从源加载函数定义:无法 从函数源生成清单:类型错误:无法读取 未定义的属性(读取“auth”)
(2)
错误:无法从源加载函数定义:无法 从函数源生成清单:类型错误:无法读取 未定义的属性(读取“OAuth2”)
去过那里。我最终得到了这个:
import * as googleAuth from 'google-auth-library';
async function getOAuthClient(secrets, { credentials } = {}) {
const { clientId, clientSecret, serverRedirectUri } = secrets;
const clientOptions = { clientId, clientSecret, redirectUri: serverRedirectUri };
const oauth2Client = new googleAuth.OAuth2Client(clientOptions);
if (credentials) {
oauth2Client.setCredentials(credentials);
}
return oauth2Client;
}
以下为例:
async function generateAuthUrl() {
const secrets = await getSecrets();
const oauth2Client = await getOAuthClient(secrets);
const authorizeUrl = oauth2Client.generateAuthUrl({
access_type: 'offline',
include_granted_scopes: true,
scope: scopes,
});
return { authorizeUrl };
}
async function authConfirmation(code) {
const secrets = await getSecrets();
const oauth2Client = await getOAuthClient(secrets);
const { tokens } = await oauth2Client.getToken(code);
await setTokens(tokens);
return { redirectUrl: secrets.clientRedirectUri };
}
// scopes in my case is:
const scopes = [
'https://www.googleapis.com/auth/business.manage',
];
// since I'm using
// import { mybusinessaccountmanagement } from '@googleapis/mybusinessaccountmanagement';
我在自述文件的顶部有这个,经过几个小时的努力,也许它们对你有帮助:
“googleapis”:“^133.0.0”(对于节点),也可以,但库太重
“@googleapis/mybusinessaccountmanagement”更轻量级
https://developers.google.com/my-business/content/review-data#list_all_reviews https://github.com/googleapis/google-api-nodejs-client?tab=readme-ov-file#oauth2-client https://github.com/googleapis/google-api-nodejs-client/issues/2700 https://github.com/googleapis/google-api-nodejs-client/blob/main/samples/oauth2.js https://developers.google.com/my-business/reference/rest/v4/accounts.locations.reviews/list#authorization-scopes https://developers.google.com/my-business/content/implement-oauth