Migração do Firebase Cloud Messaging do Google usando os SDKs do Azure

O Google vai preterir a API herdada do FCM (Firebase Cloud Messaging) até julho de 2024. Em 1º de março de 2024, você poderá começar a migrar do protocolo HTTP herdado para o FCM v1. É necessário concluir a migração até junho de 2024. Esta seção descreve as etapas para migrar do FCM herdado para o FCM v1 usando os SDKs do Azure.

Importante

A partir de junho de 2024, as APIs legadas do FCM não terão mais suporte e serão descontinuadas. Para evitar qualquer interrupção no seu serviço de notificação push, você deve migrar para o protocolo FCM v1 o mais rápido possível.

Pré-requisitos

  • Verifique se a API de Mensagens na Nuvem do Firebase (V1) está habilitada na configuração do projeto do Firebase no Cloud Messaging.
  • Verifique se as credenciais de FCM estão atualizadas. Siga a etapa 1 no guia da API REST.

SDK do Android

  1. Atualize a versão do SDK para 2.0.0 no arquivo build.gradle do aplicativo. Por exemplo:

    // This is not a complete build.gradle file; it only highlights the portions you need to update. 
    
    dependencies { 
        // Ensure the following line is updated in your app/library's "dependencies" section.
    implementation 'com.microsoft.azure:notification-hubs-android-sdk:2.0.0' 
        // optionally, use the fcm optimized SKU instead: 
        // implementation 'com.microsoft.azure:notification-hubs-android-sdk-fcm:2.0.0' 
    }
    
  2. Atualize o modelo de payload. Se não estiver usando modelos, ignore esta etapa.

    Consulte o Referência REST do FCM para a estrutura de payload do FCM v1. Para obter informações sobre como migrar do payload herdado do FCM para o payload do FCM v1, consulte Atualizar o payload das solicitações de envio.

    Por exemplo, se estiver usando registros:

    NotificationHub hub = new NotificationHub(BuildConfig.hubName, BuildConfig.hubListenConnectionString, context);
    String template = "{\"message\":{\"android\":{\"data\":{\"message\":\"{'Notification Hub test notification: ' + $(myTextProp)}\"}}}}";
    hub.registerTemplate(token, "template-name", template);
    

    Se você estiver usando instalações:

    InstallationTemplate testTemplate = new InstallationTemplate(); 
    testTemplate.setBody("{\"message\":{\"android\":{\"data\":{\"message\":\"{'Notification Hub test notification: ' + $(myTextProp)}\"}}}}");  
    NotificationHub.setTemplate("testTemplate", testTemplate);
    

