调用UPS OAuth API持续报“Unsupported grant type”错误求助
解决UPS OAuth API "Unsupported grant type" 错误
你的问题核心在于请求体格式不匹配:
- 你设置了
Content-Type: application/x-www-form-urlencoded,但却用JSON.stringify(formData)把表单数据转成了JSON字符串,服务器无法正确解析这个格式,导致读取不到grant_type参数,所以返回空值的"Unsupported grant type"错误。 - UPS的OAuth接口要求请求体必须是URL编码的键值对格式,而非JSON格式。
修改后的代码
把payload部分调整为URL编码格式(Google Apps Script的UrlFetchApp支持直接传入对象自动转换):
const formData = { grant_type: 'client_credentials' }; const url = 'https://wwwcie.ups.com/security/v1/oauth/token'; const clientID = '{clientID}'; // 替换为你的实际clientID const clientSecret = '{clientSecret}'; // 替换为你的实际clientSecret const auth = 'Basic ' + Utilities.base64Encode(`${clientID}:${clientSecret}`); let options = { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': auth }, // 直接传入formData对象,UrlFetchApp会自动转为x-www-form-urlencoded格式 payload: formData // 若自动转换失效,可手动构建字符串: // payload: `grant_type=${encodeURIComponent(formData.grant_type)}` }; // 发送请求示例 const response = UrlFetchApp.fetch(url, options); console.log(response.getContentText());
验证注意事项
- 务必替换
{clientID}和{clientSecret}为实际有效值,不要保留占位符。 - 确认请求头的
Content-Type拼写正确,没有多余空格或大小写错误。 - 若手动构建payload字符串,要用
encodeURIComponent处理参数值,避免特殊字符导致解析失败。
内容的提问来源于stack exchange,提问作者Julian Peraza
相关产品推荐
相关产品推荐

