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

如何用Node.js调用Google Cloud Commerce Procurement API并迁移Python代码

Node.js 实现 Google Cloud Commerce Procurement API 调用(含服务账号身份模拟)

依赖安装

首先安装所需的Node.js包:

npm install google-auth-library googleapis

实现代码

const { GoogleAuth, Impersonated } = require('google-auth-library');
const { google } = require('googleapis');

const PROCUREMENT_API = 'cloudcommerceprocurement';
const API_VERSION = 'v1';

async function main() {
  // 加载默认凭据
  const auth = new GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/cloud-platform']
  });
  const sourceCredentials = await auth.getCredentials();

  // 创建身份模拟凭据
  const impersonatedAuth = new Impersonated({
    sourceClient: auth,
    targetPrincipal: '<service_account_email_that_we_want_to_impersonate>',
    targetScopes: ['https://www.googleapis.com/auth/cloud-platform'],
    lifetime: 500 // 凭据有效期,单位秒
  });

  // 构建API服务客户端
  const service = google[PROCUREMENT_API]({
    version: API_VERSION,
    auth: impersonatedAuth,
    cacheDiscovery: false
  });

  try {
    // 调用 providers.accounts.list 接口
    const res = await service.providers.accounts.list({
      parent: 'providers/<provider_id>'
    });
    console.log('API响应:', res.data);
  } catch (err) {
    console.error('调用API出错:', err);
  }
}

// 执行主函数
main().catch(console.error);

代码说明

  • 加载默认凭据:通过GoogleAuth加载环境中的默认凭据(如GCP本地凭据、服务账号密钥等)
  • 身份模拟:通过Impersonated类实现服务账号身份模拟,参数和原Python代码一一对应
  • 构建API客户端:使用googleapis库构建Cloud Commerce Procurement API的客户端实例
  • 调用API:异步调用providers.accounts.list方法,并处理响应和错误

内容的提问来源于stack exchange,提问作者Patrick-Ranjit D. Madsen

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 01:01:35