标签: firebase-admin

从nodejs调用firebase云函数

我想从另一个 NodeJS 服务器或只是一个 NodeJS 脚本调用 Firebase 的云函数。

我的 firebase 函数是 onCall 函数。

我正在使用https://www.npmjs.com/package/firebase-admin与 firebase 交互,但它似乎没有调用云函数的方法...

我可以用其他方式做吗?比如http请求?

node.js firebase google-cloud-functions firebase-admin google-cloud-firestore

5
推荐指数
1
解决办法
5533
查看次数

使用 Firebase Admin SDK 将转化事件添加到云消息

我可以使用下面的代码发送推送通知,但我还需要将“转化事件”与通知相关联。这可以通过控制台完成,但我找不到如何使用 SDK 来完成此操作。

var message = new Message()
            {
                Data = new Dictionary<string, string>()
                {
                    { "test1", "6165" },
                    { "test2", "161" },
                },
                Notification =
                {
                    Body = "",
                    Title = ""
                },
                Topic = topic,

            };
            // Send a message to the devices subscribed to the provided topic.
            Task<string> response =  FirebaseMessaging.DefaultInstance.SendAsync(message, true);
            // Response is a message ID string.
            response.Wait();
            Console.WriteLine("Successfully sent message: " + response);
Run Code Online (Sandbox Code Playgroud)

firebase firebase-cloud-messaging firebase-analytics firebase-admin

5
推荐指数
0
解决办法
217
查看次数

Firebase 管理 SDK:未获取访问令牌

目标是让我的 Express 服务器使用 Firebase Cloud Messaging (FCM) 发送推送通知。

问题是admin SDK的初始化似乎不起作用。代码是用 JavaScript 编写的,节点版本是 10.16.0,firebase-admin 版本是 8.3.0,服务器在最新的 Ubuntu 上运行。

我按照 firebase 指南设置了管理 SDK: https ://firebase.google.com/docs/admin/setup#initialize_the_sdk

设置了 GOOGLE_APPLICATION_CREDENTIALS 环境变量,并尝试使用该变量打开文件:

nano $GOOGLE_APPLICATION_CREDENTIALS
Run Code Online (Sandbox Code Playgroud)

一次

admin.messaging().send(message)
Run Code Online (Sandbox Code Playgroud)

被调用时,会抛出以下错误:

