<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Christian Oluwawibe on Medium]]></title>
        <description><![CDATA[Stories by Christian Oluwawibe on Medium]]></description>
        <link>https://medium.com/@dev-tomiwa?source=rss-7f026b070569------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*drmpKi1WTWqHfetY_nJwyg.jpeg</url>
            <title>Stories by Christian Oluwawibe on Medium</title>
            <link>https://medium.com/@dev-tomiwa?source=rss-7f026b070569------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 04:47:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dev-tomiwa/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Migrate from Legacy Firebase Cloud Messaging APIs to HTTP v1]]></title>
            <link>https://dev-tomiwa.medium.com/migrate-from-legacy-firebase-cloud-messaging-apis-to-http-v1-7cf8ff864908?source=rss-7f026b070569------2</link>
            <guid isPermaLink="false">https://medium.com/p/7cf8ff864908</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[firebasecloudmessaging]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Christian Oluwawibe]]></dc:creator>
            <pubDate>Mon, 26 Feb 2024 12:32:11 GMT</pubDate>
            <atom:updated>2024-02-26T12:45:02.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fmsW9ZaMJFbjflsPl0nOew.png" /></figure><p>I n this article, I will show you how easy it is to migrate from Legacy FCM to HTTP v1. The goal of this article is to communicate between server and FCM, addressing device group management and sending messages.</p><p>Sending messages using the legacy APIs was deprecated on <strong>June 20, 2023</strong> and will be removed finally in <strong>June 2024.</strong></p><p>According to <a href="https://firebase.google.com/docs/cloud-messaging/migrate-v1">Firebase</a>, in addition to ongoing support and new features, the following are some of the advantages of the v1 API over the legacy API:</p><ul><li><strong>Better security via access tokens:</strong> The HTTP v1 API uses short-lived access tokens according to the OAuth2 security model. In the event that an access token becomes public, it can only be maliciously used for an hour or so before it expires. Refresh tokens are not transmitted as often as the security keys used in the legacy API, so they are much less likely to be captured.</li><li><strong>More efficient customization of messages across platforms:</strong> For the message body, the HTTP v1 API has common keys that go to all targeted instances, plus platform-specific keys that let you customize the message across platforms. This allows you to create “overrides” that send slightly different payloads to different client platforms in a single message.</li><li><strong>More extendable and future-proof for new client platform versions:</strong> The HTTP v1 API fully supports messaging options available on Apple platforms, Android and Web. Since each platform has its own defined block in the JSON payload, FCM can extend the API to new versions and new platforms as needed.</li></ul><p><em>It is important to note that you must have an active </em><a href="https://console.firebase.google.com/"><em>Firebase account</em></a><em> as well as a </em><a href="https://console.firebase.google.com/project/_/settings/serviceaccounts/adminsdk?_gl=1*ass1pq*_ga*MjA3NjU5ODc4MS4xNjUwMDMwMDg1*_ga_CW55HF8NVT*MTcwODk0MzUwMS4xMy4xLjE3MDg5NDM2MjAuNjAuMC4w"><em>Google service account</em></a><em>.<br>Code samples are written in C#.</em></p><p><strong>Let’s get started.</strong></p><h3>Step I</h3><p>First, we need to log in to our account in <a href="https://console.firebase.google.com/">Firebase Console</a> and in the <em>Project settings</em> go to the <em>Service Accounts</em> tab. After selecting the <em>Generate New Private Key</em> action, we will get a JSON file with the necessary data.</p><pre>{<br>  &quot;type&quot;: &quot;service_account&quot;,<br>  &quot;project_id&quot;: &quot;YOUR_PROJECT_ID&quot;,<br>  &quot;private_key_id&quot;: &quot;YOUR_PRIVATE_KEY&quot;,<br>  &quot;private_key&quot;: &quot;-----BEGIN PRIVATE KEY-----\\n-----END PRIVATE KEY-----\n&quot;,<br>  &quot;client_email&quot;: &quot;name@project_id.iam.gserviceaccount.com&quot;,<br>  &quot;client_id&quot;: &quot;YOUR_CLIENT_ID&quot;,<br>  &quot;auth_uri&quot;: &quot;https://accounts.google.com/o/oauth2/auth&quot;,<br>  &quot;token_uri&quot;: &quot;https://oauth2.googleapis.com/token&quot;,<br>  &quot;auth_provider_x509_cert_url&quot;: &quot;https://www.googleapis.com/oauth2/v1/certs&quot;,<br>  &quot;client_x509_cert_url&quot;: &quot;https://www.googleapis.com/robot/v1/metadata/x509/name%40project_id.iam.gserviceaccount.com&quot;,<br>  &quot;universe_domain&quot;: &quot;googleapis.com&quot;<br>}</pre><p><em>Please note that your account must have Owner or Editor permission.</em></p><h3>Step II</h3><p>Activate <a href="https://console.developers.google.com/apis/library/fcm.googleapis.com">Firebase Cloud Messaging API</a> to be able to use the new version of FCM.</p><h3>Step III</h3><p>Using the results obtained in <em>Step I</em>, we can prepare an authorization module that will help us to generate the necessary Access Token.</p><pre>private async Task&lt;string?&gt; getAuthToken()<br>{<br>    var scopes = new string[] { &quot;https://www.googleapis.com/auth/firebase.messaging&quot; };<br>    var path = Path.Combine(Directory.GetCurrentDirectory(), &quot;service_file_name.json&quot;);<br>    var cred = GoogleCredential.FromFile(path).CreateScoped(scopes);<br>    var token = await cred.UnderlyingCredential.GetAccessTokenForRequestAsync();<br>    return token;<br>}</pre><p><em>Kindly note that you need to install the </em><a href="https://github.com/Firebase/firebase-admin-dotnet"><em>FirebaseAdmin nuget</em></a><em> package to have access to the GoogleCredential class.</em></p><p>The Path.Combine(Directory.GetCurrentDirectory(), “service_file_name.json”); line is used to load the service file downloaded from step 1. This also assumes that the json file is stored in the project directory.</p><p>If we have everything setup correctly, we should have an access token. This token is what we’ll use for authorizing our subsequent requests.</p><h3>Step IV</h3><p>This step is divided into two(2), we’ll treat device group management first, and send push notification afterwards using the FCM HTTP v1 for both.</p><h4>Managing Device Groups</h4><p>The following are the keys for creating device groups and adding and removing members.</p><ul><li><strong>operation</strong>(required, string): The operation to run. Valid values are create, add, and remove.</li><li><strong>notification_key_name</strong>(required, string): The user-defined name of the device group to create or modify.</li><li><strong>notification_key</strong>(required (except for create operation), string)): Unique identifier of the device group. This value is returned in the response for a successful create operation, and is required for all subsequent operations on the device group.</li><li><strong>registration_ids</strong>(required, array of strings): The device tokens to add or remove. If you remove all existing registration tokens from a device group, FCM deletes the device group.</li></ul><h4>Next…</h4><p>The next thing to do is to create a generic method that sends request to the API. This method will be called when creating device groups or adding and removing device from group.</p><pre>private (bool, T) SendRequest&lt;T&gt;(string url, object requestBody = null, Method method = Method.POST)<br>{<br>    ServicePointManager.Expect100Continue = true;<br>    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;<br><br>    RestClient client = new(url);<br>    var request = new RestRequest(method);<br>    var token = getAuthToken().Result;<br>    request.AddHeader(&quot;Content-Type&quot;, &quot;application/json&quot;);<br>    request.AddHeader(&quot;Authorization&quot;, $&quot;Bearer {token}&quot;);<br>    request.AddHeader(&quot;access_token_auth&quot;, &quot;true&quot;);<br>    request.AddHeader(&quot;project_id&quot;, &quot;SENDER_ID&quot;);<br>    if (requestBody != null)<br>    {<br>        request.AddJsonBody(JsonConvert.SerializeObject(requestBody));<br>    }<br>    IRestResponse iResponse = client.Execute(request);<br><br>    if (iResponse.StatusCode != HttpStatusCode.OK)<br>    {<br>        return (false, default(T));<br>    }<br>    else<br>    {<br>        try<br>        {<br>            return (true, JsonConvert.DeserializeObject&lt;T&gt;(iResponse.Content));<br>        }<br>        catch (Exception)<br>        {<br>            return (false, default(T));<br>        }<br>    }<br>}</pre><p>The getAuthToken() method is the one we declared in our <em>Step III.</em></p><p>To create a device group, use the method below;</p><pre>public NotificationKeyResponse createGroup(string groupId, List&lt;string&gt; devices)<br>{<br>    var obj = new<br>    {<br>        operation = &quot;create&quot;,<br>        notification_key_name = groupId,<br>        registration_ids = devices.ToArray()<br>    };<br>    var baseUrl = &quot;https://fcm.googleapis.com/fcm/notification&quot;;<br>    var resp = SendRequest&lt;NotificationKeyResponse&gt;(baseUrl, obj);<br>    return resp.Item2;<br>}</pre><p>The operation performed in the snippet above is a create operation. And the parameters there are the keys already explained above. The result of the operation is a notification_key which must be saved, as it will be use afterwards to manage the group.</p><p>To add device(s) to group, use the method below;</p><pre>public NotificationKeyResponse addToGroup(string groupId, string notification_key, List&lt;string&gt; devices)<br>{<br>    var obj = new<br>    {<br>        operation = &quot;add&quot;,<br>        notification_key_name = groupId,<br>        notification_key = notification_key,<br>        registration_ids = devices.ToArray()<br>    };<br>    var baseUrl = &quot;https://fcm.googleapis.com/fcm/notification&quot;;<br>    var resp = SendRequest&lt;NotificationKeyResponse&gt;(baseUrl, obj);<br>    return resp.Item2;<br>}</pre><p>To remove device(s) from group, use the method below;</p><pre>public NotificationKeyResponse removeFromGroup(string groupId, string notification_key, List&lt;string&gt; devices)<br>{<br>    var obj = new<br>    {<br>        operation = &quot;remove&quot;,<br>        notification_key_name = groupId,<br>        notification_key = notification_key,<br>        registration_ids = devices.ToArray()<br>    };<br>    var baseUrl = &quot;https://fcm.googleapis.com/fcm/notification&quot;;<br>    var resp = SendRequest&lt;NotificationKeyResponse&gt;(baseUrl, obj);<br>    return resp.Item2;<br>}</pre><p>To retrieve a notification_key by groupId/notification_key_name, use the method below;</p><pre>public NotificationKeyResponse getNotificationKey(string groupId)<br>{<br>    var baseUrl = &quot;https://fcm.googleapis.com/fcm/notification&quot;;<br>    var resp = SendRequest&lt;NotificationKeyResponse&gt;($&quot;{baseUrl}?notification_key_name={groupId}&quot;, null, Method.GET);<br>    return resp.Item2;<br>}</pre><h4>Sending Message to Group or a Single Device</h4><p>In this part, there’s not much to do as we’ll reuse our SendRequest() method already created. The only difference will be the payload we’re sending and the URL we’re calling.</p><p>We have been sending notifications with https://fcm.googleapis.com/fcm/send. Now with the new v1 API, the URL is changed to https://fcm.googleapis.com/v1/projects/PROJECT_ID/messages:send where we have to insert a project ID (you can also get <em>PROJECT_ID</em> from the service account file from the <em>Step I</em>).</p><pre>public NotificationMessageResponse sendMessageToGroup(string notification_key, object notification, object data)<br>{<br>    var requestObj = new<br>    {<br>        token = notification_key, //to<br>        data = data,<br>        notification = notification,<br>        apns = new<br>        {<br>            payload = new<br>            {<br>                aps = new<br>                {<br>                    alert = notification,<br>                    sound = &quot;default&quot;,<br>                    badge = 1,<br>                    data<br>                }<br>            }<br>        }<br>    };<br>    var baseUrl = &quot;https://fcm.googleapis.com/v1/projects/{PROJECT_ID}/messages:send&quot;;<br>    var resp = SendRequest&lt;NotificationMessageResponse&gt;(baseUrl, requestObj);<br>    return resp.Item2;<br>}</pre><p>The definition for the notification and data payload can be found <a href="https://firebase.google.com/docs/cloud-messaging/concept-options"><em>here</em></a>. If we are not sending to group but a single device, all we need to change is the token field in our requestObj. Instead of the notification_key, we use the device_token.</p><h3>Summary</h3><p>I do hope the solutions provided in this article is worth your time and helps you navigate the migration. I’d love your suggestions and comments.</p><p>You can find me on <a href="https://github.com/softwareolatomiwa">GitHub</a> and <a href="https://twitter.com/dev_tomiwa">Twitter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7cf8ff864908" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>