quickstart-js icon indicating copy to clipboard operation
quickstart-js copied to clipboard

Following docs - sendTokenToServer() is not defined & showToken() is not defined

Open DanJ210 opened this issue 7 years ago • 9 comments

I've looked through issues and don't see this present. I have a code pen that shows code exactly. Everything seems to be working up to line 38 where. Before that I'll log the token out with messaging.getToken(); but on line 38 when sendTokenToServer(currentToken) is used is when I'm told that sendTokenToServer is not defined. Further below within the catch on line 288 I'm told that showToken() is also not defined.

This seems very easy but for some reason I can't get past why these certain methods are undefined and others before them aren't. Any help would be much appreciated. I'm following docs exactly but I'm only on the first page.

Code Pen - Firebase Implementation

DanJ210 avatar Dec 03 '18 21:12 DanJ210

Same problem

neosheps avatar Jan 17 '19 19:01 neosheps

I think Google has just abandoned their GitHub projects.

DanJ210 avatar Jan 18 '19 17:01 DanJ210

@DanJ210 Those functions are here:

https://github.com/firebase/quickstart-js/blob/a6c60d5b6efd513dd924af15c98e2d67e405ae51/messaging/index.html#L166

https://github.com/firebase/quickstart-js/blob/a6c60d5b6efd513dd924af15c98e2d67e405ae51/messaging/index.html#L157

This is a sample code, and there some functionality not implemented. I'm trying to implement this line:

https://github.com/firebase/quickstart-js/blob/a6c60d5b6efd513dd924af15c98e2d67e405ae51/messaging/index.html#L169

cluster28 avatar Feb 04 '19 11:02 cluster28

The code snippets in the docs link out to the samples @cluster28 provided, where you can find more context on what sendTokenToServer() and showToken() do.

If we added a comment to the snippets saying "this function needs to be implemented by you", would that help? Any other suggestions to make these steps more clear?

jhuleatt avatar Apr 09 '19 22:04 jhuleatt

It would certainly be better than nothing. I was following a tutorial so my assumption is that the method was part of one of the API's included in the firebase scripts. Some of us may be beginners so we are using to tutorials to explain on each part.

DanJ210 avatar Apr 10 '19 00:04 DanJ210

If you want to refresh the token, call this service to allow clients to register/refresh their instance in your database from frontend if (navigator && navigator.serviceWorker) { navigator.serviceWorker.register(url + "sw.js").then(register => { messaging.useServiceWorker(register); return navigator.serviceWorker.ready; }).then(function (reg) { reg.pushManager.getSubscription().then(function (subscription) { var Subscribe = JSON.parse(JSON.stringify(subscription)); var Key = Subscribe.keys; return fetch(url + "RegisterCredential", { method: "Post", headers: { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" }, body: JSON.stringify({ Endpoint: Subscribe.endpoint, P256dh: Key.p256dh, Auth: Key.auth }) }).catch(e => console.error(e)); }).catch(e => console.error("Error:" + e)); }).catch(e => console.error("Error:" + e)); }

Then from the backend of service verify the valid token of instance Id and create a new token based on information on above.

PS: endpoint is different each time client is open, do not trust it is solid and never change.

public async Task<HttpResponseMessage> RegisterCredential(TokenCredential Credential) { dynamic result = null; if (Context.TokenCredentials.Where(p => p.Name == Credential.Name).Any()) Context.TokenCredentials.Remove(Context.TokenCredentials.Where(p => p.Name == Credential.Name).SingleOrDefault()); Context.TokenCredentials.Add(new TokenCredential() { Name = Credential.Name, Endpoint = Credential.Endpoint, P256dh = Credential.P256dh, Auth = Credential.Auth }); await Context.SaveChangesAsync();

        var DeviceId = Context.Devices.Where(p => p.EmailName == Credential.Name).Select(p => p.DeviceId).SingleOrDefault();

        String Url = String.Format("https://iid.googleapis.com/iid/info/{0}?details=true", DeviceId);

        Boolean IsFound = false;
        while (!IsFound)
        {
            WebRequest WebRequest = WebRequest.Create(Url);
            WebRequest.Method = "Get";
            WebRequest.Headers.Add("Authorization", "key=MY_KEY");

            try
            {
                using (HttpWebResponse Response = (HttpWebResponse)WebRequest.GetResponse())
                {
                    using (Stream Stream = Response.GetResponseStream())
                    {
                        using (StreamReader Reader = new StreamReader(Stream))
                        {
                            IsFound = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                TokenCredential NewCredential = Context.TokenCredentials.Where(p => p.Name == Credential.Name).SingleOrDefault();
                String GenUrl = "https://iid.googleapis.com/v1/web/iid";

                var content = new
                {
                    endpoint = NewCredential.Endpoint,
                    keys = new
                    {
                        auth = NewCredential.Auth,
                        p256dh = NewCredential.P256dh
                    }
                };

                var Credetial_Content = JsonConvert.SerializeObject(content);
                Byte[] ConvertBytes = System.Text.Encoding.UTF8.GetBytes(Credetial_Content);

                WebRequest NewRequest = WebRequest.Create(GenUrl);
                NewRequest.Method = "Post";

                NewRequest.ContentType = "application/json";
                NewRequest.Headers.Add("Authorization", "key=My_KEY");
                NewRequest.ContentLength = ConvertBytes.Length;

                try
                {
                    using (Stream DataStream = NewRequest.GetRequestStream())
                    {
                        DataStream.Write(ConvertBytes, 0, ConvertBytes.Length);
                        using (HttpWebResponse Response = (HttpWebResponse)NewRequest.GetResponse())
                        {
                            using (Stream Stream = Response.GetResponseStream())
                            {
                                using (StreamReader Reader = new StreamReader(Stream))
                                {
                                    dynamic FromToken = JsonConvert.DeserializeObject<dynamic>(Reader.ReadToEnd());
                                    String NewToken = FromToken.token;
                                    if (Context.Devices.Where(p => p.EmailName == Credential.Name).Any())
                                        Context.Devices.Remove(Context.Devices.Where(p => p.EmailName == Credential.Name).SingleOrDefault());
                                    Context.Devices.Add(new Device() { EmailName = Credential.Name, DeviceId = NewToken });
                                    await Context.SaveChangesAsync();
                                }
                            }
                        }
                    }
                }
                catch (Exception ex_)
                {
                    result = String.Format("Error:{0}", ex_.Message);
                }
                IsFound = true;
            }
        }
        return new HttpResponseMessage(HttpStatusCode.Created);
    }

koklimabc avatar May 21 '19 07:05 koklimabc

More info can be found on "https://developers.google.com/instance-id/reference/server" After you have create new token from failed test of invalid token, stored it into your database for ready to sent out on future client/user. Well, I implement this on c# (plus entityframework) but you could try modify to suit your own language.

I'm still waiting setBackgroundMessagehandler do not working once browser was closed, it allowed to received push notification message even your browser is not open. It is working on last few months.

koklimabc avatar May 21 '19 07:05 koklimabc

Table Structure DeviceIds(Table) - For Valid token to Target Client Send Id | Name | Token

TokenCredentials - Token Credential help you to refresh token and create a new once failed Id| Name | Endpoint | p256dh | Auth

koklimabc avatar May 21 '19 07:05 koklimabc

Check your firebase-messaging-sw.js file. I fixed it by adding empty firebase-messaging-sw.js file, cause messaging service requires it.

Vondollie avatar Jul 08 '20 08:07 Vondollie