從您的應用調用函數


Cloud Functions for Firebase 用戶端 SDK 可讓您直接從 Firebase 應用呼叫函數。若要以這種方式從您的應用程式呼叫函數,請在 Cloud Functions 中編寫並部署 HTTP Callable 函數,然後新增客戶端邏輯以從您的應用程式呼叫該函數。

請務必記住,HTTP 可呼叫函數與 HTTP 函數相似但不完全相同。若要使用 HTTP 可呼叫函數,您必須使用適用於您平台的用戶端 SDK 以及後端 API(或實作協定)。 Callables 與 HTTP 函數有以下主要差異:

  • 對於可呼叫對象,Firebase 驗證令牌、FCM 令牌和應用程式檢查令牌(如果可用)會自動包含在請求中。
  • 觸發器自動反序列化請求正文並驗證身份驗證令牌。

適用於 Cloud Functions 第二代及更高版本的 Firebase SDK 與這些 Firebase 用戶端 SDK 最低版本進行互通,以支援 HTTPS 可呼叫函數:

  • 適用於 Apple 平台的 Firebase SDK 10.19.0
  • 適用於 Android 20.4.0 的 Firebase SDK
  • Firebase 模組化 Web SDK v. 9.7.0

如果您想為在不支援的平台上建置的應用程式添加類似的功能,請參閱https.onCall的協定規格。本指南的其餘部分提供了有關如何為 Apple 平台、Android、Web、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) => {
  // ...
});

例如,對於將文字訊息儲存到即時資料庫的可呼叫函數, data可以包含訊息文本,而context參數表示使用者身份驗證資訊:

// Message text passed from the client.
const text = data.text;
// Authentication / user information is automatically added to the request.
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;

可呼叫函數的位置與呼叫客戶端的位置之間的距離可能會產生網路延遲。為了優化效能,請考慮在適用的情況下指定函數位置,並確保將可呼叫函數的位置與在客戶端初始化 SDK時設定的位置對齊。

或者,您可以附加 App Check 證明,以協助保護您的後端資源免於濫用,例如計費詐欺或網路釣魚。請參閱為 Cloud Functions 啟用應用程式檢查強制執行

傳回結果

若要將資料傳回客戶端,請傳回可以 JSON 編碼的資料。例如,要傳回加法運算的結果:

// returning result.
return {
  firstNumber: firstNumber,
  secondNumber: secondNumber,
  operator: '+',
  operationResult: firstNumber + secondNumber,
};

若要在非同步操作後返回數據,請返回一個 Promise。 Promise 傳回的資料被傳送回客戶端。例如,您可以傳回可呼叫函數寫入即時資料庫的經過清理的文字:

// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize the message.
return admin.database().ref('/messages').push({
  text: sanitizedMessage,
  author: { uid, name, picture, email },
}).then(() => {
  console.log('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 functions.https.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 (!context.auth) {
  // Throwing an HttpsError so that the client gets the error details.
  throw new functions.https.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 相依性。

  1. 在 Xcode 中,開啟應用程式項目,導覽至File > Add Packages
  2. 出現提示時,新增 Firebase Apple 平台 SDK 儲存庫:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. 選擇雲函數庫。
  5. -ObjC標誌新增至目標建置設定的「其他連結器標誌」部分。
  6. 完成後,Xcode 將自動開始在背景解析並下載您的依賴項。

網路模組化API

  1. 按照說明將Firebase 新增到您的 Web 應用程式。確保從終端機執行以下命令:
    npm install firebase@10.7.1 --save
    
  2. 手動需要 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 命名空間 API

  1. 按照說明將Firebase 新增到您的 Web 應用程式
  2. 將 Firebase 核心和 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 套件提供。

  1. 從終端機執行以下命令:
    npm install firebase@8.10.1 --save
    
  2. 手動需要 Firebase 核心和 Cloud Functions:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

Kotlin+KTX

  1. 按照說明將Firebase 新增到您的 Android 應用程式

  2. 模組(應用程式層級)Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,新增 Cloud Functions 的依賴項Android 的函式庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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:20.4.0")
    }
    
    正在尋找 Kotlin 特定的庫模組?2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。

Java

  1. 按照說明將Firebase 新增到您的 Android 應用程式

  2. 模組(應用程式層級)Gradle 檔案(通常<project>/<app-module>/build.gradle.kts<project>/<app-module>/build.gradle )中,新增 Cloud Functions 的依賴項Android 的函式庫。我們建議使用Firebase Android BoM來控制函式庫版本控制。

    dependencies {
        // Import the BoM for the Firebase platform
        implementation(platform("com.google.firebase:firebase-bom:32.7.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:20.4.0")
    }
    
    正在尋找 Kotlin 特定的庫模組?2023 年 10 月(Firebase BoM 32.5.0)開始,Kotlin 和 Java 開發人員都可以依賴主庫模組(有關詳細信息,請參閱有關此計劃的常見問題解答)。

Dart

  1. 按照說明將Firebase 新增到您的 Flutter 應用程式

  2. 從 Flutter 專案的根目錄中,執行以下命令來安裝外掛程式:

    flutter pub add cloud_functions
    
  3. 完成後,重建您的 Flutter 應用程式:

    flutter run
    
  4. 安裝後,您可以透過將其匯入 Dart 程式碼來存取cloud_functions外掛程式:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

對於有 Android 的 C++

  1. 按照說明將Firebase 新增到您的 C++ 專案
  2. firebase_functions庫加入CMakeLists.txt檔案中。

對於Apple 平台上的 C++

  1. 按照說明將Firebase 新增到您的 C++ 專案
  2. 將 Cloud Functions pod 加入您的Podfile
    pod 'Firebase/Functions'
  3. 儲存文件,然後執行:
    pod install
  4. Firebase C++ SDK中的 Firebase 核心和 Cloud Functions 框架新增至您的 Xcode 專案。
    • firebase.framework
    • firebase_functions.framework

統一

  1. 按照說明將Firebase 新增到您的 Unity 專案
  2. FirebaseFunctions.unitypackageFirebase Unity SDK新增至您的 Unity 專案。

初始化客戶端SDK

初始化 Cloud Functions 實例:

迅速

lazy var functions = Functions.functions()

Objective-C

@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];

Web 命名空間 API

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();

網路模組化API

const app = initializeApp({
  projectId: '### CLOUD FUNCTIONS PROJECT ID ###',
  apiKey: '### FIREBASE API KEY ###',
  authDomain: '### FIREBASE AUTH DOMAIN ###',
});
const functions = getFunctions(app);

Kotlin+KTX

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);

統一

functions = Firebase.Functions.DefaultInstance;

呼叫函數

迅速

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 命名空間 API

var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
  .then((result) => {
    // Read result of the Cloud Function.
    var sanitizedMessage = result.data.text;
  });

網路模組化API

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+KTX

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);
}

統一

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 ,則用戶端會收到來自伺服器錯誤的錯誤codemessagedetails 。否則,錯誤包含訊息INTERNAL和代碼INTERNAL 。請參閱有關如何處理可調用函數中的錯誤的指南。

迅速

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 命名空間 API

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;
    // ...
  });

網路模組化API

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+KTX

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);
  // ...

統一

 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;
  }
});

在啟動應用程式之前,您應該啟用應用程式檢查以幫助確保只有您的應用程式可以存取您的可呼叫函數端點。