借助 Cloud Functions for Firebase 客户端 SDK,您可以直接从 Firebase 应用调用函数。如需以这种方式从应用调用函数,请在 Cloud Functions 中编写和部署 HTTP Callable 函数,然后添加从应用调用该函数的客户端逻辑。
请务必注意,HTTP Callable 函数与 HTTP 函数类似,但并不完全相同。如需使用 HTTP Callable 函数,您必须将适用于您平台的客户端 SDK 与后端 API 搭配使用(或实现相关协议)。Callable 函数与 HTTP 函数存在以下重要区别:
- 使用 Callable 函数时,Firebase Authentication 令牌、FCM 令牌和 App Check 令牌(如果可用)会自动包含在请求中。
 - 触发器会自动对请求正文进行反序列化,并验证身份验证令牌。
 
Firebase SDK for Cloud Functions 第 2 代及更高版本可与下列 Firebase 客户端 SDK 版本及更高版本交互,以支持 HTTPS Callable 函数:
- Firebase SDK 12.4.0(Apple 平台)
 - Firebase SDK 22.0.1(Android 平台)
 - Firebase Modular Web SDK v. 9.7.0
 
如果您要在不受支持的平台上构建的应用中添加类似功能,请参阅 https.onCall 协议规范。本指南的其余部分提供了有关如何编写、部署和调用面向 Apple、Android、Web、C++ 和 Unity 平台的 HTTP Callable 函数的说明。
编写和部署 Callable 函数
本部分中的代码示例基于一个完整的快速入门示例,该示例演示了如何使用客户端 SDK 之一向服务器端函数发送请求并获取响应。首先,导入所需的模块:
Node.js
// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/https");
const {logger} = require("firebase-functions");
// 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 Callable 函数。此方法可接受请求参数:
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 参数包含从客户端应用传递的数据以及身份验证状态等额外情境相关信息。例如,如果某个 Callable 函数用于将文本消息保存到 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", "")
Callable 函数的位置与调用客户端位置之间的距离可能会造成网络延迟。为了优化性能,请考虑在适用时指定函数位置,并确保将 Callable 函数的位置与您在客户端初始化 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}
您的函数必须返回值,或者(对于 Node.js)返回一个解析为值的 Promise。否则,该函数可能会在数据发送回客户端之前终止。如需获取指导,请参阅终止函数。
发送和接收流式传输结果
Callable 函数具有用于处理流式传输结果的机制。如果您的应用场景需要流式传输,您可以在可调用请求中配置流式传输,然后使用客户端 SDK 中的相应方法来调用该函数。
发送流式传输结果
如需高效地流式传输一段时间内生成的结果(例如来自多个单独的 API 请求或生成式 AI API 的结果),请检查 Callable 请求中的 acceptsStreaming 属性。将此属性设为 true 后,您可以使用 response.sendChunk() 将结果流式传输回客户端。
例如,如果应用需要检索多个地点的天气预报数据,Callable 函数可以将每个地点的天气预报分别发送给请求流式传输响应的客户端,而不是让客户端等待所有天气预报请求都已解析:
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 选项控制哪些来源可以访问您的函数。
默认情况下,Callable 函数会将 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。
处理错误
为了确保客户端获得有用的错误详情,可以抛出一个 functions.https.HttpsError 或 https_fn.HttpsError 实例(或者对于 Node.js,可返回一个被拒的 Promise 并包括此实例),通过 Callable 函数返回错误。此类错误有一个 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.")
部署 Callable 函数
当您在 index.js 内保存已完成的 Callable 函数后,系统会在您运行 firebase deploy 时部署该函数以及其他所有函数。如需只部署 Callable 函数,请按如下所示的方式使用 --only 参数执行部分部署:
firebase deploy --only functions:addMessage
如果在部署函数时遇到权限错误,请确保已将适当的 IAM 角色分配给运行部署命令的用户。
设置您的客户端开发环境
请确保您满足所有前提条件,并将必要的依赖项和客户端库添加到您的应用。
iOS+
按照相关说明将 Firebase 添加到您的 Apple 应用。
使用 Swift Package Manager 安装和管理 Firebase 依赖项。
- 在 Xcode 中打开您的应用项目,依次点击 File(文件)> Add Packages(添加软件包)。
 - 出现提示时,添加 Firebase Apple 平台 SDK 代码库:
 - 选择 Cloud Functions 库。
 - 将 
-ObjC标志添加到目标 build 设置的“其他链接器标志”部分。 - 完成之后,Xcode 将会自动开始在后台解析和下载您的依赖项。
 
https://github.com/firebase/firebase-ios-sdk.git
Web
- 按照相关说明将 Firebase 添加到您的 Web 应用。请务必在终端运行以下命令:
npm install firebase@12.4.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);
Android
按照相关说明将 Firebase 添加到您的 Android 应用。
在模块(应用级)Gradle 文件(通常是
<project>/<app-module>/build.gradle.kts或<project>/<app-module>/build.gradle)中,添加 Cloud Functions 库的依赖项。我们建议使用 Firebase Android BoM 来实现库版本控制。dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:34.4.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:22.0.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。请参阅有关如何处理 Callable 函数中的错误的指南。
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,以便确保只有您的应用可以访问您的 Callable 函数端点。