SDKs do servidor (plano de dados)

  1. Atualize o pacote SDK para a versão mais recente (4.2.0):

    Nome do GitHub do SDK Nome do pacote do SDK Versão
    azure-notificationhubs-dotnet Microsoft.Azure.NotificationHubs 4.2.0
    azure-notificationhubs-java-backend com.windowsazure.Notification-Hubs-java-sdk 1.1.0
    azure-sdk-for-js @azure/notification-hubs 1.1.0

    Por exemplo, no arquivo .csproj:

    <PackageReference Include="Microsoft.Azure.NotificationHubs" Version="4.2.0" />
    
  2. Adicione FcmV1Credential ao hub de notificações. Essa etapa é uma configuração que só precisa ser realizada uma vez. A menos que você tenha muitos hubs e queira automatizar esta etapa, é possível usar a API REST ou o portal do Azure para adicionar as credenciais do FCM v1:

    // Create new notification hub with FCM v1 credentials
    var hub = new NotificationHubDescription("hubname"); 
    hub.FcmV1Credential = new FcmV1Credential("private-key", "project-id", "client-email"); 
    hub = await namespaceManager.CreateNotificationHubAsync(hub); 
    
    // Update existing notification hub with FCM v1 credentials 
    var hub = await namespaceManager.GetNotificationHubAsync("hubname", CancellationToken.None); 
    hub.FcmV1Credential = new FcmV1Credential("private-key", "project-id", "client-email"); 
    hub = await namespaceManager.UpdateNotificationHubAsync(hub, CancellationToken.None);
    
    // Create new notification hub with FCM V1 credentials
    NamespaceManager namespaceManager = new NamespaceManager(namespaceConnectionString);
    NotificationHubDescription hub = new NotificationHubDescription("hubname");
    hub.setFcmV1Credential(new FcmV1Credential("private-key", "project-id", "client-email"));
    hub = namespaceManager.createNotificationHub(hub);
    
    // Updating existing Notification Hub with FCM V1 Credentials
    NotificationHubDescription hub = namespaceManager.getNotificationHub("hubname");
    hub.setFcmV1Credential(new FcmV1Credential("private-key", "project-id", "client-email"));
    hub = namespaceManager.updateNotificationHub(hub);
    
  3. Gerencie registros e instalações. Para registros, use FcmV1RegistrationDescription para registrar dispositivos do FCM v1. Por exemplo:

    // Create new Registration
    var deviceToken = "device-token"; 
    var tags = new HashSet<string> { "tag1", "tag2" }; 
    FcmV1RegistrationDescription registration = await hub. CreateFcmV1NativeRegistrationAsync(deviceToken, tags);
    

    Para Java, use FcmV1Registration para registrar dispositivos do FCMv1:

    // Create new registration
    NotificationHub client = new NotificationHub(connectionString, hubName);
    FcmV1Registration registration =  client.createRegistration(new FcmV1Registration("fcm-device-token"));
    

    Para JavaScript, use createFcmV1RegistrationDescription para registrar dispositivos do FCMv1:

    // Create FCM V1 registration
    const context = createClientContext(connectionString, hubName);
    const registration = createFcmV1RegistrationDescription({
      fcmV1RegistrationId: "device-token",
    });
    const registrationResponse = await createRegistration(context, registration);
    

    Para instalações, use NotificationPlatform.FcmV1 como a plataforma com Installation ou use FcmV1Installation para criar instalações do FCM v1:

    // Create new installation
    var installation = new Installation 
    { 
        InstallationId = "installation-id", 
        PushChannel = "device-token", 
        Platform = NotificationPlatform.FcmV1 
    }; 
    await hubClient.CreateOrUpdateInstallationAsync(installation); 
    
    // Alternatively, you can use the FcmV1Installation class directly 
    var installation = new FcmV1Installation("installation-id", "device-token"); 
    await hubClient.CreateOrUpdateInstallationAsync(installation);
    

    Para Java, use NotificationPlatform.FcmV1 como a plataforma:

    // Create new installation
    NotificationHub client = new NotificationHub(connectionString, hubName);
    client.createOrUpdateInstallation(new Installation("installation-id", NotificationPlatform.FcmV1, "device-token"));
    

    Para JavaScript, use createFcmV1Installation para criar uma instalação do FCMv1:

    // Create FCM V1 installation
    const context = createClientContext(connectionString, hubName);
    const installation = createFcmV1Installation({
      installationId: "installation-id",
      pushChannel: "device-token",
    });
    const result = await createOrUpdateInstallation(context, installation);
    

    Observe também as seguintes considerações:

    • Se o registro do dispositivo acontecer no aplicativo cliente, atualize o aplicativo cliente primeiro para se registrar na plataforma do FCMv1.
    • Se o registro do dispositivo acontecer no servidor, você poderá buscar todos os registros/instalações e atualizá-los para FCMv1 no servidor.
  4. Envie a notificação. para o FCMv1. Use FcmV1Notification ao enviar notificações direcionadas ao FCMv1. Por exemplo:

    // Send FCM v1 notification
    var jsonBody = "{\"message\":{\"android\":{\"data\":{\"message\":\"Notification Hub test notification\"}}}}"; 
    var n = new FcmV1Notification(jsonBody); 
    NotificationOutcome outcome = await hub.SendNotificationAsync(n, "tag");
    
    // Send FCM V1 Notification 
    NotificationHub client = new NotificationHub(connectionString, hubName);
    NotificationOutcome outcome = client.sendNotification(new FcmV1Notification("{\"message\":{\"android\":{\"data\":{\"message\":\"Notification Hub test notification\"}}}}"));
    
    // Send FCM V1 Notification
    const context = createClientContext(connectionString, hubName);
    const messageBody = `{
      "message": {
          "android": {
              "data": {
                  "message": "Notification Hub test notification"
              }
          }
      }
    }`;
    
    const notification = createFcmV1Notification({
      body: messageBody,
    });
    const result = await sendNotification(context, notification);
    

Próximas etapas

Migração do Firebase Cloud Messaging usando a API REST