Chamar funções no seu aplicativo


Com os SDKs do cliente do Cloud Functions para Firebase, é possível chamar funções diretamente de um app do Firebase. Para isso, crie e implante uma função HTTP chamável no Cloud Functions e adicione a lógica do cliente para chamar a função no seu app.

É importante ter em mente que as funções chamáveis HTTP são semelhantes, mas não são idênticas às funções HTTP. Para usar as funções HTTP chamáveis, use o SDK do cliente da sua plataforma com a API de back-end ou implemente o protocolo. Confira a seguir a diferença entre as funções chamáveis e as HTTP:

  • Com as funções chamáveis, os tokens do Firebase Authentication, do FCM e do App Check serão incluídos automaticamente nas solicitações quando estiverem disponíveis.
  • O gatilho desserializa automaticamente o corpo da solicitação e valida os tokens de autenticação.

O SDK do Firebase para Cloud Functions (2ª geração) e versões posteriores interopera com as versões mínimas do SDK de cliente do Firebase para oferecer suporte a funções HTTPS chamáveis:

  • SDK do Firebase para as plataformas da Apple 10.15.0
  • SDK do Firebase para Android 20.3.1
  • SDK modular do Firebase para Web 9.7.0

Se você quiser adicionar um recurso semelhante a um app criado em uma plataforma sem suporte, consulte a Especificação de protocolo para https.onCall. Você vai encontrar instruções na outra parte deste guia sobre como criar, implantar e chamar uma função HTTP chamável em plataformas da Apple, Android, Web, C++ e Unity.

Escrever e implantar a função chamável

Use functions.https.onCall para criar uma função HTTPS chamável. Esse método usa 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 pode conter o texto da mensagem, enquanto os parâmetros context representam a informação 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 do cliente que faz o chamado pode criar uma latência de rede significativa. Para otimizar o desempenho, especifique o local da função, quando aplicável, e alinhe o local da função chamável com o local definido ao inicializar o SDK no lado do cliente.

Como alternativa, é possível anexar um atestado do App Check para ajudar a proteger seus recursos de back-end contra abusos, como fraude de faturamento ou phishing. Consulte Ativar a aplicação do App Check no Cloud Functions.

Como enviar o resultado de volta

Para enviar dados de volta para o cliente, retorne dados que podem ser codificados com 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 o texto limpo que a função chamável escreveu 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 };
})

Tratar erros

Para garantir que o cliente receba detalhes úteis de erros, retorne erros de uma função chamável ao emitir (ou retornar uma promessa rejeitada com) uma instância de functions.https.HttpsError. O erro tem um atributo code que pode ser um dos valores listados em functions.https.HttpsError. Os erros também têm uma string message, que tem como padrão uma string vazia. Eles também podem ter um campo details opcional com um valor arbitrário. Se um erro diferente de HttpsError for emitido pelas suas funções, seu cliente receberá um erro com a mensagem INTERNAL e o código internal.

Por exemplo, uma função pode emitir erros de validação de dados e autenticação com mensagens de erro para retornar ao cliente que faz o chamado:

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

Como implantar a função chamável

Depois que você salva uma função chamável completa dentro do index.js, ela é implantada com todas as outras funções quando você executa firebase deploy. Para implementar somente a função chamável, use o argumento --only conforme mostrado a fim de executar implantações parciais:

firebase deploy --only functions:addMessage

Se você encontrar erros de permissão ao implantar funções, verifique se os papéis do IAM apropriados estão atribuídos ao usuário que executa os comandos de implantação.

Como configurar o ambiente de desenvolvimento do cliente

Verifique se você cumpre todos os pré-requisitos e adicione as dependências e bibliotecas de cliente necessárias ao app.

iOS+

Siga as instruções para adicionar o Firebase ao seu app da Apple.

Use o Swift Package Manager para instalar e gerenciar as dependências do Firebase.

  1. No Xcode, com seu projeto do app aberto, navegue até File > Add Packages.
  2. Quando solicitado, adicione o repositório do SDK do Firebase para as plataformas Apple:
  3.   https://github.com/firebase/firebase-ios-sdk
  4. Escolha a biblioteca do Cloud Functions.
  5. Quando terminar, o Xcode vai começar a resolver e fazer o download das dependências em segundo plano automaticamente.

API modular da Web

  1. Siga as instruções para adicionar o Firebase ao seu app da Web. Execute o seguinte comando no seu terminal:
    npm install firebase@10.4.0 --save
    
  2. Solicite manualmente o Firebase Core 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);
    

API com namespace da Web

  1. Siga as instruções para adicionar o Firebase ao seu app da Web.
  2. Adicione as bibliotecas de cliente do Firebase Core e do Cloud Functions ao seu 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>
    

