פונקציות התקשרות מהאפליקציה שלך


ערכות SDK של לקוח Cloud Functions for Firebase מאפשרות לך לקרוא לפונקציות ישירות מאפליקציית Firebase. כדי לקרוא לפונקציה מהאפליקציה שלך בדרך זו, כתוב ופרוס פונקציה הניתנת להתקשרות HTTP ב-Cloud Functions, ולאחר מכן הוסף לוגיקת לקוח כדי לקרוא לפונקציה מהאפליקציה שלך.

חשוב לזכור שפונקציות הניתנות להתקשרות HTTP דומות אך אינן זהות לפונקציות HTTP. כדי להשתמש בפונקציות הניתנות להתקשרות ב-HTTP, עליך להשתמש ב-SDK של הלקוח עבור הפלטפורמה שלך יחד עם ה-API העורפי (או ליישם את הפרוטוקול). לטלפונים הניתנים להתקשרות יש הבדלים מרכזיים אלה מפונקציות HTTP:

  • עם טלפונים ניתנים להתקשרות, אסימוני אימות Firebase, אסימוני FCM ואסימוני בדיקת אפליקציות, כאשר הם זמינים, נכללים אוטומטית בבקשות.
  • הטריגר מבטל באופן אוטומטי את גוף הבקשה ומאמת אסימוני אישור.

Firebase SDK for Cloud Functions דור שני ומעלה פועל בשילוב עם גרסאות המינימום האלה של Firebase Client SDK כדי לתמוך בפונקציות הניתנות להתקשרות ב-HTTPS:

  • Firebase SDK עבור פלטפורמות Apple 10.19.0
  • Firebase SDK עבור אנדרואיד 20.4.0
  • Firebase Modular Web SDK v. 9.7.0

אם ברצונך להוסיף פונקציונליות דומה לאפליקציה הבנויה על פלטפורמה שאינה נתמכת, עיין במפרט הפרוטוקול עבור https.onCall . שאר המדריך מספק הוראות כיצד לכתוב, לפרוס ולהתקשר לפונקציה הניתנת להתקשרות עם HTTP עבור פלטפורמות אפל, אנדרואיד, אינטרנט, C++ ו-Unity.

כתוב ופריסה את הפונקציה הניתנת להתקשרות

השתמש 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 כדי לסייע בהגנה על משאבי הקצה האחוריים שלך מפני שימוש לרעה, כגון הונאת חיוב או פישינג. ראה הפעלת אכיפה של בדיקת אפליקציות עבור פונקציות ענן .

שולח בחזרה את התוצאה

כדי לשלוח נתונים בחזרה ללקוח, החזר נתונים שניתן לקידוד JSON. לדוגמה, כדי להחזיר את התוצאה של פעולת הוספה:

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

כדי להחזיר נתונים לאחר פעולה אסינכרונית, החזר הבטחה. הנתונים המוחזרים בהבטחה נשלחים בחזרה ללקוח. לדוגמה, אתה יכול להחזיר טקסט מחוטא שהפונקציה הניתנת להתקשרות כתבה למסד הנתונים בזמן אמת:

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

לטפל בשגיאות

כדי להבטיח שהלקוח יקבל פרטי שגיאה שימושיים, החזר שגיאות מקובץ שניתן להתקשרות על ידי זריקת (או החזרת הבטחה שנדחתה עם) מופע של 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, כשפרויקט האפליקציה שלך פתוח, נווט אל קובץ > הוסף חבילות .
  2. כשתתבקש, הוסף את מאגר Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. בחר את ספריית Cloud Functions.
  5. הוסף את הדגל -ObjC לקטע Other Linker Flags של הגדרות הבנייה של היעד שלך.
  6. בסיום, Xcode יתחיל באופן אוטומטי לפתור ולהוריד את התלות שלך ברקע.

API מודולרי אינטרנט

  1. בצע את ההוראות להוספת Firebase לאפליקציית האינטרנט שלך . הקפד להריץ את הפקודה הבאה מהמסוף שלך:
    npm install firebase@10.7.1 --save
    
  2. דורשים ידנית גם פונקציות ליבת Firebase וגם ענן:

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