Error sending message: { Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal metadata.google.internal:80. Error code: ENOTFOUND".
    at FirebaseAppError.FirebaseError [as constructor] (/local/home/user/node_modules/firebase-admin/lib/utils/error.js:42:28)
    at FirebaseAppError.PrefixedFirebaseError …
Run Code Online (Sandbox Code Playgroud)

node.js firebase firebase-cloud-messaging firebase-admin

5
推荐指数
1
解决办法
7802
查看次数

如何在 Node js 中加载 Firebase 管理密钥?

我想使用 firebase admin SDK 让我的节点服务器免费访问我的数据库。index.js这是我文件夹中的代码functions

const functions = require("firebase-functions");
const admin = require("firebase-admin");

// Initialize app
admin.initializeApp({
  credential: admin.credential.cert("logininfo.json"),
  databaseURL: "https://thenameofmydatabase.firebaseio.com/",
  databaseAuthVariableOverride: {
    uid: "nameserver"
  }
});
Run Code Online (Sandbox Code Playgroud)

在同一个文件夹中,我有我的 logininfo.json,它看起来像这样(出于明显的原因审查了密钥):

{
  "type": "service_account",
  "project_id": "...",
  "private_key_id": "...",
  "private_key": "...",
  "client_email": "...",
  "client_id": "...",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "..."
}
Run Code Online (Sandbox Code Playgroud)

Failed to parse certificate key file: Error: ENOENT: no such file or directory但是,我在尝试部署到 firebase 托管时收到错误。

我该如何解决这个问题,是否有更安全/优雅的方法来处理这个问题?我可以在 firebase 托管中的某处更改GOOGLE_APPLICATION_CREDENTIALS变量吗?

node.js firebase firebase-hosting google-cloud-functions firebase-admin

5
推荐指数
1
解决办法
4302
查看次数

Spring boot - 从 jar 内访问 firebase admin sdk 凭证 json 文件

我有一个使用 Firebase Admin SDK 的 Java Spring Boot 后端应用程序。在 FirebaseConfig 的 init 方法中,我必须提供 FirebaseOptions 的凭据文件,

@PostConstruct
public void init() throws IOException {
    ClassLoader classLoader=Thread.currentThread().getContextClassLoader();
    FileInputStream refreshToken = new FileInputStream("src/main/resources/progresee-fa969-firebase-adminsdk-3vip2-d80bf340b7.json");
    FirebaseOptions options = new FirebaseOptions.Builder()
        .setCredentials(GoogleCredentials.fromStream(refreshToken))
        .setDatabaseUrl(dbUrl)
        .build();
    FirebaseApp.initializeApp(options);
}
Run Code Online (Sandbox Code Playgroud)

当我在本地运行时一切正常,但是当我构建 jar 文件并上传到服务器托管服务(AWS)时,我收到 FileNotFound 错误 -

Caused by: java.io.FileNotFoundException: /progresee-fa969-firebase-adminsdk-3vip2-d80bf340b7.json (No such file or directory)
at java.io.FileInputStream.open0(Native Method) ~[na:1.8.0_222]
at java.io.FileInputStream.open(FileInputStream.java:195) ~[na:1.8.0_222]
at java.io.FileInputStream.<init>(FileInputStream.java:138) ~[na:1.8.0_222]
at java.io.FileInputStream.<init>(FileInputStream.java:93) ~[na:1.8.0_222]
at com.progresee.app.firebase.FirebaseConfig.init(FirebaseConfig.java:55) ~[classes!/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_222]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_222]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_222] …
Run Code Online (Sandbox Code Playgroud)

java spring firebase-admin

5
推荐指数
1
解决办法
2342
查看次数

firebase 无法确定项目 ID

这是我使用节点发出的请求


// Initialize the default app
var admin = require('firebase-admin');

var app = admin.initializeApp({
  credential: admin.credential.applicationDefault(),
  databaseURL: process.env.FIREBASE_DATABASE
});

console.log(process.env.FIREBASE_DATABASE);


router.post('/', (req, res, next) => {

    app.auth().getUserByEmail("j.100233260@gmail.com")
    .then(function(userRecord) {
            // See the UserRecord reference doc for the contents of userRecord.
            console.log('Successfully fetched user data:', userRecord.toJSON());
            res.json(userRecord.toJSON())
        })
        .catch(function(error) {
                console.log('Error fetching user data:', error);
                res.json(error)

            });

        }

        );
Run Code Online (Sandbox Code Playgroud)

我在我的机器上设置了环境变量

在此输入图像描述

对于我的 firebase 数据库,我使用了 env

在此输入图像描述

给出为

databaseURL: "https://fssssss.firebaseio.com",
Run Code Online (Sandbox Code Playgroud)

从 Firebase 管理 GUI 中,

当我请求这条路线时邮递员中的错误

