如何在Firebase Cloud Functions中调用Google Places API?



我正在尝试借助Google Places API及其自动完成功能在我的Flutter应用程序中实现位置自动完成功能。为了使 API 调用逻辑和 API 密钥远离客户端,Flutter 应用应调用 Firebase Cloud Function,然后调用 Google Places API。几天来,我一直在努力让它工作,浏览了各种文章,但我无法取得任何进展。这是我的Firebase Cloud Function的源代码:

import * as functions from "firebase-functions";
import * as axios from "axios";
export const autofillSuggestions = functions.region("europe-west3")
.https.onCall(async (data) => {
const input = data.input;
const sessionToken = data.sessiontoken;
// will be stored as an environment variable, as soon as i get cloud function to work
const googleAPIKey = "my_api_key"; 

const requestURL = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + input +
"&key=" + googleAPIKey + "&sessiontoken=" + sessionToken;
return await axios.default.get(requestURL).then((apiResponse) => {
return {predictions: apiResponse.data.predictions,
};
})
.catch((error) => {
console.log(error);
});
});

此源代码被导入到index.ts然后再次导出文件,因此问题不应该在那里。 Flutter 应用程序中的云函数调用逻辑如下所示:

HttpsCallable _getCallable(String functionName) =>
FirebaseFunctions.instance.httpsCallable(functionName);
Future<dynamic> _getSuggestionsFromGoogleMapsAPI(String input) async {
//FirebaseFunctions.instance
//    .useFunctionsEmulator(origin: 'http://localhost:5001');
final callable = _getCallable('autofillSuggestions');
try {
final data = HashMap.of({
'sugg': input,
'sessionToken': _sessionToken,
});
final response = await callable.call(data);
return response.data;
} catch (e) {
print(e);
throw AutocompletionFailure();
}
}

当我在 Flutter 应用程序中触发云函数调用并取消注释提及useFunctionsEmulator的行时,一切正常。但是,一旦我再次注释掉这些内容并想与真正的Firebase服务器进行通信,我总是在VS Code调试控制台中收到以下错误消息:

[firebase_functions/internal] Response is not valid JSON object.

Firebase 服务器上的错误日志如下所示:

autofillSuggestions
{
"@type":"type.googleapis.com/google.cloud.audit.AuditLog",
"authenticationInfo":{"principalEmail":"my@mail.com"},
"requestMetadata": 
{
"callerIp":"10.10.101.101",
"callerSuppliedUserAgent":"FirebaseCLI/9.8.0,gzip(gfe),gzip(gfe)",
"requestAttributes":{"time":"2021-04-04T09:34:15.120516Z","auth":{}},
"destinationAttributes":{}
},
"serviceName":"cloudfunctions.googleapis.com",
"methodName":"google.cloud.functions.v1.CloudFunctionsService.SetIamPolicy",
"authorizationInfo":
[
{
"resource":"projects/my-project/locations/europe-west3/functions/autofillSuggestions",
"permission":"cloudfunctions.functions.setIamPolicy",
"granted":true,
"resourceAttributes":{}
},
{
"permission":"cloudfunctions.functions.setIamPolicy",
"granted":true,
"resourceAttributes":{}
}
],
"resourceName":"projects/my-project/locations/europe-west3/functions/autofillSuggestions",
"request":
{
"updateMask":"version,bindings",
"resource":"projects/my-project/locations/europe-west3/functions/autofillSuggestions",
"policy":
{
"bindings":
[
{
"members":["allUsers"],
"role":"roles/cloudfunctions.invoker"
}
]
},
"@type":"type.googleapis.com/google.iam.v1.SetIamPolicyRequest"
},
"response":
{
"bindings":
[
{
"members":["allUsers"],
"role":"roles/cloudfunctions.invoker"
}
],
"@type":"type.googleapis.com/google.iam.v1.Policy","etag":"BwW/IkjRmog="
},
"resourceLocation":{"currentLocations":["europe-west3"]}
}

由于它没有提到Function execution startedFunction execution terminated with ...之类的东西,我怀疑云函数根本没有被调用......我的想法是对的吗?如果是,有谁知道如何让它工作???

我把自己放在这篇文章和这篇文章上。我也发现这很有趣,还没有尝试过,因为我认为我的主要问题是云函数甚至没有被调用......

答案是 - 当然 - 相当愚蠢,但我想这是 IT 和自学的诅咒...... 如您所见,由于我的位置,我指定europe-west3作为云函数的区域。但是在获取callable引用时,我没有指定区域,这导致cloud_functionsflutter 包创建了一个默认区域设置为us-central1FirebaseFunctions实例。这搞砸了通话并导致内部错误。简单的解决方法是在颤振应用程序中:

_getCallable的新实现:

HttpsCallable _getCallable(String functionName) {
return FirebaseFunctions.instanceFor(region: 'europe-west3')
.httpsCallable(functionName);
}

相关内容

  • 没有找到相关文章

最新更新