API עם מרחב שמות אינטרנט

  1. בצע את ההוראות להוספת Firebase לאפליקציית האינטרנט שלך .
  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 וגם ענן:
    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 ), הוסף את התלות עבור פונקציות הענן ספרייה עבור אנדרואיד. אנו ממליצים להשתמש ב- 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.

    (אלטרנטיבי) הוסף תלות בספריית Firebase מבלי להשתמש ב-BoM

    אם תבחר שלא להשתמש ב-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")
    }
    
    מחפש מודול ספרייה ספציפי לקוטלין? החל מאוקטובר 2023 (Firebase BoM 32.5.0) , מפתחי Kotlin ו-Java יכולים להיות תלויים במודול הספרייה הראשי (לפרטים, עיין בשאלות הנפוצות לגבי יוזמה זו ).

Java

  1. עקוב אחר ההוראות להוספת Firebase לאפליקציית Android שלך .

  2. בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל <project>/<app-module>/build.gradle.kts או <project>/<app-module>/build.gradle ), הוסף את התלות עבור פונקציות הענן ספרייה עבור אנדרואיד. אנו ממליצים להשתמש ב- 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.

    (אלטרנטיבי) הוסף תלות בספריית Firebase מבלי להשתמש ב-BoM

    אם תבחר שלא להשתמש ב-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")
    }
    
    מחפש מודול ספרייה ספציפי לקוטלין? החל מאוקטובר 2023 (Firebase BoM 32.5.0) , מפתחי Kotlin ו-Java יכולים להיות תלויים במודול הספרייה הראשי (לפרטים, עיין בשאלות הנפוצות לגבי יוזמה זו ).

Dart

  1. עקוב אחר ההוראות להוספת Firebase לאפליקציית Flutter שלך .

  2. מהשורש של פרויקט Flutter שלך, הפעל את הפקודה הבאה כדי להתקין את הפלאגין:

    flutter pub add cloud_functions
    
  3. לאחר השלמתו, בנה מחדש את אפליקציית Flutter שלך:

    flutter run
    
  4. לאחר ההתקנה, תוכל לגשת לפלאגין cloud_functions על ידי ייבואו בקוד Dart שלך:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

עבור C++ עם אנדרואיד :

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט C++ שלך .
  2. הוסף את ספריית firebase_functions לקובץ CMakeLists.txt שלך.

עבור C++ עם פלטפורמות אפל :

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט C++ שלך .
  2. הוסף את הפוד של Cloud Functions ל- Podfile שלך:
    pod 'Firebase/Functions'
  3. שמור את הקובץ, ואז הרץ:
    pod install
  4. הוסף את מסגרות הליבה ו-Cloud Functions של Firebase מ- Firebase C++ SDK לפרויקט Xcode שלך.
    • firebase.framework
    • firebase_functions.framework

אַחְדוּת

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט Unity שלך .
  2. הוסף את FirebaseFunctions.unitypackage מ- Firebase Unity SDK לפרויקט Unity שלך.

אתחל את ה-SDK של הלקוח

אתחול מופע של פונקציות ענן:

מָהִיר

lazy var functions = Functions.functions()

Objective-C

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

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"];
}];

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

טיפול בשגיאות בלקוח

הלקוח מקבל שגיאה אם ​​השרת זרק שגיאה או אם ההבטחה שהתקבלה נדחתה.

אם השגיאה המוחזרת על ידי הפונקציה היא מסוג function.https.HttpsError , הלקוח מקבל את code השגיאה, message 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]
  }
  // ...
}

Objective-C

