首页 > 解决方案 > 如何使用 Google Scripts UrlFetchApp.fetch 从外部 API 获取字段?

问题描述

如何获取字段:dataMain在外部 API 中使用 Google Apps 脚本UrlFetchApp.fetch

这两天没有结果。客户支持对此 API 的帮助是指向https://pestroutes.api-docs.io/3.1/welcome/how-to-use-the-pestroutes-api的链接,这似乎没有帮助。这似乎应该是一件非常简单的事情,但显然不是。

外部 API 文档:https ://pestroutes.api-docs.io/3.1/import/importmainobject

示例代码(Google Apps 脚本):

function runTest() {
   var at = 'authenticationToken=<myToken>'
   var ak = 'authenticationKey=<myKey>'
   var url ='https://<myCompanyDomain>.pestroutes.com/api/import/main?' + at +'&' + ak;

   var data = [
      {
        'CustomerID':'9854poiu', 
        'CustomerName':'Fred Blair',
        'SquareFt': 3500,
        'Lead':'Fred Blair'
      }
   ];   

   var options = {  
     'method':'post',
     'contentType': 'application/json', 
     'payload': JSON.stringify(data)
   };  

   var response = UrlFetchApp.fetch(url, options);  
   var responseCode = response.getResponseCode()
   var responseBody = response.getContentText()

   if (responseCode === 200) {
      var responseJson = JSON.parse(responseBody);
      Logger.log(responseJson);
   } else {
      Logger.log(Utilities.formatString("Request failed. Expected 200, got %d: %s", responseCode, 
      responseBody))
   }
};

结果:

{
 endpoint=import, 
 params={endpoint=import,
 authenticationToken=<myToken>,
 authenticationKey=<myKey>, 
 dataMain=[],
 action=main}, 
 tokenUsage={requestsReadInLastMinute=2, requestsReadToday=0, requestsWriteToday=105,
 requestsWriteInLastMinute=0}, count=0.0, tokenLimits={limitWriteRequestsPerMinute=60.0,
 limitReadRequestsPerMinute=60.0, limitWriteRequestsPerDay=3000.0, limitReadRequestsPerDay=3000.0}, 
 requestAction=main, processingTime=153 milliseconds, dataIssueDetails=false, success=false
}

如您所见,dataMain=[]根据 API 说明,数组应该有一个对象,但总是返回空?

这是我的代码的问题,我误解了 API 的工作原理,还是 API 的问题?任何帮助或线索将不胜感激!

PS。是的,为了安全起见,我已经用和替换了我的密钥和令牌myKeymyToken

标签: google-apps-scripturlfetch

解决方案


看起来这是一个关于使用 PestRoutes 导入/主端点导入新客户和订阅的问题!我是负责 API 的 PestRoutes 开发人员,我很乐意为您提供帮助 <3.

这是将客户发布到我们的演示环境的示例:

抽象的:

apiModule.call('import','main',{
    "dataMain":[
        {
            "CustomerID": "PestRoutesOverflow1111",
            "Branch": "Demo Pest Control",
            "CustomerName": "PestRoutes Testing01",
            "CustomerAddress": "Walt Disney World Resort, Orlando, FL 32830",
            "CustomerCity": "Orlando",
            "CustomerState": "FL",
            "CustomerZipCode": "32830",
            "CustomerPhone1": "4428675309",
            "CustomerPhone2": "4438675309",
            "CustomerEmail": "",
            "CustomerStatus": "Act"

            //"Frequency": 90,              //These three fields
            //"ServiceType": 'Quarterly',   // are the minimum to
            //"Price": '111',               // create a subscription

            //"Lead": 'No',                 //Set Yes to revert subscription to a LEAD
            //"LastService": '4/26/18',     // If this is set it will override Lead to No
            //"InitialService": '1/26/18',  // If this is set it will override Lead to No
        }
    ]
});

这是卷曲的样子:

curl 'https://demo.pestroutes.com/api/import/main' \
-H 'Connection: keep-alive' \
-H 'Accept: application/json, text/javascript, */*; q=0.01' \
-H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36' \
-H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' \
-H 'Origin: null' \
-H 'Sec-Fetch-Site: cross-site' \
-H 'Sec-Fetch-Mode: cors' \
-H 'Sec-Fetch-Dest: empty' \
-H 'Accept-Language: en-US,en;q=0.9' \
--data-raw 'dataMain%5B0%5D%5BCustomerID%5D=PestRoutesOverflow1111&dataMain%5B0%5D%5BBranch%5D=Demo+Pest+Control&dataMain%5B0%5D%5BCustomerName%5D=PestRoutes+Testing01&dataMain%5B0%5D%5BCustomerAddress%5D=Walt+Disney+World+Resort%2C+Orlando%2C+FL+32830&dataMain%5B0%5D%5BCustomerCity%5D=Orlando&dataMain%5B0%5D%5BCustomerState%5D=FL&dataMain%5B0%5D%5BCustomerZipCode%5D=32830&dataMain%5B0%5D%5BCustomerPhone1%5D=4428675309&dataMain%5B0%5D%5BCustomerPhone2%5D=4438675309&dataMain%5B0%5D%5BCustomerEmail%5D=&dataMain%5B0%5D%5BCustomerStatus%5D=Act&authenticationKey=88492884d8154febd1057372867c2e34b371d8fb&authenticationToken=6915e71f53708f17dba090febd2df4f9d79364d7' \
--compressed

