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

如何通过Google AppScript获取Zoho CRM与Google Drive集成的access_token及refresh_token

解决Zoho CRM与Google Drive集成中授权码换令牌的通用实现方案

核心逻辑:调用Google OAuth2标准令牌交换接口

Google OAuth2流程中,授权码换取access_token和refresh_token是标准HTTP请求,和Zoho/Google特定脚本环境无关,你可以用任意支持HTTP请求的后端语言实现通用逻辑。

令牌交换请求参数与端点

向https://oauth2.googleapis.com/token发送POST请求,需携带以下参数:

  • code: 用户授权后得到的授权码(从授权URL中提取的code参数值)
  • client_id: 你的Google OAuth应用的客户端ID
  • client_secret: 你的Google OAuth应用的客户端密钥
  • redirect_uri: 申请Google OAuth应用时配置的重定向URI(必须和授权时用的完全一致)
  • grant_type: 固定值authorization_code

代码实现示例

Python 实现(使用requests库)

import requests

def exchange_code_for_tokens(code, client_id, client_secret, redirect_uri):
    token_url = "https://oauth2.googleapis.com/token"
    payload = {
        "code": code,
        "client_id": client_id,
        "client_secret": client_secret,
        "redirect_uri": redirect_uri,
        "grant_type": "authorization_code"
    }
    response = requests.post(token_url, data=payload)
    if response.status_code == 200:
        token_data = response.json()
        return {
            "access_token": token_data.get("access_token"),
            "refresh_token": token_data.get("refresh_token"),
            "expires_in": token_data.get("expires_in")
        }
    else:
        # 处理错误,比如授权码过期、参数不匹配等
        raise Exception(f"令牌交换失败: {response.json()}")

# 使用示例
# tokens = exchange_code_for_tokens("用户的授权码", "你的client_id", "你的client_secret", "你的redirect_uri")

Node.js 实现(使用axios库)

const axios = require('axios');

async function exchangeCodeForTokens(code, clientId, clientSecret, redirectUri) {
    const tokenUrl = "https://oauth2.googleapis.com/token";
    const payload = new URLSearchParams({
        code: code,
        client_id: clientId,
        client_secret: clientSecret,
        redirect_uri: redirectUri,
        grant_type: "authorization_code"
    });

    try {
        const response = await axios.post(tokenUrl, payload, {
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        });
        return {
            accessToken: response.data.access_token,
            refreshToken: response.data.refresh_token,
            expiresIn: response.data.expires_in
        };
    } catch (error) {
        throw new Error(`令牌交换失败: ${JSON.stringify(error.response.data)}`);
    }
}

// 使用示例
// exchangeCodeForTokens("用户的授权码", "你的client_id", "你的client_secret", "你的redirect_uri")
// .then(tokens => console.log(tokens))
// .catch(err => console.error(err));

关键注意事项

  • 存储refresh_token: 该令牌长期有效(除非用户撤销授权),需安全存储,用于后续刷新过期的access_token
  • 错误处理: 要捕获请求返回的错误,比如invalid_grant(授权码过期或无效)、redirect_uri_mismatch(重定向URI不匹配)等
  • 跨用户适配: 每个用户的授权码独立,只需将对应用户的code传入上述函数即可获取专属令牌,适配多用户场景
  • 服务部署: 将该逻辑部署为独立的API服务或后端函数,供你的集成流程调用,替代手动提取令牌的操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 22:07:17