SDK ứng dụng Chức năng đám mây cho Firebase cho phép bạn gọi các hàm trực tiếp từ một ứng dụng Firebase. Để gọi một hàm từ ứng dụng của bạn theo cách này, hãy viết và triển khai hàm có thể gọi HTTP trong Cloud Functions và sau đó thêm logic ứng dụng khách để gọi hàm từ ứng dụng của bạn.
Điều quan trọng cần ghi nhớ là các hàm có thể gọi HTTP tương tự nhau nhưng không giống với các hàm HTTP. Để sử dụng các hàm có thể gọi HTTP, bạn phải sử dụng SDK ứng dụng khách cho nền tảng của bạn cùng với phụ trợ API (hoặc triển khai giao thức). Các lệnh gọi được có các khoá này sự khác biệt so với các hàm HTTP:
- Với các lệnh gọi được, mã thông báo Xác thực Firebase, mã thông báo FCM và mã thông báo Kiểm tra ứng dụng (nếu có) sẽ tự động được đưa vào yêu cầu.
- Điều kiện kích hoạt này sẽ tự động giải tuần tự nội dung yêu cầu và xác thực mã thông báo xác thực.
Firebase SDK for Cloud Functions thế hệ thứ 2 trở lên tương tác với các ứng dụng Firebase này Phiên bản tối thiểu của SDK để hỗ trợ các hàm có thể gọi qua HTTPS:
- Firebase SDK cho các nền tảng của Apple 10.29.0
- Firebase SDK dành cho Android 21.0.0
- SDK web mô-đun Firebase phiên bản 9.7.0
Nếu bạn muốn thêm chức năng tương tự vào ứng dụng được tạo trên
nền tảng, hãy xem Thông số kỹ thuật giao thức cho https.onCall
. Phần còn lại của hướng dẫn này cung cấp
hướng dẫn về cách viết, triển khai và gọi điện
một hàm có thể gọi HTTP cho các nền tảng của Apple, Android, web, C++ và Unity.
Viết và triển khai hàm có thể gọi
Các mã ví dụ trong phần này được dựa trên mẫu bắt đầu nhanh minh hoạ cách gửi yêu cầu đến một hàm phía máy chủ và nhận một bằng một trong các SDK ứng dụng khách. Để bắt đầu, hãy nhập mô-đun:
Node.js
// Dependencies for callable functions.
const {onCall, HttpsError} = require("firebase-functions/v2/https");
const {logger} = require("firebase-functions/v2");
// Dependencies for the addMessage function.
const {getDatabase} = require("firebase-admin/database");
const sanitizer = require("./sanitizer");
Python
# Dependencies for callable functions.
from firebase_functions import https_fn, options
# Dependencies for writing to Realtime Database.
from firebase_admin import db, initialize_app
Sử dụng trình xử lý yêu cầu cho nền tảng của bạn (functions.https.onCall
)
hoặc on_call
)
để tạo một hàm có thể gọi HTTPS. Phương thức này
lấy một tham số yêu cầu:
Node.js
// Saves a message to the Firebase Realtime Database but sanitizes the
// text by removing swearwords.
exports.addmessage = onCall((request) => {
// ...
});
Python
@https_fn.on_call()
def addmessage(req: https_fn.CallableRequest) -> Any:
"""Saves a message to the Firebase Realtime Database but sanitizes the text
by removing swear words."""
Tham số request
chứa dữ liệu được truyền từ ứng dụng khách cũng như ngữ cảnh bổ sung như trạng thái xác thực. Đối với hàm có thể gọi giúp lưu tin nhắn văn bản vào Cơ sở dữ liệu theo thời gian thực,
ví dụ: data
có thể chứa văn bản tin nhắn cùng với thông tin xác thực
trong auth
:
Node.js
// Message text passed from the client.
const text = request.data.text;
// Authentication / user information is automatically added to the request.
const uid = request.auth.uid;
const name = request.auth.token.name || null;
const picture = request.auth.token.picture || null;
const email = request.auth.token.email || null;
Python
# Message text passed from the client.
text = req.data["text"]
# Authentication / user information is automatically added to the request.
uid = req.auth.uid
name = req.auth.token.get("name", "")
picture = req.auth.token.get("picture", "")
email = req.auth.token.get("email", "")
Khoảng cách giữa vị trí của hàm có thể gọi và vị trí của ứng dụng khách gọi có thể gây ra độ trễ mạng. Để tối ưu hoá hiệu suất, hãy xem xét chỉ định vị trí hàm trong đó phù hợp và đảm bảo căn chỉnh vị trí của thiết bị có thể gọi cho phù hợp với vị trí đặt khi bạn khởi động SDK ở phía máy khách.
Nếu muốn, bạn có thể đính kèm chứng thực Kiểm tra ứng dụng để giúp bảo vệ tài nguyên phụ trợ khỏi hành vi lạm dụng, chẳng hạn như gian lận thanh toán hoặc lừa đảo. Xem Bật chế độ thực thi tính năng Kiểm tra ứng dụng cho Cloud Functions.
Đang gửi lại kết quả
Để gửi dữ liệu trở lại ứng dụng, hãy trả về dữ liệu có thể được mã hoá JSON. Cho ví dụ: để trả về kết quả của phép cộng:
Node.js
// returning result.
return {
firstNumber: firstNumber,
secondNumber: secondNumber,
operator: "+",
operationResult: firstNumber + secondNumber,
};
Python
return {
"firstNumber": first_number,
"secondNumber": second_number,
"operator": "+",
"operationResult": first_number + second_number
}
Văn bản được dọn dẹp trong ví dụ về văn bản tin nhắn sẽ được trả về cho cả ứng dụng và Cơ sở dữ liệu theo thời gian thực. Trong Node.js, bạn có thể thực hiện việc này không đồng bộ bằng cách sử dụng lời hứa JavaScript:
Node.js
// Saving the new message to the Realtime Database.
const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize message.
return getDatabase().ref("/messages").push({
text: sanitizedMessage,
author: {uid, name, picture, email},
}).then(() => {
logger.info("New Message written");
// Returning the sanitized message to the client.
return {text: sanitizedMessage};
})
Python
# Saving the new message to the Realtime Database.
sanitized_message = sanitize_text(text) # Sanitize message.
db.reference("/messages").push({ # type: ignore
"text": sanitized_message,
"author": {
"uid": uid,
"name": name,
"picture": picture,
"email": email
}
})
print("New message written")
# Returning the sanitized message to the client.
return {"text": sanitized_message}
Định cấu hình CORS (Chia sẻ tài nguyên trên nhiều nguồn gốc)
Sử dụng tuỳ chọn cors
để kiểm soát những nguồn gốc có thể truy cập vào hàm của bạn.
Theo mặc định, các hàm có thể gọi được định cấu hình CORS để cho phép yêu cầu từ tất cả nguồn gốc. Để cho phép một số yêu cầu từ nhiều nguồn, nhưng không phải tất cả, hãy chuyển danh sách các miền hoặc biểu thức chính quy cụ thể được phép. Ví dụ:
Node.js
const { onCall } = require("firebase-functions/v2/https");
exports.getGreeting = onCall(
{ cors: [/firebase\.com$/, "https://flutter.com"] },
(request) => {
return "Hello, world!";
}
);
Để cấm các yêu cầu từ nhiều nguồn, hãy đặt chính sách cors
thành false
.
Xử lý lỗi
Để đảm bảo ứng dụng nhận được thông tin chi tiết hữu ích về lỗi, hãy trả về lỗi từ một lệnh gọi được
bằng cách gửi (hoặc để Node.js trả về một Lời hứa bị từ chối kèm theo) một phiên bản của
functions.https.HttpsError
hoặc https_fn.HttpsError
.
Lỗi có thuộc tính code
có thể là một trong các giá trị được liệt kê trong gRPC
Mã trạng thái.
Các lỗi cũng có một chuỗi message
, mặc định là
thành một chuỗi trống. Các lớp này cũng có thể có trường details
(không bắt buộc) với phần tử
giá trị tùy ý. Nếu hàm của bạn gặp phải một lỗi không phải là lỗi HTTPS,
khách hàng của bạn lại nhận được thông báo lỗi với thông báo INTERNAL
và mã
internal
Ví dụ: một hàm có thể gửi lỗi xác thực và xác thực dữ liệu kèm theo thông báo lỗi để quay lại ứng dụng khách gọi:
Node.js
// Checking attribute.
if (!(typeof text === "string") || text.length === 0) {
// Throwing an HttpsError so that the client gets the error details.
throw new 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 (!request.auth) {
// Throwing an HttpsError so that the client gets the error details.
throw new HttpsError("failed-precondition", "The function must be " +
"called while authenticated.");
}
Python
# Checking attribute.
if not isinstance(text, str) or len(text) < 1:
# Throwing an HttpsError so that the client gets the error details.
raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.INVALID_ARGUMENT,
message=('The function must be called with one argument, "text",'
" containing the message text to add."))
# Checking that the user is authenticated.
if req.auth is None:
# Throwing an HttpsError so that the client gets the error details.
raise https_fn.HttpsError(code=https_fn.FunctionsErrorCode.FAILED_PRECONDITION,
message="The function must be called while authenticated.")
Triển khai hàm có thể gọi
Sau khi bạn lưu một hàm có thể gọi hoàn chỉnh trong index.js
, hàm này
được triển khai cùng với tất cả hàm khác khi bạn chạy firebase deploy
.
Để chỉ triển khai đối số có thể gọi, hãy sử dụng đối số --only
như minh hoạ để thực hiện
triển khai một phần:
firebase deploy --only functions:addMessage
Nếu bạn gặp phải lỗi về quyền khi triển khai các chức năng, hãy đảm bảo rằng các vai trò quản lý danh tính và quyền truy cập (IAM) thích hợp là gán cho người dùng chạy lệnh triển khai.
Thiết lập môi trường phát triển khách hàng
Đảm bảo bạn đáp ứng mọi điều kiện tiên quyết, sau đó thêm các phần phụ thuộc bắt buộc và thư viện ứng dụng vào ứng dụng của bạn.
iOS trở lên
Làm theo hướng dẫn để thêm Firebase vào ứng dụng Apple của bạn.
Sử dụng Trình quản lý gói Swift để cài đặt và quản lý các phần phụ thuộc Firebase.
- Trong Xcode, khi dự án ứng dụng của bạn đang mở, hãy chuyển đến Tệp > Thêm gói.
- Khi được nhắc, hãy thêm kho lưu trữ SDK nền tảng Apple của Firebase:
- Chọn thư viện Cloud Functions.
- Thêm cờ
-ObjC
vào mục Cờ trình liên kết khác trong chế độ cài đặt bản dựng của mục tiêu. - Khi hoàn tất, Xcode sẽ tự động bắt đầu phân giải và tải xuống các phần phụ thuộc trong nền.
https://github.com/firebase/firebase-ios-sdk.git
Web
- Làm theo hướng dẫn để
thêm Firebase vào ứng dụng web. Đảm bảo bạn chạy
lệnh sau từ thiết bị đầu cuối của bạn:
npm install firebase@10.12.4 --save
Yêu cầu cả cốt lõi Firebase và Cloud Functions theo cách thủ công:
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);
Android
Làm theo hướng dẫn để thêm Firebase vào ứng dụng Android.
Trong tệp Gradle mô-đun (cấp ứng dụng) (thường là
<project>/<app-module>/build.gradle.kts
hoặc<project>/<app-module>/build.gradle
), thêm phần phụ thuộc cho thư viện Cloud Functions dành cho Android. Bạn nên sử dụng Bảng kê khai thành phần của Firebase cho Android để kiểm soát việc tạo phiên bản thư viện.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.1.2")) // 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") }
Bằng cách sử dụng Firebase Android BoM, ứng dụng của bạn sẽ luôn sử dụng các phiên bản tương thích của thư viện Android trên Firebase.
(Phương án thay thế) Thêm các phần phụ thuộc của thư viện Firebase mà không sử dụng BoM
Nếu chọn không sử dụng BoM của Firebase, bạn phải chỉ định từng phiên bản thư viện Firebase trong dòng phụ thuộc.
Lưu ý rằng nếu bạn sử dụng nhiều thư viện Firebase trong ứng dụng của mình, chúng tôi thực sự bạn nên sử dụng BoM để quản lý các phiên bản thư viện. Điều này đảm bảo rằng tất cả các phiên bản đều tương thích.
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:21.0.0") }
Khởi chạy SDK ứng dụng
Khởi chạy một bản sao của Cloud Functions:
Swift
lazy var functions = Functions.functions()
Objective-C
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
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();
Gọi hàm
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"];
}];
Web
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
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;
});
}
Xử lý lỗi trên ứng dụng
Máy khách nhận được thông báo lỗi nếu máy chủ báo lỗi hoặc nếu lời hứa kết quả đã bị từ chối.
Nếu lỗi được hàm trả về thuộc loại function.https.HttpsError
,
thì ứng dụng sẽ nhận được lỗi code
, message
và details
từ
lỗi máy chủ. Nếu không, lỗi sẽ chứa thông báo INTERNAL
và
mã INTERNAL
. Xem hướng dẫn về cách
xử lý lỗi trong hàm có thể gọi.
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"];
}
// ...
}
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;
// ...
});
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;
}
});
Đề xuất: Ngăn chặn hành vi sai trái bằng tính năng Kiểm tra ứng dụng
Trước khi phát hành ứng dụng, bạn nên bật tính năng Kiểm tra ứng dụng để đảm bảo chỉ các ứng dụng của bạn mới có thể truy cập vào điểm cuối của hàm có thể gọi.