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

如何在代码中无交互刷新Google Business API访问令牌?

解决方案:实现Google My Business API令牌自动刷新

要解决手动输入令牌、过期后重复操作的问题,你需要使用带刷新令牌(Refresh Token)的OAuth 2.0凭据或服务账号(针对G Suite/Workspace用户管理自家位置的场景),以下是具体实现方案:

方案一:OAuth 2.0授权码流程(带刷新令牌)

适用于需要访问第三方商家位置评论的场景,只需首次手动授权一次,后续代码自动刷新访问令牌。

步骤1:准备OAuth客户端凭据

  1. 登录Google Cloud Console,创建桌面类型的OAuth客户端ID,下载包含client_id、client_secret的JSON文件。
  2. 通过OAuth 2.0 Playground或临时代码获取含refresh_token的令牌响应(需勾选"offline"权限以获取持久刷新令牌)。

步骤2:代码实现自动刷新

替换原手动输入令牌的逻辑,改用可自动刷新的凭据:

// 加载客户端凭据(从下载的JSON文件读取,测试阶段也可直接硬编码)
var clientSecrets = GoogleClientSecrets.FromFile("client_secrets.json").Secrets;

// 配置令牌持久化存储,避免重启后重新授权
var tokenStore = new FileDataStore("MyBusiness.TokenStore");

// 创建授权流
var flow = new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
    ClientSecrets = clientSecrets,
    Scopes = new[] { "https://www.googleapis.com/auth/business.manage" },
    DataStore = tokenStore
});

var userId = "default_user"; // 用任意标识区分不同用户的令牌存储
var token = await flow.LoadTokenAsync(userId, CancellationToken.None);

// 首次运行需手动授权,后续自动使用存储的刷新令牌
if (token == null)
{
    var authUrl = flow.CreateAuthorizationCodeRequest("urn:ietf:wg:oauth:2.0:oob").ToString();
    Console.WriteLine($"请访问以下链接授权:{authUrl}");
    Console.WriteLine("输入授权码:");
    var authCode = Console.ReadLine();
    
    // 交换获取包含刷新令牌的完整令牌数据
    token = await flow.ExchangeCodeForTokenAsync(userId, authCode, "urn:ietf:wg:oauth:2.0:oob", CancellationToken.None);
}

// 创建可自动刷新的用户凭据
var credentials = new UserCredential(flow, userId, token);

// 初始化My Business服务
var myBusinessApiV4Service = new MyBusinessService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credentials
});

首次运行完成授权后,FileDataStore会自动保存刷新令牌,后续启动无需任何交互,凭据会在访问令牌过期时自动完成刷新。

方案二:服务账号(G Suite/Workspace专属)

如果你是G Suite/Workspace管理员,管理自家的Google Business Profile位置,可使用服务账号实现全程无交互授权:

步骤1:准备服务账号

  1. 在Google Cloud Console创建服务账号,下载JSON格式的密钥文件。
  2. 在G Suite管理控制台给服务账号委派https://www.googleapis.com/auth/business.manage权限范围,并指定要模拟的Google Business Profile管理员用户。

步骤2:代码实现

// 加载服务账号密钥,创建可自动刷新的凭据
var credentials = GoogleCredential.FromFile("service_account_key.json")
    .CreateScoped(new[] { "https://www.googleapis.com/auth/business.manage" })
    // 模拟指定的Google Business Profile管理员用户
    .CreateWithUser("admin@yourdomain.com");

// 初始化My Business服务
var myBusinessApiV4Service = new MyBusinessService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credentials
});

该方案全程无需用户参与,服务账号会自动处理令牌的刷新与管理。

关键说明

  • 你原代码中GoogleCredential.FromAccessToken(accessToken)创建的是一次性凭据,未关联刷新令牌,因此无法自动刷新。
  • 两种方案都需确保你的Google Cloud项目已启用My Business API,方案一还需配置好OAuth同意屏幕。

内容的提问来源于stack exchange,提问作者GordonS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 02:15:38