if (error) {
  if ([error.domain isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

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

לפני שתפעיל את האפליקציה שלך, עליך להפעיל את App Check כדי להבטיח שרק האפליקציות שלך יכולות לגשת לנקודות הקצה הניתנות להתקשרות.

,


ערכות SDK של לקוח Cloud Functions for Firebase מאפשרות לך לקרוא לפונקציות ישירות מאפליקציית Firebase. כדי לקרוא לפונקציה מהאפליקציה שלך בדרך זו, כתוב ופרוס פונקציה הניתנת להתקשרות HTTP ב-Cloud Functions, ולאחר מכן הוסף לוגיקת לקוח כדי לקרוא לפונקציה מהאפליקציה שלך.

חשוב לזכור שפונקציות הניתנות להתקשרות HTTP דומות אך אינן זהות לפונקציות HTTP. כדי להשתמש בפונקציות הניתנות להתקשרות ב-HTTP, עליך להשתמש ב-SDK של הלקוח עבור הפלטפורמה שלך יחד עם ה-API העורפי (או ליישם את הפרוטוקול). לטלפונים הניתנים להתקשרות יש הבדלים מרכזיים אלה מפונקציות HTTP:

  • עם ניתנים להתקשרות, אסימוני אימות Firebase, אסימוני FCM ואסימוני בדיקת אפליקציות, כאשר הם זמינים, נכללים אוטומטית בבקשות.
  • הטריגר מבטל באופן אוטומטי את גוף הבקשה ומאמת אסימוני אישור.

Firebase SDK for Cloud Functions דור שני ומעלה פועל בשילוב עם גרסאות המינימום האלה של Firebase Client SDK כדי לתמוך בפונקציות הניתנות להתקשרות ב-HTTPS:

  • Firebase SDK עבור פלטפורמות Apple 10.19.0
  • Firebase SDK עבור אנדרואיד 20.4.0
  • Firebase Modular Web SDK v. 9.7.0

אם ברצונך להוסיף פונקציונליות דומה לאפליקציה הבנויה על פלטפורמה שאינה נתמכת, עיין במפרט הפרוטוקול עבור https.onCall . שאר המדריך מספק הוראות כיצד לכתוב, לפרוס ולהתקשר לפונקציה הניתנת להתקשרות עם HTTP עבור פלטפורמות אפל, אנדרואיד, אינטרנט, C++ ו-Unity.

כתוב ופריסה את הפונקציה הניתנת להתקשרות

השתמש 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 כדי לסייע בהגנה על משאבי הקצה האחוריים שלך מפני שימוש לרעה, כגון הונאת חיוב או פישינג. ראה הפעלת אכיפה של בדיקת אפליקציות עבור פונקציות ענן .

שולח בחזרה את התוצאה

כדי לשלוח נתונים בחזרה ללקוח, החזר נתונים שניתן לקידוד JSON. לדוגמה, כדי להחזיר את התוצאה של פעולת הוספה:

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

כדי להחזיר נתונים לאחר פעולה אסינכרונית, החזר הבטחה. הנתונים המוחזרים בהבטחה נשלחים בחזרה ללקוח. לדוגמה, אתה יכול להחזיר טקסט מחוטא שהפונקציה הניתנת להתקשרות כתבה למסד הנתונים בזמן אמת:

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

לטפל בשגיאות

כדי להבטיח שהלקוח יקבל פרטי שגיאה שימושיים, החזר שגיאות מקובץ שניתן להתקשרות על ידי זריקת (או החזרת הבטחה שנדחתה עם) מופע של 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, כשפרויקט האפליקציה שלך פתוח, נווט אל קובץ > הוסף חבילות .
  2. כשתתבקש, הוסף את מאגר Firebase Apple platforms SDK:
  3.   https://github.com/firebase/firebase-ios-sdk.git
  4. בחר את ספריית Cloud Functions.
  5. הוסף את הדגל -ObjC לקטע Other Linker Flags של הגדרות הבנייה של היעד שלך.
  6. בסיום, Xcode יתחיל באופן אוטומטי לפתור ולהוריד את התלות שלך ברקע.

API מודולרי אינטרנט

  1. בצע את ההוראות להוספת Firebase לאפליקציית האינטרנט שלך . הקפד להריץ את הפקודה הבאה מהמסוף שלך:
    npm install firebase@10.7.1 --save
    
  2. דורשים ידנית גם פונקציות ליבת Firebase וגם ענן:

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

API עם מרחב שמות אינטרנט

  1. בצע את ההוראות להוספת Firebase לאפליקציית האינטרנט שלך .
  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 וגם ענן:
    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 ), הוסף את התלות עבור פונקציות הענן ספרייה עבור אנדרואיד. אנו ממליצים להשתמש ב- 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.

    (אלטרנטיבי) הוסף תלות בספריית Firebase מבלי להשתמש ב-BoM

    אם תבחר שלא להשתמש ב-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")
    }
    
    מחפש מודול ספרייה ספציפי לקוטלין? החל מאוקטובר 2023 (Firebase BoM 32.5.0) , מפתחי Kotlin ו-Java יכולים להיות תלויים במודול הספרייה הראשי (לפרטים, עיין בשאלות הנפוצות לגבי יוזמה זו ).

Java

  1. עקוב אחר ההוראות להוספת Firebase לאפליקציית Android שלך .

  2. בקובץ Gradle של המודול (ברמת האפליקציה) (בדרך כלל <project>/<app-module>/build.gradle.kts או <project>/<app-module>/build.gradle ), הוסף את התלות עבור פונקציות הענן ספרייה עבור אנדרואיד. אנו ממליצים להשתמש ב- 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.

    (אלטרנטיבי) הוסף תלות בספריית Firebase מבלי להשתמש ב-BoM

    אם תבחר שלא להשתמש ב-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")
    }
    
    מחפש מודול ספרייה ספציפי לקוטלין? החל מאוקטובר 2023 (Firebase BoM 32.5.0) , מפתחי Kotlin ו-Java יכולים להיות תלויים במודול הספרייה הראשי (לפרטים, עיין בשאלות הנפוצות לגבי יוזמה זו ).

