使用Google Apps Script调用Google Ads API REST接口改预算报错400
解决Google Ads API REST接口400无效JSON负载错误
问题原因
你遇到的400错误核心原因是:UrlFetchApp默认会把对象类型的payload编码为x-www-form-urlencoded格式,而非你指定的application/json。服务器收到的是类似validateOnly=true&partialFailure=true的表单键值对,而非预期的JSON结构,因此抛出"Invalid JSON payload"解析错误。
修复步骤
1. 将payload对象转为JSON字符串
使用JSON.stringify()把payload对象转换成JSON格式的字符串,确保服务器能正确识别并解析请求体。
2. 修正URL中的占位符
把URL里的{CHILD ACCOUNT ID}替换为实际的child_customer_id变量值,否则请求会发送到错误的API端点。
3. 可选:添加muteHttpExceptions查看完整响应
开启该选项可以获取完整的错误响应内容,更便于调试排查问题。
修改后的完整代码
//API specific variables const developer_token = "{DEVELOPER TOKEN}"; const parent_mcc_id = "xxxxxxxxxx"; //Temporary placeholder values var child_customer_id = "xxxxxxxxxx"; var budget_id = "xxxxxxxxxx"; let headers = { Authorization: "Bearer " + ScriptApp.getOAuthToken(), "developer-token": developer_token, "login-customer-id": parent_mcc_id }; //Make API call to modify campaign budget try{ // 先定义payload对象 let payloadObj = { operations: [ { updateMask: "amount_micros", update:{ resourceName: "customers/" + child_customer_id + "/campaignBudgets/" + budget_id, amountMicros: 60000000 // 建议改为数值类型,避免字符串转义问题 } } ], "partialFailure": true, "validateOnly": true, "responseContentType": "RESOURCE_NAME_ONLY" }; let requestParams = { method: "POST", contentType: "application/json", headers: headers, payload: JSON.stringify(payloadObj), // 转为JSON字符串 muteHttpExceptions: true // 开启以查看完整响应 }; // 替换URL中的占位符 var url = `https://googleads.googleapis.com/v11/customers/${child_customer_id}/campaignBudgets:mutate`; Logger.log(requestParams.payload); var postChange = UrlFetchApp.fetch(url, requestParams); // 打印完整响应内容用于调试 Logger.log(postChange.getContentText()); } catch(e) { Logger.log(e); }
额外注意事项
amountMicros建议使用数值类型(如60000000)而非字符串,更符合API的参数格式要求,避免潜在的类型校验错误。- 确认OAuth令牌拥有修改广告系列预算的权限,可通过Google Ads API的权限控制台验证权限范围。
内容的提问来源于stack exchange,提问作者Brandon
相关产品推荐
相关产品推荐

