【发布时间】:2020-09-12 09:30:26
【问题描述】:
我正在使用 Google Apps 脚本和自定义函数来调用外部 API 来验证电话号码。
下面是我的函数的代码。
/**
* This CUSTOM FUNCTION uses the numVerify API to validate
* a phone number based on the input from JotForm and a
* country code which is derived from the JotForm country
*
* Numverify website: https://numverify.com/dashboard (account via LastPass)
* Numverify docs: https://numverify.com/documentation
*/
function PHONE_CHECK(number, country){
if(country == "")
return [["", "country_not_set"]]
// check the API result has already been retrieved
var range = SpreadsheetApp.getActiveSheet().getActiveRange()
var apires = range.offset(0, 1).getValue()
if(apires.length > 0)
return range.offset(0, 0, 1, 2).getValues()
var url = 'http://apilayer.net/api/validate'
+ '?access_key=' + NUMVERIFY_KEY
+ '&number=' + encodeURIComponent(number)
+ '&country_code=' + encodeURIComponent(country)
+ '&format=1';
var response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
var json = response.getContentText();
var data = JSON.parse(json);
if(data.valid !== undefined){
if(data.valid){
return [[data.international_format, "OK"]]
}else{
return [["", "invalid_number"]] // overflows data to the next column (API Error) while keeping the phone field clear for import into TL
}
}else if(data.success !== undefined){
if(data.error.type.length > 0){
return [[number, data.error.type]]
}else{
return [[number, "no_error_type"]]
}
}else{
return [[number, "unexpected_error"]] // this generally shouldn't happen...
}
}
给定这个公式,它需要一个电话号码和国家代码,然后它会根据 numverify API 检查电话号码,并将结果返回到单元格中并溢出到它右侧的单元格。溢出用于指示 API 是否调用成功,并检查结果是否已经检索到。
示例:
=PHONE_CHECK("+32123456789", "BE")
请注意,第一个单元格是空的,因为 API 返回“无效电话号码”代码。由于隐私原因,我不会在这里放任何真实的电话号码。如果我使用的是真实电话号码,第一个单元格将包含以国际号码格式格式化的电话号码。
由于我使用的是免费计划,如果我已经知道结果是什么,我不想每次都重新运行该函数,因为我不想遇到速率限制。 不幸的是,这似乎不起作用,它会定期(看起来每天一次)刷新工作表中每一行的结果。
那么两个问题:
- 检查 API 结果然后退出函数时我的逻辑有问题吗? (代码见下文)
- 如果逻辑正确,为什么 Google 表格似乎会定期忽略(或刷新?)第二列中的值并调用外部 API?
var range = SpreadsheetApp.getActiveSheet().getActiveRange() // get the cell from which the function is called
var apires = range.offset(0, 1).getValue() // get the values directly to the right of the cell
if(apires.length > 0) // check if there's anything there...
return range.offset(0, 0, 1, 2).getValues() // return an array that basically just resets the same values, effectively stopping the script from running
【问题讨论】:
标签: google-apps-script custom-function