Os SDKs de clientes do Cloud Functions para Firebase permitem que você chame funções diretamente de um aplicativo do Firebase. Para chamar uma função do seu aplicativo dessa maneira, escreva e implante uma função HTTPS Callable no Cloud Functions e, em seguida, adicione a lógica do cliente para chamar a função do seu aplicativo.
É importante ter em mente que as funções callable HTTPS são semelhantes, mas não idênticas às funções HTTP. Para usar as funções que podem ser chamadas HTTPS, você deve usar o SDK do cliente para sua plataforma junto com a API de back-end functions.https
(ou implementar o protocolo). Callables têm essas diferenças importantes em relação às funções HTTP:
- Com callables, tokens Firebase Authentication, tokens FCM e tokens App Check, quando disponíveis, são incluídos automaticamente nas solicitações.
- O gatilho
functions.https.onCall
desserializa automaticamente o corpo da solicitação e valida os tokens de autenticação.
O SDK do Firebase para Cloud Functions v0.9.1 e superior interopera com estas versões mínimas do SDK do cliente Firebase para oferecer suporte a funções HTTPS Callable:
- Firebase SDK para plataformas Apple 10.4.0
- SDK do Firebase para Android 20.2.2
- Firebase JavaScript SDK 8.10.1
- Firebase Modular Web SDK v. 9.0
Se você deseja adicionar funcionalidade semelhante a um aplicativo criado em uma plataforma sem suporte, consulte a Especificação de protocolo para https.onCall
. O restante deste guia fornece instruções sobre como escrever, implantar e chamar uma função chamável HTTPS para plataformas Apple, Android, Web, C++ e Unity.
Escrever e implantar a função chamável
Use functions.https.onCall
para criar uma função HTTPS que pode ser chamada. Este método recebe dois parâmetros: data
e context
opcional:
// Saves a message to the Firebase Realtime Database but sanitizes the text by removing swearwords.
exports.addMessage = functions.https.onCall((data, context) => {
// ...
});
Para uma função chamável que salva uma mensagem de texto no Realtime Database, por exemplo, data
podem conter o texto da mensagem, enquanto os parâmetros de context
representam as informações de autenticação do usuário:
// 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;
A distância entre o local da função chamável e o local do cliente chamador pode criar latência de rede. Para otimizar o desempenho, considere especificar o local da função onde aplicável e certifique-se de alinhar o local do callable com o local definido ao inicializar o SDK no lado do cliente.
Opcionalmente, você pode anexar um atestado do App Check para ajudar a proteger seus recursos de back-end contra abusos, como fraude de cobrança ou phishing. Consulte Ativar a aplicação do App Check para Cloud Functions .
Enviando de volta o resultado
Para enviar dados de volta ao cliente, retorne dados que possam ser codificados em JSON. Por exemplo, para retornar o resultado de uma operação de adição:
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: '+',
operationResult: firstNumber + secondNumber,
};
Para retornar dados após uma operação assíncrona, retorne uma promessa. Os dados retornados pela promessa são enviados de volta ao cliente. Por exemplo, você pode retornar um texto limpo que a função chamável gravou no Realtime Database:
// 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 };
})
Lidar com erros
Para garantir que o cliente obtenha detalhes de erro úteis, retorne os erros de um callable lançando (ou retornando uma promessa rejeitada com) uma instância de functions.https.HttpsError
. O erro tem um atributo de code
que pode ser um dos valores listados em functions.https.HttpsError
. Os erros também têm uma message
de string, cujo padrão é uma string vazia. Eles também podem ter um campo de details
opcional com um valor arbitrário. Se um erro diferente de HttpsError
for lançado de suas funções, seu cliente receberá um erro com a mensagem INTERNAL
e o código internal
.
Por exemplo, uma função pode lançar erros de autenticação e validação de dados com mensagens de erro para retornar ao cliente chamador:
// 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.');
}
Implantar a função chamável
Depois de salvar uma função chamável concluída em index.js
, ela é implantada junto com todas as outras funções quando você executa o firebase deploy
. Para implantar apenas o callable, use o argumento --only
conforme mostrado para executar implantações parciais :
firebase deploy --only functions:addMessage
Se você encontrar erros de permissão ao implantar funções, certifique-se de que as funções apropriadas do IAM sejam atribuídas ao usuário que executa os comandos de implantação.
Configure seu ambiente de desenvolvimento de cliente
Certifique-se de atender a todos os pré-requisitos e, em seguida, adicione as dependências e bibliotecas de cliente necessárias ao seu aplicativo.
iOS+
Siga as instruções para adicionar o Firebase ao seu aplicativo Apple .
Use o Swift Package Manager para instalar e gerenciar dependências do Firebase.
- No Xcode, com seu projeto de aplicativo aberto, navegue até File > Add Packages .
- Quando solicitado, adicione o repositório Firebase Apple Platform SDK:
- Escolha a biblioteca Cloud Functions.
- Quando terminar, o Xcode começará automaticamente a resolver e baixar suas dependências em segundo plano.
https://github.com/firebase/firebase-ios-sdk
Web version 9
- Siga as instruções para adicionar o Firebase ao seu aplicativo da Web . Certifique-se de executar o seguinte comando no seu terminal:
npm install firebase@9.17.1 --save
Exija manualmente o núcleo do Firebase e o 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 version 8
- Siga as instruções para adicionar o Firebase ao seu aplicativo da Web .
- Adicione o núcleo do Firebase e as bibliotecas de cliente do Cloud Functions ao seu aplicativo:
<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>
O Cloud Functions SDK também está disponível como um pacote npm.
- Execute o seguinte comando no seu terminal:
npm install firebase@8.10.1 --save
- Exigir manualmente o núcleo do Firebase e o Cloud Functions:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin+KTX
Siga as instruções para adicionar o Firebase ao seu aplicativo Android .
No arquivo Gradle do módulo (nível do aplicativo) (geralmente
<project>/<app-module>/build.gradle
), adicione a dependência para a biblioteca Android do Cloud Functions. Recomendamos usar o Firebase Android BoM para controlar o controle de versão da biblioteca.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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' }
Ao usar o Firebase Android BoM , seu aplicativo sempre usará versões compatíveis das bibliotecas do Firebase Android.
(Alternativa) Adicionar dependências da biblioteca Firebase sem usar o BoM
Se você optar por não usar o Firebase BoM, deverá especificar cada versão da biblioteca Firebase em sua linha de dependência.
Observe que, se você usar várias bibliotecas do Firebase em seu aplicativo, recomendamos usar o BoM para gerenciar as versões da biblioteca, o que garante que todas as versões sejam compatíveis.
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.2.2' }
Java
Siga as instruções para adicionar o Firebase ao seu aplicativo Android .
No arquivo Gradle do módulo (nível do aplicativo) (geralmente
<project>/<app-module>/build.gradle
), adicione a dependência para a biblioteca Android do Cloud Functions. Recomendamos usar o Firebase Android BoM para controlar o controle de versão da biblioteca.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:31.2.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' }
Ao usar o Firebase Android BoM , seu aplicativo sempre usará versões compatíveis das bibliotecas do Firebase Android.
(Alternativa) Adicionar dependências da biblioteca Firebase sem usar o BoM
Se você optar por não usar o Firebase BoM, deverá especificar cada versão da biblioteca Firebase em sua linha de dependência.
Observe que, se você usar várias bibliotecas do Firebase em seu aplicativo, recomendamos usar o BoM para gerenciar as versões da biblioteca, o que garante que todas as versões sejam compatíveis.
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.2.2' }
Dart
Siga as instruções para adicionar o Firebase ao seu aplicativo Flutter .
Na raiz do seu projeto Flutter, execute o seguinte comando para instalar o plug-in:
flutter pub add cloud_functions
Depois de concluído, reconstrua seu aplicativo Flutter:
flutter run
Uma vez instalado, você pode acessar o plug-in
cloud_functions
importando-o em seu código Dart:import 'package:cloud_functions/cloud_functions.dart';
C++
Para C++ com Android :
- Siga as instruções para adicionar o Firebase ao seu projeto C++ .
- Adicione a biblioteca
firebase_functions
ao seu arquivoCMakeLists.txt
.
Para C++ com plataformas Apple :
- Siga as instruções para adicionar o Firebase ao seu projeto C++ .
- Adicione o pod do Cloud Functions ao seu
Podfile
:pod 'Firebase/Functions'
- Salve o arquivo e execute:
pod install
- Adicione o núcleo do Firebase e as estruturas do Cloud Functions do Firebase C++ SDK ao seu projeto Xcode.
-
firebase.framework
-
firebase_functions.framework
-
Unidade
- Siga as instruções para adicionar o Firebase ao seu projeto Unity .
- Adicione o
FirebaseFunctions.unitypackage
do Firebase Unity SDK ao seu projeto do Unity.
Inicializar o SDK do cliente
Inicialize uma instância do Cloud Functions:
Rápido
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
Web version 8
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 version 9
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);
Unidade
functions = Firebase.Functions.DefaultInstance;
Chame a função
Rápido
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 version 8
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
Web version 9
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();
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);
}
Unidade
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;
});
}
Tratar erros no cliente
O cliente recebe um erro se o servidor emitir um erro ou se a promessa resultante for rejeitada.
Se o erro retornado pela função for do tipo function.https.HttpsError
, o cliente receberá o code
de erro , a message
e os details
do erro do servidor. Caso contrário, o erro conterá a mensagem INTERNAL
e o código INTERNAL
. Consulte as orientações para saber como lidar com erros em sua função chamável.
Rápido
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 version 8
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 version 9
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);
// ...
Unidade
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;
}
});
Recomendado: evite abusos com o App Check
Antes de iniciar seu aplicativo, você deve habilitar o App Check para ajudar a garantir que apenas seus aplicativos possam acessar seus endpoints de função chamável.