Google 致力于为黑人社区推动种族平等。查看具体举措
本頁面由 Cloud Translation API 翻譯而成。
Switch to English

通過您的應用調用功能

Firebase客戶端SDK的雲功能可讓您直接從Firebase應用程序調用功能。要以這種方式從您的應用程序中調用函數,請在Cloud Functions中編寫並部署HTTPS Callable函數,然後添加客戶端邏輯以從您的應用程序中調用該函數。

重要的是要記住,HTTPS可調用函數HTTP函數相似但不相同。要使用HTTPS可調用函數,必須將平台的客戶端SDK與這些functions.https一起使用。https後端API(或實現協議)。可調用項與HTTP函數有以下主要區別:

  • 對於可調用對象,Firebase身份驗證和FCM令牌(如果可用)會自動包含在請求中。
  • functions.https.onCall .https.onCall觸發器會自動反序列化請求正文並驗證auth令牌。

用於雲功能的Firebase SDK v0.9.1和更高版本可與以下Firebase客戶端SDK最低版本進行互操作,以支持HTTPS可調用功能:

  • 適用於iOS 7.11.0的Firebase SDK
  • 適用於Android 19.2.0的Firebase SDK
  • Firebase JavaScript SDK 8.4.1
  • Firebase模塊化Web SDK 9.0版

如果要向在不受支持的平台上構建的應用程序添加類似的功能,請參閱https.onCall協議規範。本指南的其餘部分提供了有關如何針對iOS,Android,Web,C ++和Unity編寫,部署和調用HTTPS可調用函數的說明。

編寫並部署可調用函數

使用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時將可調用對象的位置與設置的位置對齊。

發回結果

要將數據發送回客戶端,請返回可以進行JSON編碼的數據。例如,要返回加法運算的結果:

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

要在異步操作後返回數據,請返回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時,它將與所有其他函數一起firebase deploy 。要僅部署可調用對象,請使用--only參數,如圖所示,以執行部分部署

$ firebase deploy --only functions:addMessage

如果在部署功能時遇到權限錯誤,請確保將適當的IAM角色分配給運行部署命令的用戶。

設置您的客戶開發環境

確保滿足所有先決條件,然後將所需的依賴項和客戶端庫添加到您的應用程序。

的iOS

  1. 按照說明將Firebase添加到您的iOS應用
  2. 將Cloud Functions窗格添加到您的Podfile
    pod 'Firebase/Functions'
  3. 保存文件,然後運行:
    pod install

Web v9

  1. 按照說明將Firebase添加到您的Web應用程序
  2. 將Firebase核心和Cloud Functions客戶端庫添加到您的應用中:
    <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-functions.js"></script>
    

Cloud Functions SDK也作為npm軟件包提供。

  1. 從終端運行以下命令:
    npm install firebase@8.4.1 --save
    
  2. 手動同時要求Firebase核心和Cloud功能:

    import { initializeApp } from 'firebase/app';
    import { initializeFunctions } from 'firebase/functions';

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

Web v8

  1. 按照說明將Firebase添加到您的Web應用程序
  2. 將Firebase核心和Cloud Functions客戶端庫添加到您的應用中:
    <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.4.1/firebase-functions.js"></script>
    

Cloud Functions SDK也作為npm軟件包提供。

  1. 從終端運行以下命令:
    npm install firebase@8.4.1 --save
    
  2. 手動要求Firebase核心和Cloud功能:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

爪哇

  1. 按照說明將Firebase添加到您的Android應用

  2. 使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為app/build.gradle )中聲明Cloud Functions Android庫的依賴app/build.gradle

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:27.1.0')
    
        // Declare 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 {
        // Declare 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:19.2.0'
    }
    

Kotlin + KTX

  1. 按照說明將Firebase添加到您的Android應用

  2. 使用Firebase Android BoM ,在模塊(應用程序級)Gradle文件(通常為app/build.gradle )中聲明Cloud Functions Android庫的依賴app/build.gradle

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:27.1.0')
    
        // Declare 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-ktx'
    }
    

    通過使用Firebase Android BoM ,您的應用將始終使用Firebase Android庫的兼容版本。

    (可選)使用BoM聲明Firebase庫依賴關係

    如果選擇不使用Firebase BoM,則必須在其依賴關係行中指定每個Firebase庫版本。

    請注意,如果您在應用中使用多個Firebase庫,我們強烈建議您使用BoM來管理庫版本,以確保所有版本都兼容。

    dependencies {
        // Declare 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-ktx:19.2.0'
    }
    

C ++

對於帶有Android的C ++

  1. 按照說明將Firebase添加到您的C ++項目
  2. firebase_functions庫添加到您的CMakeLists.txt文件。

對於帶有iOS的C ++

  1. 按照說明將Firebase添加到您的C ++項目
  2. 將Cloud Functions窗格添加到您的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.unitypackage火力地堡統一SDK ,以您的統一項目。

初始化客戶端SDK

初始化Cloud Functions實例:

迅速

lazy var functions = Functions.functions()

物鏡

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

Web v8

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 v9

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

爪哇

private FirebaseFunctions mFunctions;
// ...
mFunctions = FirebaseFunctions.getInstance();

Kotlin + KTX

private lateinit var functions: FirebaseFunctions
// ...
functions = Firebase.functions

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 text = result?.data as? String {
    self.resultField.text = text
  }
}

物鏡

[[_functions HTTPSCallableWithName:@"addMessage"] callWithObject:@{@"text": _inputField.text}
                                                      completion:^(FIRHTTPSCallableResult * _Nullable result, NSError * _Nullable error) {
  if (error) {
    if (error.domain == FIRFunctionsErrorDomain) {
      FIRFunctionsErrorCode code = error.code;
      NSString *message = error.localizedDescription;
      NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
    }
    // ...
  }
  self->_resultField.text = result.data;
}];

Web v8

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

Web v9

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

爪哇

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

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

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

處理客戶端上的錯誤

如果服務器拋出錯誤或拒絕的結果承諾,則客戶端會收到錯誤消息。

如果由該函數返回的錯誤的類型為function.https.HttpsError ,則客戶端收到錯誤codemessage ,和details從服務器錯誤。否則,錯誤包含消息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]
  }
  // ...
}

物鏡

if (error) {
  if (error.domain == FIRFunctionsErrorDomain) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[FIRFunctionsErrorDetailsKey];
  }
  // ...
}

Web v8

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 v9

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

爪哇

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

                    // ...
                }

                // ...
            }
        });

Kotlin + KTX

addMessage(inputMessage)
        .addOnCompleteListener(OnCompleteListener { task ->
            if (!task.isSuccessful) {
                val e = task.exception
                if (e is FirebaseFunctionsException) {
                    val code = e.code
                    val details = e.details
                }

                // ...
            }

            // ...
        })

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