如何用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
相关产品推荐
相关产品推荐

