Cloud Functions for Firebase 用戶端 SDK 可讓您直接從 Firebase 應用程式呼叫函式。如要透過這種方式從應用程式呼叫函式,請在 Cloud Functions 中編寫及部署 HTTP 可呼叫函式,然後新增用戶端邏輯,以便從應用程式呼叫函式。
請注意,HTTP 可呼叫函式與 HTTP 函式類似,但不完全相同。如要使用 HTTP 可呼叫函式,您必須搭配使用平台適用的用戶端 SDK 和後端 API (或實作通訊協定)。可呼叫函式與 HTTP 函式的主要差異如下:
- 使用可呼叫函式時,系統會自動在要求中加入 Firebase Authentication 權杖、FCM 權杖和 App Check 權杖 (如有)。
- 觸發條件會自動將要求主體去序列化,並驗證驗證權杖。
Cloud Functions 2nd gen 以上版本的 Firebase SDK 可與下列 Firebase 用戶端 SDK 最低版本互通,支援 HTTPS 可呼叫函式:
- 適用於 Apple 平台的 Firebase SDK 13.0.0
- Android 23.0.0 版 Firebase SDK
- Firebase Modular Web SDK 9.7.0 版
如要在不支援的平台上建構的應用程式中加入類似功能,請參閱「https.onCall 的通訊協定規格」。本指南其餘部分將說明如何編寫、部署及呼叫 Apple 平台、Android、網頁、C++ 和 Unity 的 HTTP 可呼叫函式。
編寫及部署可呼叫函式
使用 functions.https.onCall 建立 HTTPS 可呼叫函式。這個方法有兩個參數:data 和選用的 context:
// Saves a message to the Firebase Realtime Database but sanitizes the // text by removing swearwords. exports.addMessage = functions.https.onCall((data, context) => { // ... });
舉例來說,如果可呼叫函式會將簡訊儲存至 Realtime Database,data 可能會包含訊息文字,而 context 參數則代表使用者驗證資訊:
// 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;
可呼叫函式的位置與呼叫用戶端的位置之間的距離,可能會造成網路延遲。為達到最佳效能,建議您視情況指定函式位置,並確保可呼叫函式的位置與您在用戶端初始化 SDK 時設定的位置一致。
您也可以選擇附加 App Check 認證,保護後端資源,以免發生帳單詐欺或網路釣魚等濫用行為。請參閱「為 Cloud Functions 啟用 App Check 強制執行功能」。
傳回結果
如要將資料傳回用戶端,請傳回可採用 JSON 編碼的資料。舉例來說,如要傳回加法運算的結果,請按照下列步驟操作:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: "+",
operationResult: firstNumber + secondNumber,
};
如要在非同步作業後傳回資料,請傳回 promise。Promise 傳回的資料會傳回用戶端。舉例來說,您可以傳回可呼叫函式寫入 Realtime Database 的經過清理文字:
// 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};
})
處理錯誤
為確保用戶端取得實用的錯誤詳細資料,請擲回 (或傳回遭拒的 Promise) functions.https.HttpsError 執行個體,從可呼叫函式傳回錯誤。錯誤具有 code 屬性,其值可能是 functions.https.HttpsError 列出的其中一個值。錯誤也有字串 message,預設為空字串。也可以包含選用的 details 欄位,其中包含任意值。如果函式擲回 HttpsError 以外的錯誤,用戶端會收到錯誤訊息 INTERNAL 和代碼 internal。
舉例來說,函式可能會擲回資料驗證和驗證錯誤,並傳回錯誤訊息給呼叫用戶端:
// 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.");
}
部署可呼叫函式
在 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 程式庫。
- 在目標建構設定的「Other Linker Flags」部分,新增
-ObjC標記。 - 完成後,Xcode 會自動開始在背景解析及下載依附元件。
https://github.com/firebase/firebase-ios-sdk.git
Web
- 按照操作說明將 Firebase 新增至網頁應用程式。請務必在終端機中執行下列指令:
npm install firebase@13.0.0 --save
手動要求 Firebase 核心和 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);
Web
- 按照操作說明將 Firebase 新增至網頁應用程式。
- 將 Firebase Core 和 Cloud Functions 用戶端程式庫新增至應用程式:
<script src="https://www.gstatic.com/firebasejs/8.10.1/firebase.js"></script> <script src="https://www.gstatic.com/firebasejs/8.10.1/firebase-functions.js"></script>
Cloud Functions SDK 也提供 npm 套件。
- 在終端機中執行下列指令:
npm install firebase@8.10.1 --save
- 手動要求 Firebase 核心和 Cloud Functions:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin
按照操作說明將 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:35.0.2")) // 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:23.0.0") }
Java
按照操作說明將 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:35.0.2")) // 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:23.0.0") }
Dart
按照操作說明將 Firebase 新增至 Flutter 應用程式。
在 Flutter 專案的根目錄中,執行下列指令來安裝外掛程式:
flutter pub add cloud_functions完成後,請重新建構 Flutter 應用程式:
flutter run安裝完成後,只要在 Dart 程式碼中匯入
cloud_functions外掛程式,即可存取該外掛程式:import 'package:cloud_functions/cloud_functions.dart';
C++
C++ 搭配 Android:
- 按照操作說明將 Firebase 新增至 C++ 專案。
- 將
firebase_functions程式庫新增至CMakeLists.txt檔案。
搭配 Apple 平台使用 C++:
- 按照操作說明將 Firebase 新增至 C++ 專案。
- 將 Cloud Functions Pod 新增至
Podfile:pod 'Firebase/Functions'
- 儲存檔案,然後執行:
pod install
- 將 Firebase C++ SDK 的 Firebase 核心和 Cloud Functions 架構新增至 Xcode 專案。
firebase.frameworkfirebase_functions.framework
Unity
- 按照操作說明將 Firebase 新增至 Unity 專案。
- 將 Firebase Unity SDK 的
FirebaseFunctions.unitypackage新增至 Unity 專案。
初始化用戶端 SDK
初始化 Cloud Functions 的例項:
Swift
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
// Initialize Cloud Functions through Firebase
var functions = firebase.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();
Dart
final functions = FirebaseFunctions.instance;
C++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
Unity
functions = Firebase.Functions.DefaultInstance;
呼叫函式
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;
}
});
設定用戶端逾時
根據預設,Cloud Functions 用戶端 SDK 會對可呼叫要求設定 70 秒的逾時時間。如果可呼叫函式需要超過 70 秒才能完成,用戶端 SDK 會終止要求,並傳回 DEADLINE_EXCEEDED (deadline-exceeded) 錯誤,即使您設定了較長的伺服器端逾時時間也一樣。
如要支援長時間執行的可呼叫函式,您必須增加伺服器和用戶端兩者的逾時時間:
- 延長伺服器端函式逾時時間 (請參閱「設定逾時和記憶體配置」)。
- 在應用程式中設定可呼叫參照時,請增加用戶端逾時時間:
Swift
let callable = functions.httpsCallable("addMessage")
callable.timeoutInterval = 300 // 300 seconds (default is 70)
let result = try await callable.call(["text": text, "push": true])
Objective-C
FIRHTTPSCallable *callable = [self.functions HTTPSCallableWithName:@"addMessage"];
callable.timeoutInterval = 300; // 300 seconds (default is 70)
[callable callWithObject:@{@"text": text, @"push": @YES}
completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
// ...
}];
Web
var addMessage = firebase.functions().httpsCallable('addMessage', {
timeout: 300000, // 300 seconds in milliseconds (default is 70000)
});
addMessage({ text: messageText })
.then((result) => {
// ...
});
Web
import { getFunctions, httpsCallable } from "firebase/functions";
const functions = getFunctions();
const addMessage = httpsCallable(functions, 'addMessage', {
timeout: 300000, // 300 seconds in milliseconds (default is 70000)
});
const result = await addMessage({ text: messageText });
Kotlin
val callable = functions.getHttpsCallable("addMessage")
callable.setTimeout(300L, TimeUnit.SECONDS)
val result = callable.call(data).await()
Java
HttpsCallableReference callable = mFunctions.getHttpsCallable("addMessage");
callable.setTimeout(300L, TimeUnit.SECONDS);
Task<HttpsCallableResult> result = callable.call(data);
Dart
final callable = FirebaseFunctions.instance.httpsCallable(
'addMessage',
options: HttpsCallableOptions(
timeout: const Duration(seconds: 300),
),
);
final result = await callable.call({
'text': text,
'push': true,
});
建議做法:使用 App Check 防範濫用行為
在推出應用程式前,請務必啟用 App Check,確保只有您的應用程式可以存取可呼叫函式端點。