Thứ Hai, 15 tháng 7, 2019

Firebase Push Notification in Flutter

1. Postman:

1. Method: POST
2. URL: https://fcm.googleapis.com/fcm/send
3. Headers:
Content-Type: application/json
Authorization: key=your_key
4. Body raw json:
{
    "to": "/topics/191448148",
    "collapse_key": "type_a",
    "notification": {
        "title": "TieuDe",
        "body": "NoiDung",
        "sound": "Enabled"

    },
    "data": {
        "title": "TieuDe",
        "body": "NoiDung",
        "dichvu": "1",
        "chucnang": "giaoduc",
        "chucnangid": "thongbao",
        "click_action": "FLUTTER_NOTIFICATION_CLICK"
    },
    "priority": "high"
}
5. Response json when success:
{
    "message_id": 607975690105141
}

2. C# code:

private void FirebasePush() {
    try {
        applicationID = "YOUR_KEY"; // legacy server key firebase
        string senderId = "YOUR_ID";

        WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
        tRequest.Method = "post";
        tRequest.ContentType = "application/json";
        var dataSend = new {
            to = "/topics/" + "TenTaiKhoan",
            collapse_key = "type_a",
            notification = new {
                title = row["TieuDe"],
                body = row["NoiDung"],
                sound = "Enabled"
            },
            data = new {
                title = row["TieuDe"],
                body = row["NoiDung"],
                dichvu = row["DichVu"],
                chucnang = row["ChucNang"],
                chucnangid = row["ChucNangID"],
                click_action = "FLUTTER_NOTIFICATION_CLICK"
            },
            priority = "high"
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(dataSend);
        Byte[] byteArray = Encoding.UTF8.GetBytes(json.ToString());

        tRequest.Headers.Add(string.Format("Authorization: key={0}", applicationID));
        tRequest.Headers.Add(string.Format("Sender: id={0}", senderId));
        tRequest.ContentLength = byteArray.Length;

        using(Stream dataStream = tRequest.GetRequestStream()) {

            dataStream.Write(byteArray, 0, byteArray.Length);
            using(WebResponse tResponse = tRequest.GetResponse()) {
                using(Stream dataStreamResponse = tResponse.GetResponseStream()) {
                    using(StreamReader tReader = new StreamReader(dataStreamResponse)) {
                        String sResponseFromServer = tReader.ReadToEnd();
                        string str = sResponseFromServer;
                        //Execute StoreProcedure
                        /*HERE*/
                    }
                }
            }
        }
    }
    catch {}
    Thread.Sleep(5000); // 5giay
}

Không có nhận xét nào:

Đăng nhận xét