O SDK do Cloud Functions também está disponível como um pacote npm.

  1. Execute o seguinte comando no seu terminal:
    npm install firebase@8.10.1 --save
    
  2. Solicite manualmente o Firebase Core e o Cloud Functions:
    const firebase = require("firebase");
    // Required for side-effects
    require("firebase/functions");
    

Kotlin+KTX

  1. Siga as instruções para adicionar o Firebase ao seu app Android.

  2. No arquivo do Gradle (nível do app) do módulo, (geralmente <project>/<app-module>/build.gradle.kts ou <project>/<app-module>/build.gradle), adicione a dependência da biblioteca do Cloud Functions para Android. Para gerenciar o controle de versões das bibliotecas, recomendamos usar a BoM do Firebase para Android.

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

    Com a BoM do Firebase para Android, seu app sempre vai usar versões compatíveis das bibliotecas do Firebase para Android.

    (Alternativa) Adicionar dependências das bibliotecas do Firebase sem usar a BoM

    Se você preferir não usar a BoM do Firebase, especifique cada versão das bibliotecas do Firebase na linha de dependência correspondente.

    Se você usa várias bibliotecas do Firebase no seu app, recomendamos utilizar a BoM para gerenciar as versões delas, porque isso ajuda a garantir a compatibilidade de todas as bibliotecas.

    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

  1. Siga as instruções para adicionar o Firebase ao seu app Android.

  2. No arquivo do Gradle (nível do app) do módulo, (geralmente <project>/<app-module>/build.gradle.kts ou <project>/<app-module>/build.gradle), adicione a dependência da biblioteca do Cloud Functions para Android. Para gerenciar o controle de versões das bibliotecas, recomendamos usar a BoM do Firebase para Android.

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

    Com a BoM do Firebase para Android, seu app sempre vai usar versões compatíveis das bibliotecas do Firebase para Android.

    (Alternativa) Adicionar dependências das bibliotecas do Firebase sem usar a BoM

    Se você preferir não usar a BoM do Firebase, especifique cada versão das bibliotecas do Firebase na linha de dependência correspondente.

    Se você usa várias bibliotecas do Firebase no seu app, recomendamos utilizar a BoM para gerenciar as versões delas, porque isso ajuda a garantir a compatibilidade de todas as bibliotecas.

    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

  1. Siga as instruções para adicionar o Firebase ao seu app criado com o Flutter.

  2. Na raiz do seu projeto do Flutter, execute o seguinte comando para instalar o plug-in:

    flutter pub add cloud_functions
    
  3. Após a conclusão, recrie seu aplicativo criado com o Flutter:

    flutter run
    
  4. Depois de instalado, você poderá acessar o plug-in cloud_functions, importando-o no código Dart:

    import 'package:cloud_functions/cloud_functions.dart';
    

C++

Para C ++ com Android:

  1. Siga as instruções para adicionar o Firebase ao seu projeto em C++.
  2. Adicione a biblioteca firebase_functions ao arquivo CMakeLists.txt.

Para C++ com plataformas da Apple:

  1. Siga as instruções para adicionar o Firebase ao seu projeto em C++.
  2. Adicione o pod do Cloud Functions ao seu Podfile:
    pod 'Firebase/Functions'
  3. Salve o arquivo e execute:
    pod install
  4. Adicione os frameworks do Cloud Functions e do Firebase Core do SDK do Firebase para C++ ao seu projeto do Xcode.
    • firebase.framework
    • firebase_functions.framework

Unity

  1. Siga as instruções para adicionar o Firebase ao seu projeto do Unity.
  2. Adicione o FirebaseFunctions.unitypackage do SDK do Firebase para Unity ao seu projeto do Unity.

Como inicializar o SDK do cliente

Inicialize uma instância do Cloud Functions:

Swift

lazy var functions = Functions.functions()

Objective-C

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

API com namespace da 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 modular da 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);

Unity

functions = Firebase.Functions.DefaultInstance;

Chamar a função

Swift

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 com namespace da Web

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

API modular da 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);
}

Unity

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

Como solucionar erros no cliente

O cliente vai receber um erro se o servidor tiver emitido um erro ou se a promessa resultante tiver sido recusada.

Se o erro retornado pela função for do tipo function.https.HttpsError, o cliente vai receber code, message e details do erro do servidor. Caso contrário, o erro vai conter a mensagem INTERNAL e o código INTERNAL. Consulte as orientações sobre como tratar erros na sua função chamável.

Swift

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 com namespace da 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 modular da 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);
  // ...

Unity

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

Antes de iniciar o app, ative o App Check para ajudar a garantir que somente seus apps possam acessar os endpoints da função chamável.