Dart

  1. עקוב אחר ההוראות להוספת Firebase לאפליקציית Flutter שלך .

  2. מהשורש של פרויקט Flutter שלך, הפעל את הפקודה הבאה כדי להתקין את הפלאגין:

    flutter pub add cloud_functions
    
  3. לאחר השלמתו, בנה מחדש את אפליקציית Flutter שלך:

    flutter run
    
  4. לאחר ההתקנה, תוכל לגשת לפלאגין cloud_functions על ידי ייבואו בקוד Dart שלך:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

עבור C++ עם אנדרואיד :

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט C++ שלך .
  2. הוסף את ספריית firebase_functions לקובץ CMakeLists.txt שלך.

עבור C++ עם פלטפורמות אפל :

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט C++ שלך .
  2. הוסף את הפוד של Cloud Functions ל- Podfile שלך:
    pod 'Firebase/Functions'
  3. שמור את הקובץ, ואז הרץ:
    pod install
  4. הוסף את מסגרות הליבה ו-Cloud Functions של Firebase מ- Firebase C++ SDK לפרויקט Xcode שלך.
    • firebase.framework
    • firebase_functions.framework

אַחְדוּת

  1. עקוב אחר ההוראות להוספת Firebase לפרויקט Unity שלך .
  2. הוסף את FirebaseFunctions.unitypackage מ- Firebase Unity SDK לפרויקט Unity שלך.

אתחל את ה-SDK של הלקוח

אתחול מופע של פונקציות ענן:

מָהִיר

lazy var functions = Functions.functions()

Objective-C

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

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"];
}];

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

טיפול בשגיאות בלקוח

הלקוח מקבל שגיאה אם ​​השרת זרק שגיאה או אם ההבטחה שהתקבלה נדחתה.

אם השגיאה המוחזרת על ידי הפונקציה היא מסוג function.https.HttpsError , הלקוח מקבל את code השגיאה, message 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]
  }
  // ...
}

Objective-C

if (error) {
  if ([error.domain isEqual:@"com.firebase.functions"]) {
    FIRFunctionsErrorCode code = error.code;
    NSString *message = error.localizedDescription;
    NSObject *details = error.userInfo[@"details"];
  }
  // ...
}

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

לפני שתפעיל את האפליקציה שלך, עליך לאפשר בדיקת אפליקציות כדי לעזור להבטיח שרק האפליקציות שלך יכולות לגשת לנקודות הקצה שלך לפונקציה הניתנת להתקשרות.