تتيح لك حزم SDK الخاصة بعميل Cloud Functions for Firebase استدعاء الوظائف مباشرةً من تطبيق Firebase. لاستدعاء وظيفة من تطبيقك بهذه الطريقة، اكتب وظيفة HTTP قابلة للاستدعاء ونشرها في Cloud Functions، ثم أضف منطق العميل لاستدعاء الوظيفة من تطبيقك.
من المهم أن تضع في اعتبارك أن وظائف HTTP القابلة للاستدعاء متشابهة ولكنها ليست متطابقة مع وظائف HTTP. لاستخدام وظائف HTTP القابلة للاستدعاء، يجب عليك استخدام SDK للعميل لنظامك الأساسي مع واجهة برمجة التطبيقات الخلفية (أو تنفيذ البروتوكول). تحتوي العناصر القابلة للاستدعاء على هذا الاختلاف الرئيسي عن وظائف HTTP:
- باستخدام العناصر القابلة للاستدعاء، يتم تلقائيًا تضمين رموز Firebase Authentication المميزة ورموز FCM ورموز التحقق من التطبيق، عند توفرها، في الطلبات تلقائيًا.
- يقوم المشغل تلقائيًا بإلغاء تسلسل نص الطلب والتحقق من صحة رموز المصادقة.
يتفاعل الجيل الثاني من Firebase SDK for Cloud Functions والإصدارات الأحدث مع الحد الأدنى من إصدارات SDK لعميل Firebase لدعم وظائف HTTPS القابلة للاستدعاء:
- Firebase SDK لمنصات Apple 10.15.0
- Firebase SDK لنظام التشغيل Android 20.3.1
- الإصدار 9.7.0 من Firebase Modular Web SDK
إذا كنت تريد إضافة وظائف مشابهة إلى تطبيق مبني على نظام أساسي غير مدعوم، فراجع مواصفات البروتوكول لـ https.onCall
. يوفر الجزء المتبقي من هذا الدليل إرشادات حول كيفية كتابة ونشر واستدعاء وظيفة HTTP قابلة للاستدعاء لأنظمة Apple الأساسية وAndroid والويب و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 على جانب العميل.
اختياريًا، يمكنك إرفاق شهادة التحقق من التطبيق للمساعدة في حماية موارد الواجهة الخلفية لديك من سوء الاستخدام، مثل الاحتيال في الفواتير أو التصيد الاحتيالي. راجع تمكين فرض التحقق من التطبيق لوظائف السحابة .
إرسال النتيجة مرة أخرى
لإرسال البيانات مرة أخرى إلى العميل، قم بإرجاع البيانات التي يمكن ترميزها بتنسيق 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 المناسبة للمستخدم الذي يقوم بتشغيل أوامر النشر.
قم بإعداد بيئة تطوير العميل الخاص بك
تأكد من استيفاء أي متطلبات أساسية، ثم أضف التبعيات المطلوبة ومكتبات العملاء إلى تطبيقك.
دائرة الرقابة الداخلية +
اتبع الإرشادات لإضافة Firebase إلى تطبيق Apple الخاص بك .
استخدم Swift Package Manager لتثبيت تبعيات Firebase وإدارتها.
- في Xcode، مع فتح مشروع التطبيق الخاص بك، انتقل إلى File > Add Packages .
- عندما يُطلب منك ذلك، قم بإضافة مستودع Firebase Apple الأساسي لـ SDK:
- اختر مكتبة وظائف السحابة.
- عند الانتهاء، سيبدأ Xcode تلقائيًا في حل وتنزيل تبعياتك في الخلفية.
https://github.com/firebase/firebase-ios-sdk
واجهة برمجة تطبيقات الويب المعيارية
- اتبع الإرشادات لإضافة Firebase إلى تطبيق الويب الخاص بك . تأكد من تشغيل الأمر التالي من جهازك الطرفي:
npm install firebase@10.4.0 --save
تتطلب يدويًا كلاً من وظائف 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);
واجهة برمجة تطبيقات مساحة اسم الويب
- اتبع الإرشادات لإضافة Firebase إلى تطبيق الويب الخاص بك .
- أضف مكتبات عملاء 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.
- قم بتشغيل الأمر التالي من جهازك الطرفي:
npm install firebase@8.10.1 --save
- يتطلب يدويًا كلاً من وظائف Firebase الأساسية والسحابية:
const firebase = require("firebase"); // Required for side-effects require("firebase/functions");
Kotlin+KTX
اتبع الإرشادات لإضافة Firebase إلى تطبيق Android الخاص بك .
في ملف 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.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") }
باستخدام 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-ktx:20.3.1") }
Java
اتبع الإرشادات لإضافة Firebase إلى تطبيق Android الخاص بك .
في ملف 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.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") }
باستخدام 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.3.1") }
Dart
اتبع التعليمات لإضافة Firebase إلى تطبيق Flutter .
من جذر مشروع Flutter، قم بتشغيل الأمر التالي لتثبيت المكون الإضافي:
flutter pub add cloud_functions
بمجرد الانتهاء، قم بإعادة إنشاء تطبيق Flutter الخاص بك:
flutter run
بمجرد التثبيت، يمكنك الوصول إلى المكون الإضافي
cloud_functions
عن طريق استيراده في كود Dart الخاص بك:import 'package:cloud_functions/cloud_functions.dart';
سي ++
بالنسبة لـ C++ مع Android :
- اتبع التعليمات لإضافة Firebase إلى مشروع C++ الخاص بك .
- أضف مكتبة
firebase_functions
إلى ملفCMakeLists.txt
.
بالنسبة لـ C++ مع منصات Apple :
- اتبع التعليمات لإضافة Firebase إلى مشروع C++ الخاص بك .
- أضف جراب Cloud Functions إلى
Podfile
الخاص بك:pod 'Firebase/Functions'
- احفظ الملف، ثم قم بتشغيل:
pod install
- أضف إطاري عمل Firebase الأساسي وCloud Functions من Firebase C++ SDK إلى مشروع Xcode الخاص بك.
-
firebase.framework
-
firebase_functions.framework
-
وحدة
- اتبع الإرشادات لإضافة Firebase إلى مشروع Unity الخاص بك .
- قم بإضافة
FirebaseFunctions.unitypackage
من Firebase Unity SDK إلى مشروع Unity الخاص بك.
تهيئة العميل SDK
تهيئة مثيل للوظائف السحابية:
سويفت
lazy var functions = Functions.functions()
ج موضوعية
@property(strong, nonatomic) FIRFunctions *functions;
// ...
self.functions = [FIRFunctions functions];
واجهة برمجة تطبيقات مساحة اسم الويب
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();
واجهة برمجة تطبيقات الويب المعيارية
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;
سي ++
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
}
}
ج موضوعية
[[_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"];
}];
واجهة برمجة تطبيقات مساحة اسم الويب
var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({ text: messageText })
.then((result) => {
// Read result of the Cloud Function.
var sanitizedMessage = result.data.text;
});
واجهة برمجة تطبيقات الويب المعيارية
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;
سي ++
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]
}
// ...
}
ج موضوعية
if (error) {
if ([error.domain isEqual:@"com.firebase.functions"]) {
FIRFunctionsErrorCode code = error.code;
NSString *message = error.localizedDescription;
NSObject *details = error.userInfo[@"details"];
}
// ...
}
واجهة برمجة تطبيقات مساحة اسم الويب
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;
// ...
});
واجهة برمجة تطبيقات الويب المعيارية
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);
}
سي ++
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;
}
});
موصى به: منع إساءة الاستخدام من خلال التحقق من التطبيق
قبل تشغيل التطبيق الخاص بك، يجب عليك تمكين التحقق من التطبيق للمساعدة في التأكد من أن تطبيقاتك فقط هي التي يمكنها الوصول إلى نقاط النهاية الوظيفية القابلة للاستدعاء.