{
    "code": "app/invalid-credential",
    "message": "Failed to determine project …
Run Code Online (Sandbox Code Playgroud)

node.js firebase-authentication firebase-admin

5
推荐指数
2
解决办法
2万
查看次数

如何按“_createTime”对 firestore 文档进行排序?

我正在使用带有 Admin SDK 的云 Firebase 函数从我的 Firestore 集合中获取最新文档。排序基于timestamp字段。该值是在编写文档时明确提供的。

获取代码

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

这些console.log语句打印以下输出。看_createTime在底部。

输出

const fetchedTransaction = (await transactionsColRef.orderBy('timestamp', 'desc')
                .limit(1).get()).docs[0]

console.log(fetchedTransaction)
console.log('Transaction created at', fetchedTransaction.createTime.toDate())
Run Code Online (Sandbox Code Playgroud)

我正在寻找一种方法来排序文档,而_createTime不是timestamp每次都写入一个值。使用orderBy('_createTime')orderBy('createTime')没有效果。

firebase google-cloud-functions firebase-admin google-cloud-firestore

5
推荐指数
1
解决办法
2544
查看次数

无法在 Node.js 中导入 firebase-admin

我有一个 Node (14.3.0) 服务器,通过添加以下行在 package.json 中启用了 ES6 模块导入:

包.json:

"type": "module",

根据此处的 firebase-admin 文档:https ://firebase.google.com/docs/admin/setup/#node.js

如果您使用的是 ES2015,则可以导入该模块:

从“firebase-admin”导入*作为管理员;

当我使用时import * as admin from 'firebase-admin';,我收到以下错误:

凭证:admin.credential.applicationDefault(),
TypeError:无法读取未定义的属性“applicationDefault”

似乎firebase-admin没有正确导入 - 我尝试删除"type": "module"package.json 中的行并使用 require 导入 firebase-admin :

const admin = require(firebase-admin)

它有效,所以我的问题是 - 是否可以firebase-admin使用 ES6 导入 Node,如果可以,如何导入?

下面是一个完整的、最小的复制品:

服务器.js

import express from 'express';
import * as admin from 'firebase-admin';

const app = express();
const PORT = process.env.PORT || 5000;

app.use(express.json());

admin.initializeApp({
  credential: admin.credential.applicationDefault(), …
Run Code Online (Sandbox Code Playgroud)

node.js firebase ecmascript-6 es6-modules firebase-admin

5
推荐指数
1
解决办法
4545
查看次数

是否可以使用“firebase-admin”包调用 firebase 函数?

我有带有基于服务帐户的访问权限的节点应用程序,所以我使用了firebase-admin. 正如我之前所看到的,firebase-admin大部分是重复的firebase包(除了身份验证部分、签名和其他一些部分),但现在我想调用函数,但找不到firebase.apps[0].functions().httpsCallable('myFunction'). 我研究了 Typescript 类型,他们甚至没有提到函数。

admin.initializeApp({
  credential: admin.credential.cert('./service-account-credentials.json'),
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
});

const config = {
  storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
};

const storageBucket = admin.storage().bucket(config.storageBucket);
const firestore = admin.firestore();



// const functions = admin.apps[0].functions(); // not possible
const functions = firebase.apps[0].functions(); // possible, but Firestore.apps not initialized
Run Code Online (Sandbox Code Playgroud)

我有什么选择?

node.js firebase firebase-admin

5
推荐指数
1
解决办法
2512
查看次数

无法在 Apple M1 芯片中安装 python django 的 firebase-admin pip 包

无法在 Apple M1 芯片系统中安装 firebase-admin

系统配置

System OS: macOS Bigsur(11.2.2) 
chip: Apple M1
python version: 3.9.2 
Pip Version: 20.0.1 
Djnago: 3.1.7 
Run Code Online (Sandbox Code Playgroud)

我使用以下步骤为我的项目创建虚拟环境

  1. install virtualenv using pip install virtualenv
  2. virtualenv venv -p python3.x(无论你想要哪个)
  3. source /your_project/venv/bin/activate
  4. venv将激活,然后您可以在 pip 的帮助下安装要求

之后我尝试安装 firebase-adminpip install firebase-admin并收到如下错误

File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/cffi/api.py", line 48, in __init__
        import _cffi_backend as backend
    ImportError: dlopen(/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so, 2): no suitable image found.  Did find:
        /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture
        /private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-build-env-aapo6r5y/normal/lib/python3.9/site-packages/_cffi_backend.cpython-39-darwin.so: mach-o, but wrong architecture


 File "/private/var/folders/2l/g855nfq11js0q9s9dc9ygk000000gn/T/pip-install-yurwgn0k/grpcio_2bb9c0d1fcb8462591aa5aa845bcb162/src/python/grpcio/_parallel_compile_patch.py", line 54, in …
Run Code Online (Sandbox Code Playgroud)

python django pip firebase-admin apple-m1

5
推荐指数
1
解决办法
2575
查看次数