تتيح لك حزم SDK لعملاء Cloud Functions for Firebase استدعاء الدوال مباشرةً من تطبيق Firebase. لاستدعاء دالة من تطبيقك بهذه الطريقة، اكتب وانشر إحدى وظائف HTTP Callable في دوال السحابة، ثم أضف منطق العميل لاستدعاء الدالة من تطبيقك.
من المهم أن تضع في اعتبارك أنّ دوال HTTP القابلة للاستدعاء متشابهة ولكنها غير متطابقة مع دوال HTTP. لاستخدام وظائف HTTP القابلة للاتصال، يجب عليك استخدام حزمة SDK للعميل لنظامك الأساسي مع واجهة برمجة التطبيقات الخلفية (أو تنفيذ البروتوكول). تتميز العناصر القابلة للاتصال بهذا الاختلاف الرئيسي عن دوال HTTP:
- ويتم تلقائيًا تضمين الرموز المميّزة لمصادقة Firebase ورموز FCM والرموز المميّزة لـ App Check، إن توفّرت في الطلبات.
- يُلغي العامل المشغِّل تلقائيًا نص الطلب ويتحقق من صحة رموز المصادقة المميزة.
تتوافق حزمة تطوير البرامج (SDK) لمنصّة Firebase الخاصة بوظائف السحابة الإلكترونية من الجيل الثاني والأعلى منها مع إصدارات الحد الأدنى لحزمة تطوير البرامج (SDK) الخاصة بعميل Firebase من أجل إتاحة وظائف HTTPS القابلة للاتصال:
- حزمة تطوير البرامج (SDK) لمنصة Firebase للإصدار 10.26.0 من أنظمة Apple الأساسية
- حزمة تطوير البرامج (SDK) لمنصة Firebase لنظام التشغيل Android 21.0.0
- حزمة تطوير البرامج (SDK) للوحدة التنظيمية على Firebase، الإصدار 9.7.0
إذا كنت ترغب في إضافة وظائف مماثلة إلى تطبيق تم إنشاؤه على نظام أساسي غير متوافق،
اطّلع على مواصفات البروتوكول لـ 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 = 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;
يمكن أن تخلق المسافة بين موقع الدالة القابلة للاستدعاء وموقع عميل الاتصال، وقت استجابة الشبكة. لتحسين الأداء، يمكنك تحديد الموقع الجغرافي للوظيفة حيثما ينطبق ذلك، والتأكّد من محاذاة موقع الجهاز القابل للاستدعاء مع الموقع الجغرافي الذي تم ضبطه عند إعداد حزمة تطوير البرامج (SDK) من جهة العميل.
يمكنك اختياريًا إرفاق مصادقة "فحص التطبيقات" للمساعدة في حماية موارد الخلفية من إساءة الاستخدام، مثل الاحتيال في الفوترة أو التصيّد الاحتيالي. يُرجى الاطّلاع على مقالة تفعيل فرض فحص التطبيقات لدوال Cloud.
جارٍ إرسال النتيجة
لإرسال البيانات مرة أخرى إلى العميل، يمكنك عرض البيانات التي يمكن ترميزها بتنسيق 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 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};
})
التعامل مع الأخطاء
لضمان حصول العميل على تفاصيل مفيدة عن الخطأ، عليك عرض أخطاء من طلب يمكن استدعاءه من خلال طرح مثيل 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 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.");
}
نشر الدالة القابلة للاتصال
بعد حفظ دالة قابلة للاستدعاء مكتملة في index.js
، يتم نشرها مع جميع الدوال الأخرى عند تشغيل firebase deploy
.
لنشر الدالة التي يمكن طلبها فقط، استخدِم الوسيطة --only
كما هو موضّح لتنفيذ عمليات النشر الجزئية:
firebase deploy --only functions:addMessage
إذا واجهت أخطاء في الأذونات عند نشر الوظائف، تأكَّد من تحديد أدوار إدارة الهوية وإمكانية الوصول المناسبة للمستخدم الذي يشغل أوامر النشر.
إعداد بيئة تطوير العميل
احرص على استيفاء أي متطلبات أساسية، ثم أضِف التبعيات المطلوبة ومكتبات العملاء إلى تطبيقك.
iOS+
اتّبِع التعليمات من أجل إضافة Firebase إلى تطبيق Apple.
استخدِم "مدير الحزم" في Swift لتثبيت تبعيات Firebase وإدارتها.
- في Xcode، بعد فتح مشروع التطبيق، انتقِل إلى ملف > إضافة حزم.
- أضِف مستودع حزمة تطوير البرامج (SDK) لمنصة Firebase من Apple عندما يُطلب منك ذلك:
- اختر مكتبة Cloud Functions.
- أضِف العلامة
-ObjC
إلى قسم علامات روابط أخرى في إعدادات إصدار الهدف. - عند الانتهاء، سيبدأ Xcode تلقائيًا في حل تبعياتك وتنزيلها في الخلفية.
https://github.com/firebase/firebase-ios-sdk.git
واجهة برمجة تطبيقات الويب النموذجية
- اتّبِع التعليمات
لإضافة Firebase إلى تطبيق الويب. احرص على تنفيذ
الأمر التالي من الوحدة الطرفية:
npm install firebase@10.12.1 --save
أن تتطلب كلاً من وظيفتَي Firebase الأساسية وCloud بشكل يدوي:
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 الأساسية وCloud:
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
)، أضِف التبعية لمكتبة دوال السحابة الإلكترونية لنظام التشغيل Android. ننصحك باستخدام برنامج Firebase Android BoM للتحكّم في إصدارات المكتبة.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.0.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") }
باستخدام إطار عمل Android BoM، سيستخدم تطبيقك دائمًا إصدارات متوافقة من مكتبات Android في Firebase.
(بديل) أضِف تبعيات مكتبة Firebase بدون استخدام قائمة BoM.
إذا اختَرت عدم استخدام قائمة مشروعات Firebase، يجب تحديد كل إصدار من إصدارات مكتبة 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:21.0.0") }
Java
اتّبِع التعليمات لإضافة Firebase إلى تطبيق Android.
في ملف Gradle للوحدة (على مستوى التطبيق) (عادةً
<project>/<app-module>/build.gradle.kts
أو<project>/<app-module>/build.gradle
)، أضِف التبعية لمكتبة دوال السحابة الإلكترونية لنظام التشغيل Android. ننصحك باستخدام برنامج Firebase Android BoM للتحكّم في إصدارات المكتبة.dependencies { // Import the BoM for the Firebase platform implementation(platform("com.google.firebase:firebase-bom:33.0.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") }
باستخدام إطار عمل Android BoM، سيستخدم تطبيقك دائمًا إصدارات متوافقة من مكتبات Android في Firebase.
(بديل) أضِف تبعيات مكتبة Firebase بدون استخدام قائمة BoM.
إذا اختَرت عدم استخدام قائمة مشروعات Firebase، يجب تحديد كل إصدار من إصدارات مكتبة 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:21.0.0") }
Dart
اتّبِع التعليمات من أجل إضافة Firebase إلى تطبيق Flutter.
من جذر مشروع Flutter، شغِّل الأمر التالي لتثبيت المكوّن الإضافي:
flutter pub add cloud_functions
بعد اكتمال الخطوات، أعِد إنشاء تطبيق Flutter:
flutter run
بعد التثبيت، يمكنك الوصول إلى المكوّن الإضافي
cloud_functions
عن طريق استيراده في رمز Dart:import 'package:cloud_functions/cloud_functions.dart';
C++
بالنسبة إلى لغة C++ مع Android:
- اتّبِع التعليمات لإضافة Firebase إلى مشروع C++ الخاص بك.
- أضِف مكتبة
firebase_functions
إلى ملفCMakeLists.txt
.
بالنسبة إلى C++ مع أنظمة Apple الأساسية:
- اتّبِع التعليمات لإضافة Firebase إلى مشروع C++ الخاص بك.
- إضافة مجموعة دوال السحابة إلى
Podfile
:pod 'Firebase/Functions'
- احفظ الملف، ثم شغِّل:
pod install
- أضِف إطارَي العمل الأساسيَين ووظائف السحابة الإلكترونية في Firebase من
حزمة تطوير البرامج (SDK) الخاصة بمنصة Firebase C++ إلى مشروع Xcode.
firebase.framework
firebase_functions.framework
Unity
- اتّبِع التعليمات من أجل إضافة Firebase إلى مشروع Unity.
- أضِف حزمة
FirebaseFunctions.unitypackage
من حزمة تطوير البرامج (SDK) لنظام Firebase Unity إلى مشروع Unity.
إعداد حزمة تطوير البرامج (SDK) للعميل
إعداد مثيل من دوال السحابة:
Swift
lazy var functions = Functions.functions()
Objective-C
@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;
C++
firebase::functions::Functions* functions;
// ...
functions = firebase::functions::Functions::GetInstance(app);
Unity
functions = Firebase.Functions.DefaultInstance;
استدعاء الدالة
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"];
}];
واجهة برمجة تطبيقات مساحات الاسم على الويب
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;
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;
});
}
التعامل مع الأخطاء على العميل
يتلقى العميل رسالة خطأ إذا عرض الخادم خطأً أو إذا تم رفض الوعد الناتج.
إذا كان الخطأ الذي تعرضه الدالة من النوع function.https.HttpsError
،
سيتلقّى العميل الأخطاء code
وmessage
وdetails
من خطأ الخادم. وبخلاف ذلك، سيحتوي الخطأ على الرسالة INTERNAL
والرمز INTERNAL
. اطّلِع على إرشادات حول كيفية
التعامل مع الأخطاء في دالة إمكانية الاتصال.
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"];
}
// ...
}
واجهة برمجة تطبيقات مساحات الاسم على الويب
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);
}
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;
}
});
إجراء مقترَح: منع إساءة الاستخدام باستخدام ميزة "فحص التطبيقات"
قبل إطلاق التطبيق، يجب تفعيل ميزة فحص التطبيقات للمساعدة في ضمان وصول تطبيقاتك فقط إلى نقاط نهاية الوظائف التي يمكن الاتصال بها.