Gli SDK client Cloud Functions for Firebase ti consentono di chiamare le funzioni direttamente da un'app Firebase. Per chiamare una funzione dalla tua app in questo modo, scrivi ed esegui il deployment di una funzione HTTP Callable in Cloud Functions, quindi aggiungi la logica client per chiamare la funzione dalla tua app.
È importante tenere presente che le funzioni richiamabili HTTP sono simili ma non identiche alle funzioni HTTP. Per utilizzare le funzioni richiamabili HTTP è necessario utilizzare l'SDK del client per la propria piattaforma insieme all'API di back-end (o implementare il protocollo). I callable hanno queste differenze fondamentali rispetto alle funzioni HTTP:
I callable presentano queste differenze fondamentali rispetto alle funzioni HTTP:
- Con i callable, i token di autenticazione Firebase, i token FCM e i token App Check, se disponibili, vengono inclusi automaticamente nelle richieste.
- Il trigger deserializza automaticamente il corpo della richiesta e convalida i token di autenticazione.
L'SDK Firebase per Cloud Functions di seconda generazione e versioni successive interagisce con queste versioni minime dell'SDK client Firebase per supportare le funzioni HTTPS Callable:
- SDK Firebase per piattaforme Apple 10.10.0
- SDK Firebase per Android 20.3.1
- Firebase Modular Web SDK versione 9.7.0
Se desideri aggiungere funzionalità simili a un'app creata su una piattaforma non supportata, consulta la specifica del protocollo per https.onCall
. Il resto di questa guida fornisce istruzioni su come scrivere, distribuire e chiamare una funzione chiamabile HTTP per piattaforme Apple, Android, Web, C++ e Unity.
Scrivere e distribuire la funzione richiamabile
Utilizzare functions.https.onCall
per creare una funzione richiamabile HTTPS. Questo metodo accetta due parametri: data
e context
facoltativo:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
Per una funzione richiamabile che salva un messaggio di testo nel database in tempo reale, ad esempio, data
potrebbero contenere il testo del messaggio, mentre i parametri context
rappresentano le informazioni sull'autenticazione dell'utente:
// 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;
La distanza tra la posizione della funzione richiamabile e la posizione del client chiamante può creare latenza di rete. Per ottimizzare le prestazioni, valuta la possibilità di specificare la posizione della funzione, ove applicabile, e assicurati di allineare la posizione del callable con la posizione impostata quando inizializzi l'SDK sul lato client.
Facoltativamente, puoi allegare un'attestazione App Check per proteggere le tue risorse di back-end da abusi, come ad esempio frodi di fatturazione o phishing. Consulta Abilitare l'applicazione di App Check per Cloud Functions .
Restituzione del risultato
Per inviare i dati al client, restituire i dati che possono essere codificati in JSON. Ad esempio, per restituire il risultato di un'operazione di addizione:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
Per restituire i dati dopo un'operazione asincrona, restituire una promessa. I dati restituiti dalla promessa vengono inviati al client. Ad esempio, potresti restituire il testo sanificato che la funzione richiamabile ha scritto nel database in tempo reale:
// 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 };
})
Gestire gli errori
Per garantire che il client ottenga dettagli utili sull'errore, restituire gli errori da un callable lanciando (o restituendo una promessa rifiutata con) un'istanza di functions.https.HttpsError
. L'errore ha un attributo code
che può essere uno dei valori elencati in functions.https.HttpsError
. Gli errori hanno anche una stringa message
, che per impostazione predefinita è una stringa vuota. Possono anche avere un campo details
facoltativo con un valore arbitrario. Se un errore diverso da HttpsError
viene generato dalle tue funzioni, il tuo client riceve invece un errore con il messaggio INTERNAL
e il codice internal
.
Ad esempio, una funzione potrebbe generare errori di convalida e autenticazione dei dati con messaggi di errore da restituire al client chiamante:
// 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.');
}
Distribuire la funzione richiamabile
Dopo aver salvato una funzione richiamabile completata all'interno di index.js
, viene distribuita insieme a tutte le altre funzioni quando esegui firebase deploy
. Per distribuire solo il chiamabile, utilizzare l'argomento --only
come mostrato per eseguire distribuzioni parziali :
firebase deploy --only functions:addMessage
Se riscontri errori di autorizzazione durante la distribuzione delle funzioni, assicurati che i ruoli IAM appropriati siano assegnati all'utente che esegue i comandi di distribuzione.
Imposta il tuo ambiente di sviluppo client
Assicurati di soddisfare tutti i prerequisiti, quindi aggiungi le dipendenze e le librerie client richieste alla tua app.
iOS+
Segui le istruzioni per aggiungere Firebase alla tua app Apple .
Utilizza Swift Package Manager per installare e gestire le dipendenze di Firebase.
- In Xcode, con il progetto dell'app aperto, vai a File > Add Packages .
- Quando richiesto, aggiungi il repository SDK delle piattaforme Firebase Apple:
- Scegli la libreria Cloud Functions.
- Al termine, Xcode inizierà automaticamente a risolvere e scaricare le tue dipendenze in background.
https://github.com/firebase/firebase-ios-sdk
API modulare Web
- Segui le istruzioni per aggiungere Firebase alla tua app Web . Assicurati di eseguire il seguente comando dal tuo terminale:
npm install firebase@9.22.1 --save
Richiedi manualmente sia Firebase core che 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);
API con spazio dei nomi Web
- Segui le istruzioni per aggiungere Firebase alla tua app Web .
- Aggiungi le librerie client Firebase Core e Cloud Functions alla tua app:
<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>
L'SDK di Cloud Functions è disponibile anche come pacchetto npm.
- Esegui il seguente comando dal tuo terminale:
npm install firebase@8.10.1 --save
- Richiedi manualmente sia Firebase core che Cloud Functions:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin+KTX
Segui le istruzioni per aggiungere Firebase alla tua app Android .
Nel file Gradle del modulo (a livello di app) (in genere
<project>/<app-module>/build.gradle
), aggiungi la dipendenza per la libreria Android di Cloud Functions. Ti consigliamo di utilizzare la distinta base Android di Firebase per controllare il controllo delle versioni della libreria.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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-ktx' }
Utilizzando Firebase Android BoM , la tua app utilizzerà sempre versioni compatibili delle librerie Firebase Android.
(Alternativa) Aggiungi le dipendenze della libreria Firebase senza utilizzare la distinta base
Se scegli di non utilizzare Firebase BoM, devi specificare ogni versione della libreria Firebase nella relativa riga di dipendenza.
Tieni presente che se utilizzi più librerie Firebase nella tua app, ti consigliamo vivamente di utilizzare la distinta base per gestire le versioni della libreria, che garantisce che tutte le versioni siano compatibili.
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-ktx:20.3.1' }
Java
Segui le istruzioni per aggiungere Firebase alla tua app Android .
Nel file Gradle del modulo (a livello di app) (in genere
<project>/<app-module>/build.gradle
), aggiungi la dipendenza per la libreria Android di Cloud Functions. Ti consigliamo di utilizzare la distinta base Android di Firebase per controllare il controllo delle versioni della libreria.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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' }
Utilizzando Firebase Android BoM , la tua app utilizzerà sempre versioni compatibili delle librerie Firebase Android.
(Alternativa) Aggiungi le dipendenze della libreria Firebase senza utilizzare la distinta base
Se scegli di non utilizzare Firebase BoM, devi specificare ogni versione della libreria Firebase nella relativa riga di dipendenza.
Tieni presente che se utilizzi più librerie Firebase nella tua app, ti consigliamo vivamente di utilizzare la distinta base per gestire le versioni della libreria, che garantisce che tutte le versioni siano compatibili.
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.3.1' }
Dart
Segui le istruzioni per aggiungere Firebase alla tua app Flutter .
Dalla radice del tuo progetto Flutter, esegui il seguente comando per installare il plugin:
flutter pub add cloud_functions
Una volta completato, ricostruisci la tua applicazione Flutter:
flutter run
Una volta installato, puoi accedere al plug-in
cloud_functions
importandolo nel tuo codice Dart:import 'package:cloud_functions/cloud_functions.dart';
C++
Per C++ con Android :
- Segui le istruzioni per aggiungere Firebase al tuo progetto C++ .
- Aggiungi la libreria
firebase_functions
al tuo fileCMakeLists.txt
.
Per C++ con piattaforme Apple :
- Segui le istruzioni per aggiungere Firebase al tuo progetto C++ .
- Aggiungi il pod Cloud Functions al tuo
Podfile
:pod 'Firebase/Functions'
- Salva il file, quindi esegui:
pod install
- Aggiungi i framework Firebase core e Cloud Functions dall'SDK Firebase C++ al tuo progetto Xcode.
-
firebase.framework
-
firebase_functions.framework
-
Unità
- Segui le istruzioni per aggiungere Firebase al tuo progetto Unity .
- Aggiungi il
FirebaseFunctions.unitypackage
da Firebase Unity SDK al tuo progetto Unity.
Inizializza l'SDK del client
Inizializza un'istanza di Cloud Functions:
Rapido
lazy var functions = Functions.functions()
Obiettivo-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
API con spazio dei nomi Web
firebase.initializeApp({
apiKey: '### FIREBASE API KEY ###',
authDomain: '### FIREBASE AUTH DOMAIN ###',
projectId: '### CLOUD FUNCTIONS PROJECT ID ###'
databaseURL: 'https://### YOUR DATABASE NAME ###.firebaseio.com',
});
// Initialize Cloud Functions through Firebase
var functions = firebase.functions();
API modulare Web
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);
Unità
functions = Firebase.Functions.DefaultInstance;
Chiama la funzione
Rapido
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
}
}
Obiettivo-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 con spazio dei nomi Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
API modulare 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+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);
}
Unità
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;
});
}
Gestire gli errori sul client
Il client riceve un errore se il server ha generato un errore o se la promessa risultante è stata respinta.
Se l'errore restituito dalla funzione è di tipo function.https.HttpsError
, il client riceve il code
errore , message
e details
dall'errore del server. In caso contrario, l'errore contiene il messaggio INTERNAL
e il codice INTERNAL
. Consulta la guida su come gestire gli errori nella tua funzione richiamabile.
Rapido
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]
}
// ...
}
Obiettivo-C
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
API con spazio dei nomi 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;
// ...
});
API modulare 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+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);
// ...
Unità
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;
}
});
Consigliato: prevenire gli abusi con App Check
Prima di avviare l'app, devi abilitare App Check per assicurarti che solo le tue app possano accedere agli endpoint delle funzioni richiamabili.