如何使用FCM向特定用户发送通知?

42

我为FCM准备了接收器,并可以向所有设备发送通知。

通过此链接gcm-http.googleapis.com/gcm/send,可以向已注册的目标用户发送通知并将其发送到目标设备(例如以下JSON代码):

 {
     "notification": {
                "title": "sample Title",
                "text": "sample text"   },   
        "to" : "[registration id]"
         }

然而,我需要通过电子邮件或者姓名等方式向我选择的目标用户发送通知...

例如:

{
     "notification": {
                "title": "sample Title",
                "text": "sample text"   },   
        "to" : "[email or name or sex ...]"
         }

我该怎么做呢? 我需要创建一个Web服务器或其他东西吗?

2个回答

46

我需要创建一个Web服务器吗?

是的,您需要一个可以将名称/电子邮件映射到注册ID的地方。这些注册ID必须包含在向FCM的请求中。

{
    'registration_ids': ['qrgqry34562456', '245346236ef'],
    'notification': {
        'body': '',
        'title': ''
    },
    'data': {

    }
}

将推送发送到'qrgqry34562456'和'245346236ef'。

在调用中使用的注册ID是在应用程序中此回调中称为“token”的ID。

public class MyService extends FirebaseInstanceIdService {
    @Override
    public void onTokenRefresh() {
    }
}

谢谢您的回复。对我很有帮助。我几乎阅读了FCM的所有文档。那里写着和您的回答一样的内容。我想确认一下,因为我认为有一个用于通知的服务器。 - Olcay Sönmez
3
注册 ID 和注册令牌是同一物吗? - Angga Ari Wijaya
2
@AnggaAriWijaya 是的 - Tim
很好,但是如果你可以从FirebaseInstanceId.getInstance().getToken()或者类AppFirebaseMessageingService中获取,会更好:class AppFirebaseMessageingService: FirebaseMessagingService() {override fun onNewToken(token: String?) { super.onNewToken(token) } override fun onMessageReceived(msg: RemoteMessage?) { super.onMessageReceived(msg) }} - John Albert
所以如果我理解正确的话,在我们获得注册ID之后,我们需要在自己的端点上进行一次postback来保存该注册ID以及用户在我们系统中的唯一标识符。而Firebase没有办法为我们保存那些数据吗? - TheWebGuy
2
@TheWebGuy 是的。如果你不知道要发送消息给谁,你该如何告诉 Firebase 呢? - Tim

0

使用此代码,您可以向其他设备发送消息。此代码中不需要服务器。

public  String send(String to,  String body) {
            try {

                final String apiKey = "AIzaSyBsY_tfxxxxxxxxxxxxxxx";
                URL url = new URL("https://fcm.googleapis.com/fcm/send");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setDoOutput(true);
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.setRequestProperty("Authorization", "key=" + apiKey);
                conn.setDoOutput(true);
                JSONObject message = new JSONObject();
                message.put("to", to);
                message.put("priority", "high");

                JSONObject notification = new JSONObject();
               // notification.put("title", title);
                notification.put("body", body);
                message.put("data", notification);
                OutputStream os = conn.getOutputStream();
                os.write(message.toString().getBytes());
                os.flush();
                os.close();

                int responseCode = conn.getResponseCode();
                System.out.println("\nSending 'POST' request to URL : " + url);
                System.out.println("Post parameters : " + message.toString());
                System.out.println("Response Code : " + responseCode);
                System.out.println("Response Code : " + conn.getResponseMessage());

                BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String inputLine;
                StringBuffer response = new StringBuffer();

                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();

                // print result
                System.out.println(response.toString());
                return response.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return "error";
        }

4
这不是推荐的方式,因为任何人都可以使用类似 Smali2Java 的工具获取你的 API 密钥,并向任何人发送通知。 - kunwar97
那是黑客攻击的一部分,我也不建议这样做,但我正在提供我们可以从这里完成它的答案,如果需要,我们可以通过加密密钥来保护该部分。是的,谢谢你让我知道这个。 - Durgesh Kumar
1
我们将如何使用这个? - Tarlan Ahad
10
“我们可以通过对密钥进行加密来保证该部分的安全性” - 这不是真实情况。 - Tim
6
不要这样做。你的私人API密钥是用于你控制下的硬件上使用的,请勿公开分发它。 - Caleb_Allen
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接