Cloud Functions for Firebase用戶端 SDK 可讓您直接從 Firebase 應用程式呼叫函式。如要透過這種方式從應用程式呼叫函式,請在 Cloud Functions 中編寫及部署 HTTP 可呼叫函式,然後新增用戶端邏輯,從應用程式呼叫函式。
請務必注意,HTTP 可呼叫函式與 HTTP 函式類似,但並不相同。如要使用 HTTP 可呼叫函式,您必須搭配後端 API (或實作通訊協定),使用適用於您平台的用戶端 SDK。可呼叫函式與 HTTP 函式的主要差異如下:
- 如果要求中包含可呼叫的 Firebase Authentication 權杖、FCM 權杖和 App Check 權杖,系統會自動將這些權杖納入要求。
- 觸發程序會自動將要求主體去序列化,並驗證驗證權杖。
Cloud Functions 第 2 代以上裝置的 Firebase SDK 可與下列 Firebase 用戶端 SDK 最低版本互通,以支援 HTTPS 可呼叫函式:
- Firebase 適用於 Apple 平台的 SDK 11.15.0
- Firebase SDK for Android 21.2.1
- Firebase Modular Web SDK 9.7.0 版
如要在以不支援的平台建構的應用程式中新增類似功能,請參閱 https.onCall
的通訊協定規格。本指南的其餘部分會說明如何為 Apple 平台、Android、網頁、C++ 和 Unity 編寫、部署及呼叫 HTTP 可呼叫函式。
編寫及部署可呼叫的函式
本節中的程式碼範例是以完整的快速入門範例為基礎,說明如何使用其中一個 Client SDK 將要求傳送至伺服器端函式,並取得回應。如要開始使用,請匯入必要模組:
Node.js
// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/v2/https");
const {logger} = require("firebase-functions/v2");
// Dependencies for the addMessage function.
const {getDatabase} = require("firebase-admin/database");
const sanitizer = require("./sanitizer");
Python
# Dependencies for callable functions.
from firebase_functions import https_fn, options
# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app
使用平台適用的要求處理常式 (functions.https.onCall
或 on_call
),建立 HTTPS 可呼叫函式。這個方法會採用要求參數:
Node.js
// Saves a message to the Firebase Realtime Database but sanitizes the
// text by removing swearwords.
exports.addmessage = onCall((request) => {
// ...
});
Python
@https_fn.on_call()
def addmessage(req: https_fn.CallableRequest) -> Any:
"""Saves a message to the Firebase Realtime Database but sanitizes the text
by removing swear words."""
request
參數包含從用戶端應用程式傳遞的資料,以及驗證狀態等額外內容。以可呼叫函式為例,如果該函式會將文字訊息儲存至 Realtime Database,data
可能會包含訊息文字,以及 auth
中的驗證資訊:
Node.js
// Message text passed from the client.
const text = request.data.text;
// Authentication / user information is automatically added to the request.
const uid = request.auth.uid;
const name = request.auth.token.name || null;
const picture = request.auth.token.picture || null;
const email = request.auth.token.email || null;
Python
# Message text passed from the client.
text = req.data["text"]
# Authentication / user information is automatically added to the request.
uid = req.auth.uid
name = req.auth.token.get("name", "")
picture = req.auth.token.get("picture", "")
email = req.auth.token.get("email", "")
可呼叫函式的位置與呼叫端用戶端的位置之間的距離,可能會造成網路延遲。如要提升效能,請考慮在適用的情況下指定函式位置,並確保可呼叫項目的位置與您在用戶端初始化 SDK 時設定的位置一致。
您也可以選擇附加 App Check 認證,保護後端資源,避免遭到帳單詐欺或網路釣魚等濫用行為影響。請參閱「為 Cloud Functions 啟用 App Check 強制執行功能」。
傳回結果
如要將資料傳回給用戶端,請傳回可進行 JSON 編碼的資料。舉例來說,如要傳回加法運算的結果:
Node.js
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: "+",
operationResult: firstNumber + secondNumber,
};
Python
return {
"firstNumber": first_number,
"secondNumber": second_number,
"operator": "+",
"operationResult": first_number + second_number
}
訊息文字範例經過清理後,會傳回給用戶端和 Realtime Database。在 Node.js 中,這項作業可使用 JavaScript Promise 以非同步方式完成:
Node.js
// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize message.
return getDatabase().ref("/messages").push({
text: sanitizedMessage,
author: {uid, name, picture, email},
}).then(() => {
logger.info("New Message written");
// Returning the sanitized message to the client.
return {text: sanitizedMessage};
})
Python
# Saving the new message to the Realtime Database.
sanitized_message = sanitize_text(text) # Sanitize message.
db.reference("/messages").push({ # type: ignore
"text": sanitized_message,
"author": {
"uid": uid,
"name": name,
"picture": picture,
"email": email
}
})
print("New message written")
# Returning the sanitized message to the client.
return {"text": sanitized_message}
傳送及接收串流結果
可呼叫函式具有處理串流結果的機制。如有需要串流的用途,您可以在可呼叫的請求中設定串流,然後使用用戶端 SDK 中的適當方法呼叫函式。
傳送串流結果
如要有效率地串流處理隨時間產生的結果 (例如來自多個個別 API 要求或生成式 AI API),請檢查可呼叫要求中的 acceptsStreaming
屬性。將這項屬性設為 true
後,您可以使用 response.sendChunk()
將結果串流回用戶端。
舉例來說,如果應用程式需要擷取多個地點的天氣預報資料,可呼叫的函式可以分別將每個地點的預報傳送給要求串流回應的用戶端,不必等到所有預報要求都解決:
exports.getForecast = onCall(async (request, response) => { if (request.data?.locations?.length < 1) { throw new HttpsError("invalid-argument", "Missing locations to forecast"); } // fetch forecast data for all requested locations const allRequests = request.data.locations.map( async ({latitude, longitude}) => { const forecast = await weatherForecastApi(latitude, longitude); const result = {latitude, longitude, forecast}; // clients that support streaming will have each // forecast streamed to them as they complete if (request.acceptsStreaming) { response.sendChunk(result); } return result; }, ); // Return the full set of data to all clients return Promise.all(allRequests); });
請注意,response.sendChunk()
的運作方式取決於用戶端要求的特定詳細資料:
如果用戶端要求串流回應:
response.sendChunk(data)
會立即傳送資料片段。如果用戶端未要求串流回應:
response.sendChunk()
不會對該呼叫執行任何動作。所有資料準備就緒後,系統就會傳送完整的回應。
如要判斷用戶端是否要求串流回應,請檢查 request.acceptsStreaming
屬性。舉例來說,如果 request.acceptsStreaming
為 false,您可能會決定略過與準備或傳送個別區塊相關的任何耗用大量資源的工作,因為用戶端不會預期增量傳送。
接收串流結果
在一般情況下,用戶端會使用 .stream
方法要求串流,然後逐一查看結果:
Swift
func listenToWeatherForecast() async throws {
isLoading = true
defer { isLoading = false }
Functions
.functions(region: "us-central1")
let getForecast: Callable<WeatherRequest, StreamResponse<WeatherResponse, [WeatherResponse]>> = Functions.functions().httpsCallable("getForecast")
let request = WeatherRequest(locations: locations)
let stream = try getForecast.stream(request)
for try await response in stream {
switch response {
case .message(let singleResponse):
weatherData["\(singleResponse.latitude),\(singleResponse.longitude)"] = singleResponse
case .result(let arrayOfResponses):
for response in arrayOfResponses {
weatherData["\(response.latitude),\(response.longitude)"] = response
}
print("Stream ended.")
return
}
}
}
Web
// Get the callable by passing an initialized functions SDK.
const getForecast = httpsCallable(functions, "getForecast");
// Call the function with the `.stream()` method to start streaming.
const { stream, data } = await getForecast.stream({
locations: favoriteLocations,
});
// The `stream` async iterable returned by `.stream()`
// will yield a new value every time the callable
// function calls `sendChunk()`.
for await (const forecastDataChunk of stream) {
// update the UI every time a new chunk is received
// from the callable function
updateUi(forecastDataChunk);
}
// The `data` promise resolves when the callable
// function completes.
const allWeatherForecasts = await data;
finalizeUi(allWeatherForecasts);
如圖所示,循環處理 stream
非同步可疊代項目。等待 data
promise,向用戶端表示要求已完成
Kotlin
// Get the callable by passing an initialized functions SDK.
val getForecast = functions.getHttpsCallable("getForecast");
// Call the function with the `.stream()` method and convert it to a flow
getForecast.stream(
mapOf("locations" to favoriteLocations)
).asFlow().collect { response ->
when (response) {
is StreamResponse.Message -> {
// The flow will emit a [StreamResponse.Message] value every time the
// callable function calls `sendChunk()`.
val forecastDataChunk = response.message.data as Map<String, Any>
// Update the UI every time a new chunk is received
// from the callable function
updateUI(
forecastDataChunk["latitude"] as Double,
forecastDataChunk["longitude"] as Double,
forecastDataChunk["forecast"] as Double,
)
}
is StreamResponse.Result -> {
// The flow will emit a [StreamResponse.Result] value when the
// callable function completes.
val allWeatherForecasts = response.result.data as List<Map<String, Any>>
finalizeUI(allWeatherForecasts)
}
}
}
如要使用 asFlow()
擴充功能函式,請將 org.jetbrains.kotlinx:kotlinx-coroutines-reactive
程式庫新增為應用程式 build.gradle(.kts)
檔案的依附元件。
Java
// Get the callable by passing an initialized functions SDK.
HttpsCallableReference getForecast = mFunctions.getHttpsCallable("getForecast");
getForecast.stream(
new HashMap<String, Object>() {{
put("locations", favoriteLocations);
}}
).subscribe(new Subscriber<StreamResponse>() {
@Override
public void onSubscribe(Subscription subscription) {
subscription.request(Long.MAX_VALUE);
}
@Override
public void onNext(StreamResponse streamResponse) {
if (streamResponse instanceof StreamResponse.Message) {
// The flow will emit a [StreamResponse.Message] value every time the
// callable function calls `sendChunk()`.
StreamResponse.Message response = (StreamResponse.Message) streamResponse;
Map<String, Object> forecastDataChunk =
(Map<String, Object>) response.getMessage().getData();
// Update the UI every time a new chunk is received
// from the callable function
updateUI(
(double) forecastDataChunk.get("latitude"),
(double) forecastDataChunk.get("longitude"),
(double) forecastDataChunk.get("forecast")
);
} else if(streamResponse instanceof StreamResponse.Result) {
// The flow will emit a [StreamResponse.Result] value when the
// callable function completes.
StreamResponse.Result response = (StreamResponse.Result) streamResponse;
List<Map<String, Object>> allWeatherForecasts =
(List<Map<String, Object>>) response.getResult().getData();
finalizeUI();
}
}
@Override
public void onError(Throwable throwable) {
// an error occurred in the function
}
@Override
public void onComplete() {
}
});
設定 CORS (跨源資源共享)
使用 cors
選項控管可存取函式的來源。
根據預設,可呼叫函式的 CORS 設定會允許來自所有來源的要求。如要允許部分跨來源要求,但不是全部,請傳遞應允許的特定網域或規則運算式清單。例如:
Node.js
const { onCall } = require("firebase-functions/v2/https");
exports.getGreeting = onCall(
{ cors: [/firebase\.com$/, "https://flutter.com"] },
(request) => {
return "Hello, world!";
}
);
如要禁止跨來源要求,請將 cors
政策設為 false
。
處理錯誤
如要確保用戶端取得實用的錯誤詳細資料,請擲回 (或針對 Node.js 傳回以 functions.https.HttpsError
或 https_fn.HttpsError
執行個體拒絕的 Promise) 可呼叫函式的錯誤。錯誤具有 code
屬性,該屬性可以是 gRPC 狀態碼中列出的其中一個值。錯誤也包含字串 message
,預設為空字串。也可以選擇性地加入 details
欄位,並提供任意值。如果函式擲回的錯誤不是 HTTPS 錯誤,用戶端會收到錯誤訊息 INTERNAL
和錯誤代碼 internal
。
舉例來說,函式可能會擲回資料驗證和驗證錯誤,並附上錯誤訊息,以便傳回給呼叫端用戶端:
Node.js
// Checking attribute.
if (!(typeof text === "string") || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("invalid-argument", "The function must be called " +
"with one arguments \"text\" containing the message text to add.");
}
// Checking that the user is authenticated.
if (!request.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("failed-precondition", "The function must be " +
"called while authenticated.");
}
Python
# Checking attribute.
if not isinstance(text, str) or len(text) < 1:
# Throwing an HttpsError so that the client gets the error details.
raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
message=('The function must be called with one argument, "text",'
" containing the message text to add."))
# Checking that the user is authenticated.
if req.auth is None:
# Throwing an HttpsError so that the client gets the error details.
raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.FAILED_PRECONDITION,
message="The function must be called while authenticated.")
部署可呼叫函式
在 index.js
中儲存已完成的可呼叫函式後,執行 firebase deploy
時,系統會一併部署該函式和所有其他函式。如要只部署可呼叫函式,請使用 --only
引數,如以下範例所示,執行部分部署:
firebase deploy --only functions:addMessage
如果在部署函式時發生權限錯誤,請確認已將適當的 IAM 角色指派給執行部署指令的使用者。
設定用戶端開發環境
請確認您符合所有必要條件,然後將必要的依附元件和用戶端程式庫新增至應用程式。
iOS+
按照操作說明將 Firebase 新增至 Apple 應用程式。
使用 Swift Package Manager 安裝及管理 Firebase 依附元件。
- 在 Xcode 中保持開啟應用程式專案,然後依序點選「File」(檔案) 和「Add Packages」(新增 Package)。
- 系統提示時,請新增 Firebase Apple 平台 SDK 存放區:
- 選擇 Cloud Functions 程式庫。
- 將
-ObjC
標記新增至目標建構設定的「Other Linker Flags」部分。 - 完成後,Xcode 會自動開始在背景中解析並下載依附元件。
https://github.com/firebase/firebase-ios-sdk.git
Web
- 按照操作說明將 Firebase 新增至您的網頁應用程式。請務必從終端機執行下列指令:
npm install firebase@11.10.0 --save
手動要求 Firebase Core 和 Cloud Functions:
import { initializeApp } from 'firebase/app'; import { getFunctions } from 'firebase/functions'; const app = initializeApp({ projectId: '### CLOUD FUNCTIONS PROJECT ID ###', apiKey: '### FIREBASE API KEY ###', authDomain: '### FIREBASE AUTH DOMAIN ###', }); const functions = getFunctions(app);
Android
按照操作說明將 Firebase 新增至 Android 應用程式。
在模組 (應用程式層級) Gradle 檔案 (通常是
<project>/<app-module>/build.gradle.kts
或<project>/<app-module>/build.gradle
) 中,加入 Android 適用的 Cloud Functions 程式庫依附元件。建議使用 Firebase Android BoM 控制程式庫版本。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.16.0")) // Add the dependency for the Cloud Functions library // When using the BoM, you don't specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions") }
只要使用 Firebase Android BoM,應用程式就會一律使用相容的 Firebase Android 程式庫版本。
(替代做法) 不使用 BoM 新增 Firebase 程式庫依附元件
如果選擇不使用 Firebase BoM,則必須在依附元件行中指定每個 Firebase 程式庫版本。
請注意,如果應用程式使用多個 Firebase 程式庫,強烈建議使用 BoM 管理程式庫版本,確保所有版本都相容。
dependencies { // Add the dependency for the Cloud Functions library // When NOT using the BoM, you must specify versions in Firebase library dependencies implementation("com.google.firebase:firebase-functions:21.2.1") }
初始化用戶端 SDK
初始化 Cloud Functions 的例項:
Swift
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web
const app = initializeApp({
projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
});
const functions = getFunctions(app);
Kotlin
private lateinit var functions: FirebaseFunctions // ... functions = Firebase.functions
Java
private FirebaseFunctions mFunctions; // ... mFunctions = FirebaseFunctions.getInstance();
呼叫函式
Swift
functions.httpsCallable("addMessage").call(["text": inputField.text]) { result, error in
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
if let data = result?.data as? [String: Any], let text = data["text"] as? String {
self.resultField.text = text
}
}
Objective-C
[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
self->_resultField.text = result.data[@"text"];
}];
Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Web
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
const data = result.data;
const sanitizedMessage = data.text;
});
Kotlin
private fun addMessage(text: String): Task<String> { // Create the arguments to the callable function. val data = hashMapOf( "text" to text, "push" to true, ) return functions .getHttpsCallable("addMessage") .call(data) .continueWith { task -> // This continuation runs on either success or failure, but if the task // has failed then result will throw an Exception which will be // propagated down. val result = task.result?.data as String result } }
Java
private Task<String> addMessage(String text) { // Create the arguments to the callable function. Map<String, Object> data = new HashMap<>(); data.put("text", text); data.put("push", true); return mFunctions .getHttpsCallable("addMessage") .call(data) .continueWith(new Continuation<HttpsCallableResult, String>() { @Override public String then(@NonNull Task<HttpsCallableResult> task) throws Exception { // This continuation runs on either success or failure, but if the task // has failed then getResult() will throw an Exception which will be // propagated down. String result = (String) task.getResult().getData(); return result; } }); }
Dart
final result = await FirebaseFunctions.instance.httpsCallable('addMessage').call(
{
"text": text,
"push": true,
},
);
_response = result.data as String;
C++
firebase::Future<firebase::functions::HttpsCallableResult> AddMessage(
const std::string& text) {
// Create the arguments to the callable function.
firebase::Variant data = firebase::Variant::EmptyMap();
data.map()["text"] = firebase::Variant(text);
data.map()["push"] = true;
// Call the function and add a callback for the result.
firebase::functions::HttpsCallableReference doSomething =
functions->GetHttpsCallable("addMessage");
return doSomething.Call(data);
}
Unity
private Task<string> addMessage(string text) {
// Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = text;
data["push"] = true;
// Call the function and extract the operation from the result.
var function = functions.GetHttpsCallable("addMessage");
return function.CallAsync(data).ContinueWith((task) => {
return (string) task.Result.Data;
});
}
處理用戶端錯誤
如果伺服器擲回錯誤,或產生的 Promise 遭到拒絕,用戶端就會收到錯誤訊息。
如果函式傳回的錯誤屬於 function.https.HttpsError
類型,用戶端就會從伺服器錯誤收到 code
、message
和 details
錯誤。否則,錯誤會包含 INTERNAL
訊息和 INTERNAL
程式碼。請參閱處理可呼叫函式中的錯誤指引。
Swift
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
// ...
}
Objective-C
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
})
.catch((error) => {
// Getting the Error details.
var code = error.code;
var message = error.message;
var details = error.details;
// ...
});
Web
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
/** @type {any} */
const data = result.data;
const sanitizedMessage = data.text;
})
.catch((error) => {
// Getting the Error details.
const code = error.code;
const message = error.message;
const details = error.details;
// ...
});
Kotlin
addMessage(inputMessage) .addOnCompleteListener { task -> if (!task.isSuccessful) { val e = task.exception if (e is FirebaseFunctionsException) { val code = e.code val details = e.details } } }
Java
addMessage(inputMessage) .addOnCompleteListener(new OnCompleteListener<String>() { @Override public void onComplete(@NonNull Task<String> task) { if (!task.isSuccessful()) { Exception e = task.getException(); if (e instanceof FirebaseFunctionsException) { FirebaseFunctionsException ffe = (FirebaseFunctionsException) e; FirebaseFunctionsException.Code code = ffe.getCode(); Object details = ffe.getDetails(); } } } });
Dart
try {
final result =
await FirebaseFunctions.instance.httpsCallable('addMessage').call();
} on FirebaseFunctionsException catch (error) {
print(error.code);
print(error.details);
print(error.message);
}
C++
void OnAddMessageCallback(
const firebase::Future<firebase::functions::HttpsCallableResult>& future) {
if (future.error() != firebase::functions::kErrorNone) {
// Function error code, will be kErrorInternal if the failure was not
// handled properly in the function call.
auto code = static_cast<firebase::functions::Error>(future.error());
// Display the error in the UI.
DisplayError(code, future.error_message());
return;
}
const firebase::functions::HttpsCallableResult* result = future.result();
firebase::Variant data = result->data();
// This will assert if the result returned from the function wasn't a string.
std::string message = data.string_value();
// Display the result in the UI.
DisplayResult(message);
}
// ...
// ...
auto future = AddMessage(message);
future.OnCompletion(OnAddMessageCallback);
// ...
Unity
addMessage(text).ContinueWith((task) => {
if (task.IsFaulted) {
foreach (var inner in task.Exception.InnerExceptions) {
if (inner is FunctionsException) {
var e = (FunctionsException) inner;
// Function error code, will be INTERNAL if the failure
// was not handled properly in the function call.
var code = e.ErrorCode;
var message = e.ErrorMessage;
}
}
} else {
string result = task.Result;
}
});
建議做法:使用 App Check 防範濫用行為
啟動應用程式前,請啟用 App Check,確保只有您的應用程式可以存取可呼叫函式端點。