Google Apps Script调用HMRC API报client_id is required错误排查
问题定位与修复方案
- 核心错误:你将OAuth 2.0授权请求必填参数错误放置在请求头中,HMRC的
/oauth/authorize端点要求client_id、response_type、scope、redirect_uri这类授权参数必须作为URL查询参数传递,服务端不会从请求头中读取这类参数,因此返回client_id is required报错。 - 额外注意:
/oauth/authorize是用户交互授权端点,直接用UrlFetchApp.fetch请求该接口无法获得授权码,正确逻辑是生成拼接好参数的授权URL,引导用户跳转访问该地址完成授权,授权完成后会回调你填写的redirect_uri并带回授权码。
修正后代码示例
function getAuth() { const authBaseUrl = 'https://test-api.service.hmrc.gov.uk/oauth/authorize'; // 构造授权查询参数 const params = new URLSearchParams({ 'response_type': 'code', 'client_id': CLIENT_ID, 'scope': 'hello', 'redirect_uri': 'https://www.xxxxxxx.com/' }); const fullAuthUrl = `${authBaseUrl}?${params.toString()}`; // 如果需要调试请求,仅保留Accept在请求头中 const response = UrlFetchApp.fetch(fullAuthUrl, { headers: { 'Accept': 'application/vnd.hmrc.1.0+json' } }); const result = JSON.parse(response.getContentText()); Logger.log(JSON.stringify(result, null, 2)); // 正常业务场景下输出fullAuthUrl引导用户跳转授权即可 Logger.log('授权访问地址:' + fullAuthUrl); }
如果运行环境不支持URLSearchParams,可以手动拼接转码后的参数:
const fullAuthUrl = authBaseUrl + '?response_type=code&client_id=' + encodeURIComponent(CLIENT_ID) + '&scope=hello&redirect_uri=' + encodeURIComponent('https://www.xxxxxxx.com/')
内容的提问来源于stack exchange,提问作者h-edwards
相关产品推荐
相关产品推荐

