تتيح لك وظائف السحابة لحزم SDK لعميل Firebase استدعاء الوظائف مباشرة من تطبيق Firebase. لاستدعاء وظيفة من تطبيقك بهذه الطريقة ، اكتب وانشر وظيفة HTTP Callable في Cloud Functions ، ثم أضف منطق العميل لاستدعاء الوظيفة من تطبيقك.
من المهم أن تضع في اعتبارك أن وظائف HTTP القابلة للاستدعاء متشابهة ولكنها غير متطابقة مع وظائف HTTP. لاستخدام وظائف HTTP القابلة للاستدعاء ، يجب عليك استخدام عميل SDK للنظام الأساسي الخاص بك مع واجهة API الخلفية (أو تنفيذ البروتوكول). تحتوي العناصر القابلة للاستدعاء على هذه الاختلافات الرئيسية عن وظائف HTTP:
تحتوي العناصر القابلة للاستدعاء على هذه الاختلافات الرئيسية عن وظائف HTTP:
- مع العناصر القابلة للاستدعاء ورموز مصادقة Firebase ورموز FCM المميزة ورموز التحقق من التطبيقات ، عند توفرها ، يتم تضمينها تلقائيًا في الطلبات.
- يقوم المشغل تلقائيًا بإلغاء تسلسل نص الطلب والتحقق من صحة رموز المصادقة.
تعمل حزمة Firebase SDK للوظائف السحابية من الجيل الثاني والإصدارات الأحدث مع الحد الأدنى من إصدارات حزمة SDK لعميل Firebase لدعم وظائف HTTPS القابلة للاستدعاء:
- Firebase SDK لمنصات Apple 10.10.0
- Firebase SDK لنظام Android 20.3.1
- Firebase Modular Web SDK الإصدار 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) => {
// ...
});
بالنسبة إلى الوظيفة القابلة للاستدعاء التي تحفظ رسالة نصية في قاعدة بيانات Realtime ، على سبيل المثال ، يمكن أن تحتوي 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 على جانب العميل.
اختياريًا ، يمكنك إرفاق شهادة App Check للمساعدة في حماية موارد الواجهة الخلفية من إساءة الاستخدام ، مثل الاحتيال في الفواتير أو التصيد الاحتيالي. راجع تمكين فرض التحقق من التطبيق لوظائف السحابة .
إعادة إرسال النتيجة
لإرسال البيانات مرة أخرى إلى العميل ، قم بإرجاع البيانات التي يمكن تشفيرها بتنسيق 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 المناسبة للمستخدم الذي يقوم بتشغيل أوامر النشر.
قم بإعداد بيئة تطوير العميل الخاص بك
تأكد من استيفاء أي متطلبات مسبقة ، ثم أضف التبعيات ومكتبات العملاء المطلوبة إلى تطبيقك.
iOS +
اتبع التعليمات لإضافة Firebase إلى تطبيق Apple الخاص بك .
استخدم Swift Package Manager لتثبيت وإدارة تبعيات Firebase.
- في Xcode ، مع فتح مشروع التطبيق الخاص بك ، انتقل إلى ملف> إضافة حزم .
- عند المطالبة ، أضف مستودع SDK لأنظمة Apple الأساسية لـ Firebase:
- اختر مكتبة وظائف السحابة.
- عند الانتهاء ، سيبدأ Xcode تلقائيًا في حل وتنزيل التبعيات الخاصة بك في الخلفية.
https://github.com/firebase/firebase-ios-sdk
Web version 9
- اتبع التعليمات لإضافة Firebase إلى تطبيق الويب الخاص بك . تأكد من تشغيل الأمر التالي من جهازك الطرفي:
npm install firebase@9.22.1 --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);
Web version 8
- اتبع التعليمات لإضافة Firebase إلى تطبيق الويب الخاص بك .
- أضف مكتبات عميل Firebase core و 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>
تتوفر حزمة 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
) ، أضف التبعية لمكتبة Cloud Functions Android. نوصي باستخدام Firebase Android BoM للتحكم في إصدارات المكتبة.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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' }
باستخدام 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
) ، أضف التبعية لمكتبة Cloud Functions Android. نوصي باستخدام Firebase Android BoM للتحكم في إصدارات المكتبة.dependencies { // Import the BoM for the Firebase platform implementation platform('com.google.firebase:firebase-bom:32.1.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' }
باستخدام 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 ++
بالنسبة لـ C ++ مع Android :
- اتبع التعليمات لإضافة Firebase إلى مشروع C ++ الخاص بك .
- أضف مكتبة
firebase_functions
إلى ملفCMakeLists.txt
.
لـ C ++ مع منصات Apple :
- اتبع التعليمات لإضافة Firebase إلى مشروع C ++ الخاص بك .
- أضف جراب وظائف السحابة إلى
Podfile
:pod 'Firebase/Functions'
- احفظ الملف ، ثم قم بتشغيل:
pod install
- أضف إطار عمل Firebase core و Cloud Functions من Firebase C ++ SDK إلى مشروع Xcode الخاص بك.
-
firebase.framework
-
firebase_functions.framework
-
وحدة
- اتبع التعليمات لإضافة Firebase إلى مشروع Unity الخاص بك .
- أضف
FirebaseFunctions.unitypackage
من Firebase Unity SDK إلى مشروع الوحدة الخاص بك.
تهيئة العميل SDK
تهيئة مثيل من وظائف السحابة:
سويفت
lazy var functions = Functions.functions()
ج موضوعية
@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);
وحدة
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"];
}];
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(
{
"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);
}
وحدة
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"];
}
// ...
}
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);
// ...
وحدة
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;
}
});
موصى به: منع إساءة الاستخدام باستخدام التحقق من التطبيق
قبل بدء تشغيل التطبيق الخاص بك ، يجب عليك تمكين التحقق من التطبيق للمساعدة في ضمان أن تطبيقاتك فقط يمكنها الوصول إلى نقاط نهاية الوظائف القابلة للاستدعاء الخاصة بك.