作为一个获取:

fetch("https://demo.pestroutes.com/api/import/main", {
"headers": {
    "accept": "application/json, text/javascript, */*; q=0.01",
    "accept-language": "en-US,en;q=0.9",
    "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "cross-site"
},
"referrerPolicy": "no-referrer-when-downgrade",
"body": "dataMain%5B0%5D%5BCustomerID%5D=PestRoutesOverflow1111&dataMain%5B0%5D%5BBranch%5D=Demo+Pest+Control&dataMain%5B0%5D%5BCustomerName%5D=PestRoutes+Testing01&dataMain%5B0%5D%5BCustomerAddress%5D=Walt+Disney+World+Resort%2C+Orlando%2C+FL+32830&dataMain%5B0%5D%5BCustomerCity%5D=Orlando&dataMain%5B0%5D%5BCustomerState%5D=FL&dataMain%5B0%5D%5BCustomerZipCode%5D=32830&dataMain%5B0%5D%5BCustomerPhone1%5D=4428675309&dataMain%5B0%5D%5BCustomerPhone2%5D=4438675309&dataMain%5B0%5D%5BCustomerEmail%5D=&dataMain%5B0%5D%5BCustomerStatus%5D=Act&authenticationKey=88492884d8154febd1057372867c2e34b371d8fb&authenticationToken=6915e71f53708f17dba090febd2df4f9d79364d7",
"method": "POST",
"mode": "cors",
"credentials": "omit"
}).then( r=>r.json()).then(console.log);

首次运行结果:

{
    "params": {
        "endpoint": "import",
        "action": "main",
        "dataMain": [],
        "authenticationKey": "88492884d8154febd1057372867c2e34b371d8fb",
        "authenticationToken": "6915e71f53708f17dba090febd2df4f9d79364d7"
    },
    "tokenUsage": {
        "requestsReadToday": "0",
        "requestsWriteToday": "1",
        "requestsReadInLastMinute": "0",
        "requestsWriteInLastMinute": "0"
    },
    "tokenLimits": {
        "limitReadRequestsPerMinute": 1000,
        "limitReadRequestsPerDay": 1000,
        "limitWriteRequestsPerMinute": 1000,
        "limitWriteRequestsPerDay": 1000
    },
    "requestAction": "main",
    "endpoint": "import",
    "success": true,
    "customersImported": [
        {
            "CustomerID": "PestRoutesOverflow1111",
            "PestRoutesCustomerID": "21257",
            "Action": "Created"
        }
    ],
    "processingTime": "1199 milliseconds",
    "count": 0
}

第二次运行结果:

{
    "params": {
        "endpoint": "import",
        "action": "main",
        "dataMain": [],
        "authenticationKey": "88492884d8154febd1057372867c2e34b371d8fb",
        "authenticationToken": "6915e71f53708f17dba090febd2df4f9d79364d7"
    },
    "tokenUsage": {
        "requestsReadToday": "0",
        "requestsWriteToday": "2",
        "requestsReadInLastMinute": "1",
        "requestsWriteInLastMinute": "0"
    },
    "tokenLimits": {
        "limitReadRequestsPerMinute": 1000,
        "limitReadRequestsPerDay": 1000,
        "limitWriteRequestsPerMinute": 1000,
        "limitWriteRequestsPerDay": 1000
    },
    "requestAction": "main",
    "endpoint": "import",
    "success": true,
    "customersImported": [
        {
            "CustomerID": "PestRoutesOverflow1111",
            "PestRoutesCustomerID": "21257",
            "Action": "Updated"
        }
    ],
    "processingTime": "1036 milliseconds",
    "count": 0
}

请注意,虽然具有相同 CustomerID 的第二个请求将更新,但使用此端点进行客户更新非常危险,不推荐使用。(给我发电子邮件以获取替代工作流程)

请注意,结果中的 dataMain 对象始终为空。对于大多数 PestRoutes 端点,此参数数组将完全按照接收到的方式返回有效负载,但这是一个遗留端点,输出有点奇怪;因此,您可以将该字段的空白视为此特定端点的错误症状。

至于编码内容类型;application/x-www-form-urlencoded 和 multipart/form-data 被服务器接受。

请通过电子邮件与我联系 michael ~at~pesroutes.com 以获得进一步的帮助:)


推荐阅读