Skip to content

Notificações por push

Notificações por push permitem que você envie notificações do seu app quando eventos importantes ocorrerem. Você pode enviar uma notificação por push quando tiver novas mensagens instantâneas para entregar, alertas de notícias de última hora para enviar ou o episódio mais recente do programa de TV favorito do seu usuário pronto para ele baixar para visualização offline. Eles também são mais eficientes do que a busca em segundo plano, pois seu aplicativo só é iniciado quando necessário.

Pré-requisitos

Antes de poder usar esse recurso, você precisará integrar o Android Braze SDK.

Recursos integrados

Os seguintes recursos estão integrados ao SDK Android do Braze. Para usar quaisquer outros recursos de notificação por push, você precisará configurar notificações por push para seu app.

Sobre o ciclo de vida da notificação por push

O fluxograma a seguir mostra como o Braze lida com o ciclo de vida da notificação por push, como solicitações de permissão, geração de tokens e entrega de mensagens.

---
config:
  theme: neutral
---
flowchart TD

%% Permission flow
subgraph Permission[Push Permissions]
    B{Android version of the device?}
    B -->|Android 13+| C["requestPushPermissionPrompt() called"]
    B -->|Android 12 and earlier| D[No permissions required]
    
    %% Connect Android 12 path to Braze state
    D --> H3[Braze: user subscription state]
    H3 --> J3[Defaults to 'subscribed' when user profile created]
    
    C --> E{Did the user grant push permission?}
    E -->|Yes| F[POST_NOTIFICATIONS permission granted]
    E -->|No| G[POST_NOTIFICATIONS permission denied]
    
    %% Braze subscription state updates
    F --> H1[Braze: user subscription state]
    G --> H2[Braze: user subscription state]
    
    H1 --> I1{Automatically opt in after permission granted?}
    I1 -->|true| J1[Set to 'opted-in']
    I1 -->|false| J2[Remains 'subscribed']
    
    H2 --> K1[Remains 'subscribed'<br/>or 'unsubscribed']
    
    %% Subscription state legend
    subgraph BrazeStates[Braze subscription states]
        L1['Subscribed' - default state<br/>when user profile created]
        L2['Opted-in' - user explicitly<br/>wants push notifications]
        L3['Unsubscribed' - user explicitly<br/>opted out of push]
    end
    
    %% Note about user-level states
    note1[Note: These states are user-level<br/>and apply across all devices for the user]
    
    %% Connect states to legend
    J1 -.-> L2
    J2 -.-> L1
    J3 -.-> L1
    K1 -.-> L3
    note1 -.-> BrazeStates
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass
---
config:
  theme: neutral
---
flowchart TD

%% Token generation flow
subgraph Token[Token Generation]
    H["Braze SDK initialized"] --> Q{Is FCM auto-registration enabled?}
    Q -->|Yes| L{Is required configuration present?}
    Q -->|No| M[No FCM token generated]
    L -->|Yes| I[Generate FCM token]
    L -->|No| M
    I --> K[Register token with Braze]

    %% Configuration requirements
    subgraph Config[Required configuration]
        N['google-services.json' file is present]
        O['com.google.firebase:firebase-messaging' in gradle]
        P['com.google.gms.google-services' plugin in gradle]
    end

    %% Connect config to check
    N -.-> L
    O -.-> L
    P -.-> L
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass
---
config:
  theme: neutral
  fontSize: 10
---
flowchart TD

subgraph Display[Push Display]
    %% Push delivery flow
    W[Push sent to FCM servers] --> X{Did FCM receive push?}
    X -->|App is terminated| Y[FCM cannot deliver push to the app]
    X -->|Delivery conditions met| X1[App receives push from FCM]
    X1 --> X2[Braze SDK receives push]
    X2 --> R[Push type?]

    %% Push Display Flow
    R -->|Standard push| S{Is push permission required?}
    R -->|Silent push| T[Braze SDK processes silent push]
    S -->|Yes| S1{Did the user grant push permission?}
    S -->|No| V[Notification is shown to the user]
    S1 -->|Yes| V
    S1 -->|No| U[Notification is not shown to the user]
end

%% Styling
classDef permissionClass fill:#e3f2fd,stroke:#1565c0,stroke-width:2px
classDef tokenClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px
classDef sdkClass fill:#fff3e0,stroke:#e65100,stroke-width:2px
classDef configClass fill:#f3e5f5,stroke:#7b1fa2,stroke-width:2px
classDef displayClass fill:#ffebee,stroke:#c62828,stroke-width:2px
classDef deliveryClass fill:#fce4ec,stroke:#c2185b,stroke-width:2px
classDef brazeClass fill:#e8f5e9,stroke:#2e7d32,stroke-width:3px

class A,B,C,E,F,G permissionClass
class H,I tokenClass
class J,K sdkClass
class N,O,P configClass
class R,S,S1,T,U,V displayClass
class W,X,X1,X2,Y,Z deliveryClass
class H1,H2,H3,I1,J1,J2,J3,K1,L1,L2,L3,note1 brazeClass

Configurando notificações por push

Limites de taxa

A API do Firebase Cloud Messaging (FCM) tem um limite de frequência padrão de 600.000 solicitações por minuto. Se você atingir esse limite, o Braze tentará automaticamente outra vez em alguns minutos. Para solicitar um aumento, entre em contato com o suporte do Firebase.

Etapa 1: Adicione o Firebase ao seu projeto

Primeiro, adicione o Firebase ao seu projeto Android. Para obter instruções passo a passo, consulte o guia de configuração do Firebase do Google.

Etapa 2: Adicione o Cloud Messaging às suas dependências

Em seguida, adicione a biblioteca do Cloud Messaging às dependências de seu projeto. Em seu projeto Android, abra build.gradle e, em seguida, adicione a seguinte linha ao bloco dependencies.

1
implementation "google.firebase:firebase-messaging:+"

Suas dependências devem ser semelhantes às seguintes:

1
2
3
4
dependencies {
  implementation project(':android-sdk-ui')
  implementation "com.google.firebase:firebase-messaging:+"
}

Etapa 3: Ativar a API de envio de mensagens do Firebase Cloud

No Google Cloud, selecione o projeto que seu app Android está usando e ative a API do Firebase Cloud Messaging.

API do Firebase Cloud Messaging ativada

Etapa 4: Crie uma conta de serviço

Em seguida, crie uma nova conta de serviço, para que a Braze possa fazer chamadas de API autorizadas ao registrar tokens FCM. No Google Cloud, acesse Contas de Serviço, depois escolha seu projeto. Na página Contas de serviço, selecione Criar conta de serviço.

Página inicial da conta de serviço de um projeto com a opção "Criar conta de serviço" destacada.

Insira um nome de conta de serviço, ID e descrição, em seguida selecione Criar e continuar.

O formulário para "Detalhes da conta de serviço".

No campo Função, localize e selecione Firebase Cloud Messaging API Admin na lista de funções. Para obter acesso mais restritivo, crie uma função personalizada com a permissão cloudmessaging.messages.create e, em vez disso, escolha-a na lista. Quando terminar, selecione Concluído.

O formulário para "Conceder acesso a esta conta de serviço ao projeto" com "Administrador da API do Firebase Cloud Messaging" selecionado como função.

Etapa 5: Gere credenciais JSON

Em seguida, gere credenciais JSON para sua conta de serviço FCM. No Google Cloud IAM & Admin, acesse Service Accounts, depois escolha seu projeto. Localize a conta de serviço FCM que você criou anteriormente e selecione Actions > Manage Keys.

A página inicial da conta de serviço do projeto com o menu "Actions" (Ações) aberto.

Selecione Adicionar chave > Criar nova chave.

A conta de serviço selecionada com o menu "Add Key" aberto.

Escolha JSON, depois selecione Criar. Se você criou sua conta de serviço usando um ID de projeto do Google Cloud diferente do ID de projeto do FCM, será necessário atualizar manualmente o valor atribuído ao project_id no seu arquivo JSON.

Lembre-se de onde baixou a chave - você precisará dela na próxima etapa.

O formulário para criar uma chave privada com "JSON" selecionado.

Etapa 6: Faça upload de suas credenciais JSON na Braze

Em seguida, faça upload de suas credenciais JSON em seu dashboard da Braze. Na Braze, selecione Configurações > Configurações do app.

O menu "Settings" (Configurações) é aberto no Braze com "App Settings" (Configurações do app) destacado.

Nas configurações de notificação por push do seu app para Android, escolha Firebase, selecione Upload JSON File e faça upload das credenciais geradas anteriormente. Quando terminar, selecione Salvar.

O formulário para "Push Notification Settings" (Configurações de notificação por push) com "Firebase" selecionado como o provedor de push.

Etapa 7: Configure o registro automático de tokens

Quando um de seus usuários aceita notificações por push, seu app precisa gerar um token FCM no dispositivo dele antes de poder enviar notificações por push. Com o SDK do Braze, é possível ativar o registro automático do token FCM para cada dispositivo do usuário nos arquivos de configuração do Braze do seu projeto.

Primeiro, acesse o Console Firebase, abra seu projeto e selecione Settings > Project settings (Configurações .> Configurações do projeto).

O projeto Firebase com o menu "Settings" (Configurações) aberto.

Selecione Envio de mensagens na nuvem e, em seguida, em Firebase Cloud Messaging API (V1), copie o número no campo Sender ID (ID do remetente ).

A página "Cloud Messaging" do projeto Firebase com o "Sender ID" (ID do remetente) destacado.

Em seguida, abra seu projeto do Android Studio e use seu Firebase Sender ID para ativar o registro automático do token FCM em braze.xml ou BrazeConfig.

Para configurar o registro automático do token FCM, adicione as seguintes linhas ao arquivo braze.xml:

1
2
<bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

Substitua FIREBASE_SENDER_ID pelo valor que você copiou das configurações do projeto Firebase. braze.xml deve ser semelhante ao seguinte:

1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <string translatable="false" name="com_braze_api_key">12345ABC-6789-DEFG-0123-HIJK456789LM</string>
  <bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">603679405392</string>
</resources>

Para configurar o registro automático do token FCM, adicione as seguintes linhas a BrazeConfig:

1
2
.setIsFirebaseCloudMessagingRegistrationEnabled(true)
.setFirebaseCloudMessagingSenderIdKey("FIREBASE_SENDER_ID")
1
2
.setIsFirebaseCloudMessagingRegistrationEnabled(true)
.setFirebaseCloudMessagingSenderIdKey("FIREBASE_SENDER_ID")

Substitua FIREBASE_SENDER_ID pelo valor que você copiou das configurações do projeto Firebase. BrazeConfig deve ser semelhante ao seguinte:

1
2
3
4
5
6
7
8
9
10
BrazeConfig brazeConfig = new BrazeConfig.Builder()
  .setApiKey("12345ABC-6789-DEFG-0123-HIJK456789LM")
  .setCustomEndpoint("sdk.iad-01.braze.com")
  .setSessionTimeout(60)
  .setHandlePushDeepLinksAutomatically(true)
  .setGreatNetworkDataFlushInterval(10)
  .setIsFirebaseCloudMessagingRegistrationEnabled(true)
  .setFirebaseCloudMessagingSenderIdKey("603679405392")
  .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
6
7
8
9
10
val brazeConfig = BrazeConfig.Builder()
  .setApiKey("12345ABC-6789-DEFG-0123-HIJK456789LM")
  .setCustomEndpoint("sdk.iad-01.braze.com")
  .setSessionTimeout(60)
  .setHandlePushDeepLinksAutomatically(true)
  .setGreatNetworkDataFlushInterval(10)
  .setIsFirebaseCloudMessagingRegistrationEnabled(true)
  .setFirebaseCloudMessagingSenderIdKey("603679405392")
  .build()
Braze.configure(this, brazeConfig)

Etapa 8: Remover solicitações automáticas em sua classe de aplicativo

Para evitar que a Braze dispare solicitações de rede desnecessárias sempre que você enviar notificações por push silenciosas, remova todas as solicitações de rede automáticas configuradas no método onCreate() de sua classe Application. Para saber mais, consulte Android Developer Reference: Aplicativo.

Exibindo notificações

Etapa 1: Registre o serviço de envio de mensagens do Braze Firebase

Você pode criar um novo, existente ou um Serviço de Mensagens do Firebase não-Braze. Escolha o que melhor atende às suas necessidades específicas.

A Braze oferece um serviço para lidar com recebimento de push e intenções de abertura. Nossa classe BrazeFirebaseMessagingService precisará ser registrada em seu site AndroidManifest.xml:

1
2
3
4
5
6
<service android:name="com.braze.push.BrazeFirebaseMessagingService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.google.firebase.MESSAGING_EVENT" />
  </intent-filter>
</service>

Nosso código de notificação também usa o site BrazeFirebaseMessagingService para lidar com o rastreamento de ações de abertura e cliques. Esse serviço deve ser registrado no site AndroidManifest.xml para funcionar corretamente. Além disso, lembre-se de que o Braze prefixa as notificações de nosso sistema com uma chave exclusiva, de modo que só renderizamos as notificações enviadas de nossos sistemas. Você pode registrar serviços adicionais separadamente para processar as notificações enviadas por outros serviços da FCM. Veja AndroidManifest.xml no app de exemplo de push do Firebase.

Se você já tiver um serviço de envio de mensagens do Firebase registrado, poderá passar objetos RemoteMessage para o Braze via BrazeFirebaseMessagingService.handleBrazeRemoteMessage(). Esse método só exibirá uma notificação se o objeto RemoteMessage for originário do Braze e, caso contrário, será ignorado com segurança.

1
2
3
4
5
6
7
8
9
10
11
12
13
public class MyFirebaseMessagingService extends FirebaseMessagingService {
  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if (BrazeFirebaseMessagingService.handleBrazeRemoteMessage(this, remoteMessage)) {
      // This Remote Message originated from Braze and a push notification was displayed.
      // No further action is needed.
    } else {
      // This Remote Message did not originate from Braze.
      // No action was taken and you can safely pass this Remote Message to other handlers.
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
class MyFirebaseMessagingService : FirebaseMessagingService() {
  override fun onMessageReceived(remoteMessage: RemoteMessage?) {
    super.onMessageReceived(remoteMessage)
    if (BrazeFirebaseMessagingService.handleBrazeRemoteMessage(this, remoteMessage)) {
      // This Remote Message originated from Braze and a push notification was displayed.
      // No further action is needed.
    } else {
      // This Remote Message did not originate from Braze.
      // No action was taken and you can safely pass this Remote Message to other handlers.
    }
  }
}

Se você tiver outro Firebase Messaging Service que também gostaria de usar, especifique um Firebase Messaging Service de fallback para chamar se o aplicativo receber um push que não seja da Braze.

Em braze.xml, especifique:

1
2
<bool name="com_braze_fallback_firebase_cloud_messaging_service_enabled">true</bool>
<string name="com_braze_fallback_firebase_cloud_messaging_service_classpath">com.company.OurFirebaseMessagingService</string>

ou definido por meio da configuração de tempo de execução:

1
2
3
4
5
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setFallbackFirebaseMessagingServiceEnabled(true)
        .setFallbackFirebaseMessagingServiceClasspath("com.company.OurFirebaseMessagingService")
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
val brazeConfig = BrazeConfig.Builder()
        .setFallbackFirebaseMessagingServiceEnabled(true)
        .setFallbackFirebaseMessagingServiceClasspath("com.company.OurFirebaseMessagingService")
        .build()
Braze.configure(this, brazeConfig)

Etapa 2: Adequar os ícones pequenos às diretrizes de design

Para obter informações gerais sobre os ícones de notificação do Android, visite a visão geral de Notificações.

A partir do Android N, você deve atualizar ou remover pequenos ativos de ícones de notificação que envolvam cores. O sistema Android (não o SDK do Braze) ignora todos os canais não alfa e de transparência nos ícones de ação e no ícone pequeno de notificação. Em outras palavras, o Android converterá todas as partes do seu pequeno ícone de notificação em monocromático, exceto as regiões transparentes.

Para criar um ícone pequeno de notificação que seja exibido corretamente:

  • Remova todas as cores da imagem, exceto o branco.
  • Todas as outras regiões não brancas do ativo devem ser transparentes.

Os ícones grandes e pequenos a seguir são exemplos de ícones projetados adequadamente:

Um ícone pequeno que aparece no canto inferior de um ícone grande ao lado de uma mensagem que diz "Ei, estou a caminho do bar, mas..."

Etapa 3: Configurar ícones de notificação

Especificação de ícones em braze.xml

A Braze permite que você configure seus ícones de notificação especificando recursos desenháveis em braze.xml:

1
2
<drawable name="com_braze_push_small_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>
<drawable name="com_braze_push_large_notification_icon">REPLACE_WITH_YOUR_ICON</drawable>

É necessário definir um pequeno ícone de notificação. Se você não definir um, o Braze usará, por padrão, o ícone do aplicativo como o pequeno ícone de notificação, o que pode não parecer ideal.

A definição de um ícone de notificação grande é opcional, mas recomendada.

Especificação da cor de destaque do ícone

A cor de destaque do ícone de notificação pode ser substituída em seu site braze.xml. Se a cor não for especificada, a cor padrão será o mesmo cinza que o Lollipop usa para as notificações do sistema.

1
<integer name="com_braze_default_notification_accent_color">0xFFf33e3e</integer>

Opcionalmente, você também pode usar uma referência de cor:

1
<color name="com_braze_default_notification_accent_color">@color/my_color_here</color>

Etapa 4: Adicionar deep linking

Ativando a abertura automática de deep linking

Para permitir que a Braze abra automaticamente seu app e quaisquer deep links quando uma notificação por push for clicada, defina com_braze_handle_push_deep_links_automatically como true em seu braze.xml:

1
<bool name="com_braze_handle_push_deep_links_automatically">true</bool>

Esse sinalizador também pode ser definido por meio da configuração do tempo de execução:

1
2
3
4
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setHandlePushDeepLinksAutomatically(true)
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
val brazeConfig = BrazeConfig.Builder()
        .setHandlePushDeepLinksAutomatically(true)
        .build()
Braze.configure(this, brazeConfig)

Se quiser personalizar o tratamento de deep linkings, você precisará criar um retorno de chamada de push que escute as intenções de push recebidas e abertas da Braze. Para saber mais, veja Usando um retorno de chamada para eventos de push.

Siga as instruções encontradas na documentação do desenvolvedor Android sobre deep linking se você ainda não adicionou deep links ao seu app. Para saber mais sobre o que são deep linkings, consulte nosso artigo de perguntas frequentes.

O dashboard do Braze oferece suporte à configuração de deep links ou URLs da Web em campanhas de notificações por push e canvas que serão abertos quando a notificação for clicada.

A configuração "Comportamento ao clicar" no painel do Braze com "Deep Link Into Application" selecionado no menu suspenso.

Personalização do comportamento da pilha traseira

O SDK do Android, por padrão, colocará a atividade principal do iniciador do seu app host na pilha traseira ao seguir push deep links. A Braze permite definir uma atividade personalizada para ser aberta na pilha traseira no lugar da atividade principal do iniciador ou desativar a pilha traseira completamente.

Por exemplo, para definir uma atividade chamada YourMainActivity como a atividade de back stack usando a configuração de tempo de execução:

1
2
3
4
5
BrazeConfig brazeConfig = new BrazeConfig.Builder()
        .setPushDeepLinkBackStackActivityEnabled(true)
        .setPushDeepLinkBackStackActivityClass(YourMainActivity.class)
        .build();
Braze.configure(this, brazeConfig);
1
2
3
4
5
val brazeConfig = BrazeConfig.Builder()
        .setPushDeepLinkBackStackActivityEnabled(true)
        .setPushDeepLinkBackStackActivityClass(YourMainActivity.class)
        .build()
Braze.configure(this, brazeConfig)

Veja a configuração equivalente para seu braze.xml. Note que o nome da classe deve ser o mesmo retornado por Class.forName().

1
2
<bool name="com_braze_push_deep_link_back_stack_activity_enabled">true</bool>
<string name="com_braze_push_deep_link_back_stack_activity_class_name">your.package.name.YourMainActivity</string>

Etapa 5: Definir canais de notificação

O SDK do Braze para Android é compatível com os canais de notificação do Android. Se uma notificação do Braze não contiver o ID de um canal de notificação ou se uma notificação do Braze contiver um ID de canal inválido, o Braze exibirá a notificação com o canal de notificação padrão definido no SDK. Os usuários do Braze usam os canais de notificação do Android na plataforma para agrupar notificações.

Para definir o nome do canal de notificação padrão do Braze voltado para o usuário, use BrazeConfig.setDefaultNotificationChannelName().

Para definir a descrição voltada para o usuário do canal de notificação padrão do Braze, use BrazeConfig.setDefaultNotificationChannelDescription().

Atualize todas as campanhas da API com o parâmetro de objeto Android push para incluir o campo notification_channel. Se esse campo não for especificado, o Braze enviará a carga útil da notificação com o ID do canal fallback dashboard.

Além do canal de notificação padrão, a Braze não criará nenhum canal. Todos os outros canais devem ser definidos programaticamente pelo app host e, em seguida, inseridos no dashboard da Braze.

O nome e a descrição padrão do canal também podem ser configurados em braze.xml.

1
2
<string name="com_braze_default_notification_channel_name">Your channel name</string>
<string name="com_braze_default_notification_channel_description">Your channel description</string>

Etapa 6: Teste a exibição de notificações e a análise de dados

Tela de teste

Nesse ponto, você poderá ver as notificações enviadas pelo Braze. Para testar isso, acesse a página Campaigns (Campanhas ) em seu dashboard do Braze e crie uma campanha de notificação por push. Escolha o Android Push e crie sua mensagem. Em seguida, clique no ícone do olho no criador para obter o remetente de teste. Digite o ID do usuário ou o endereço de e-mail do usuário atual e clique em Send Test (Enviar teste). Você deverá ver o push aparecer em seu dispositivo.

A guia "Teste" de uma campanha de notificação por push no dashboard do Braze.

Para problemas relacionados ao push display, consulte nosso guia de solução de problemas.

Análise de dados de teste

Nesse ponto, você também deve ter registro de análise de dados para aberturas de notificações por push. Ao clicar na notificação quando ela chegar, as aberturas diretas na página de resultados de sua campanha deverão aumentar em 1. Confira nosso artigo sobre relatórios push para obter informações detalhadas sobre a análise de dados push.

Para problemas relacionados à análise de dados por push, consulte nosso guia de solução de problemas.

Testes a partir da linha de comando

Se quiser testar notificações por push e no aplicativo por meio da interface de linha de comando, você poderá enviar uma única notificação pelo terminal via cURL e a API de envio de mensagens. Você precisará substituir os seguintes campos pelos valores corretos para o seu caso de teste:

  • YOUR_API_KEY (Acessar Configurações > API Keys.)
  • YOUR_EXTERNAL_USER_ID (Procure um perfil na página Buscar Usuários.)
  • YOUR_KEY1 (opcional)
  • YOUR_VALUE1 (opcional)
1
2
3
4
5
6
7
8
9
10
11
12
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "android_push": {
      "title":"Test push title",
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }  
  }
}' https://rest.iad-01.braze.com/messages/send

Este exemplo usa a instância US-01. Se você não estiver nessa instância, substitua o endpoint US-01 pelo seu endpoint.

Notificações por push de conversa

A iniciativa de pessoas e conversas existe há vários anos no Android e tem como objetivo destacar pessoas e conversas na superfície do sistema do smartphone. Esta prioridade é baseada no fato de que a comunicação e a interação com outras pessoas ainda são a área funcional mais valorizada e importante para a maioria dos usuários de Android em todas as faixas demográficas.

Requisitos de uso

  • Esse tipo de notificação requer o SDK da Braze para Android v15.0.0+ e dispositivos Android 11+.
  • Dispositivos ou SDKs sem suporte voltarão a usar uma notificação por push padrão.

Este recurso está disponível apenas na API REST da Braze. Consulte o objeto push do Android para saber mais.

Erros de cota excedida do FCM

Quando seu limite para o Firebase Cloud Messaging (FCM) é excedido, o Google retorna erros de “cota excedida”. O limite padrão do FCM é de 600.000 solicitações por minuto. A Braze tenta reenviar de acordo com as melhores práticas recomendadas pelo Google. No entanto, um grande volume desses erros pode prolongar o tempo de envio por vários minutos. Para atenuar o possível impacto, a Braze enviará um alerta de que o limite de taxa está sendo excedido e informando quais as medidas que você pode tomar para evitar os erros.

Para verificar seu limite atual, acesse seu Google Cloud Console > APIs e Serviços > API do Firebase Cloud Messaging > Limites e Cotas do Sistema, ou visite a página de Cotas da API do FCM.

Melhores práticas

Recomendamos essas melhores práticas para manter esses volumes de erro baixos.

Solicitar um aumento de limite de taxa do FCM

Para solicitar um aumento de limite de taxa do FCM, você pode entrar em contato diretamente com Suporte do Firebase ou fazer o seguinte:

  1. Acesse a página de Cotas da API do FCM.
  2. Localize a cota de Solicitações enviadas por minuto.
  3. Selecione Editar Cota.
  4. Insira um novo valor e envie sua solicitação.

Solicitar limitação global de taxa via Braze

Para aplicar um limite em todo o espaço de trabalho para notificações por push do Android, entre em contato com Suporte da Braze.

Limites de taxa

As notificações por push são limitadas por taxa, então não tenha medo de enviar quantas sua aplicação precisar. O iOS e o serviço de Notificações por Push da Apple (APNs) controlarão a frequência com que são entregues, e você não terá problemas por enviar muitas. Se suas notificações por push forem limitadas, elas podem ser atrasadas até a próxima vez que o dispositivo enviar um pacote keep-alive ou receber outra notificação.

Configuração de notificações por push

Etapa 1: Faça upload de seu token de APNs

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

Etapa 2: Ativar push capabilities

No Xcode, acesse a seção Signing & Capabilities do direcionamento do app principal e adicione o recurso de notificações por push.

A seção "Signing & Capabilities" (Assinatura e recursos) em um projeto Xcode.

Etapa 3: Configurar o manuseio do push

Você pode usar o Swift SDK para automatizar o processamento de notificações remotas recebidas do Braze. Essa é a maneira mais simples de lidar com notificações por push e é o método de tratamento recomendado.

Etapa 3.1: Ativar a capacitação na propriedade push

Para ativar a integração automática de push, defina a propriedade automation da configuração push para true:

1
2
let configuration = Braze.Configuration(apiKey: "{YOUR-BRAZE-API-KEY}", endpoint: "{YOUR-BRAZE-API-ENDPOINT}")
configuration.push.automation = true
1
2
BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:@"{YOUR-BRAZE-API-KEY}" endpoint:@"{YOUR-BRAZE-API-ENDPOINT}"];
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];

Isso instrui o SDK a:

  • Registre seu aplicativo para notificação por push no sistema.
  • Solicite a autorização/permissão de notificação por push na inicialização.
  • Forneça dinamicamente implementações para os métodos delegados relacionados ao sistema de notificação por push.

Etapa 3.2: Substituir configurações individuais (opcional)

Para um controle mais granular, cada etapa de automação pode ser ativada ou desativada individualmente:

1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = true
configuration.push.automation.requestAuthorizationAtLaunch = false
1
2
3
// Enable all automations and disable the automatic notification authorization request at launch.
configuration.push.automation = [[BRZConfigurationPushAutomation alloc] initEnablingAllAutomations:YES];
configuration.push.automation.requestAuthorizationAtLaunch = NO;

Consulte Braze.Configuration.Push.Automation para todas as opções disponíveis e automation para saber mais sobre o comportamento da automação.

Etapa 3.1: Registre-se para notificações por push com APNs

Inclua o exemplo de código apropriado no método de delegado application:didFinishLaunchingWithOptions: do seu app para que os dispositivos dos seus usuários possam se registrar no APNs. Certifique-se de chamar todo o código de integração push na thread principal do seu aplicativo.

Braze também fornece categorias de push padrão para suporte ao botão de ação por push, que devem ser adicionadas manualmente ao seu código de registro de push. Consulte os botões de ação por push para obter etapas adicionais de integração.

Adicione o seguinte código ao método application:didFinishLaunchingWithOptions: do seu delegado do app.

1
2
3
4
5
6
7
8
9
10
11
application.registerForRemoteNotifications()
let center = UNUserNotificationCenter.current()
center.setNotificationCategories(Braze.Notifications.categories)
center.delegate = self
var options: UNAuthorizationOptions = [.alert, .sound, .badge]
if #available(iOS 12.0, *) {
  options = UNAuthorizationOptions(rawValue: options.rawValue | UNAuthorizationOptions.provisional.rawValue)
}
center.requestAuthorization(options: options) { granted, error in
  print("Notification authorization, granted: \(granted), error: \(String(describing: error))")
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
[application registerForRemoteNotifications];
UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter;
[center setNotificationCategories:BRZNotifications.categories];
center.delegate = self;
UNAuthorizationOptions options = UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge;
if (@available(iOS 12.0, *)) {
  options = options | UNAuthorizationOptionProvisional;
}
[center requestAuthorizationWithOptions:options
                      completionHandler:^(BOOL granted, NSError *_Nullable error) {
                        NSLog(@"Notification authorization, granted: %d, "
                              @"error: %@)",
                              granted, error);
}];

Etapa 3.2: Registre push tokens com a Braze

Depois que o registro do APNs estiver completo, passe o deviceToken resultante para a Braze para ativar as notificações por push para o usuário.

Adicione o seguinte código ao método application(_:didRegisterForRemoteNotificationsWithDeviceToken:) do seu app:

1
AppDelegate.braze?.notifications.register(deviceToken: deviceToken)

Adicione o seguinte código ao método application:didRegisterForRemoteNotificationsWithDeviceToken: do seu app:

1
[AppDelegate.braze.notifications registerDeviceToken:deviceToken];

Etapa 3.3: Ativar push handling

Em seguida, passe as notificações por push recebidas para a Braze. Esta etapa é necessária para registrar a análise de dados de push e o manuseio de links. Certifique-se de chamar todo o código de integração push na thread principal do seu aplicativo.

Manipulação padrão de push

Para ativar a capacitação do push padrão do Braze, adicione o seguinte código ao método application(_:didReceiveRemoteNotification:fetchCompletionHandler:) do seu app:

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleBackgroundNotification(
  userInfo: userInfo,
  fetchCompletionHandler: completionHandler
) {
  return
}
completionHandler(.noData)

Em seguida, adicione o seguinte ao método userNotificationCenter(_:didReceive:withCompletionHandler:) do seu app:

1
2
3
4
5
6
7
if let braze = AppDelegate.braze, braze.notifications.handleUserNotification(
  response: response,
  withCompletionHandler: completionHandler
) {
  return
}
completionHandler()

Para ativar a capacitação do push padrão do Braze, adicione o seguinte código ao método application:didReceiveRemoteNotification:fetchCompletionHandler: de seu aplicativo:

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleBackgroundNotificationWithUserInfo:userInfo
                                                                                                       fetchCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler(UIBackgroundFetchResultNoData);

Em seguida, adicione o seguinte código ao método (void)userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: do seu app:

1
2
3
4
5
6
7
BOOL processedByBraze = AppDelegate.braze != nil && [AppDelegate.braze.notifications handleUserNotificationWithResponse:response
                                                                                                  withCompletionHandler:completionHandler];
if (processedByBraze) {
  return;
}

completionHandler();
Manipulação de push em primeiro plano

Para ativar notificações por push em primeiro plano e permitir que a Braze as reconheça quando forem recebidas, implemente UNUserNotificationCenter.userNotificationCenter(_:willPresent:withCompletionHandler:). Se um usuário tocar na sua notificação em primeiro plano, o userNotificationCenter(_:didReceive:withCompletionHandler:) push delegate será chamado e a Braze registrará o evento de clique no push.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
func userNotificationCenter(
  _ center: UNUserNotificationCenter,
  willPresent notification: UNNotification,
  withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions
) -> Void) {
  if let braze = AppDelegate.braze {
    // Forward notification payload to Braze for processing.
    braze.notifications.handleForegroundNotification(notification: notification)
  }

  // Configure application's foreground notification display options.
  if #available(iOS 14.0, *) {
    completionHandler([.list, .banner])
  } else {
    completionHandler([.alert])
  }
}

Para ativar notificações por push em primeiro plano e permitir que a Braze as reconheça quando forem recebidas, implemente userNotificationCenter:willPresentNotification:withCompletionHandler:. Se um usuário tocar na sua notificação em primeiro plano, o userNotificationCenter:didReceiveNotificationResponse:withCompletionHandler: push delegate será chamado e a Braze registrará o evento de clique no push.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
  if (AppDelegate.braze != nil) {
    // Forward notification payload to Braze for processing.
    [AppDelegate.braze.notifications handleForegroundNotificationWithNotification:notification];
  }

  // Configure application's foreground notification display options.
  if (@available(iOS 14.0, *)) {
    completionHandler(UNNotificationPresentationOptionList | UNNotificationPresentationOptionBanner);
  } else {
    completionHandler(UNNotificationPresentationOptionAlert);
  }
}

Notificações de teste

Se você quiser testar notificações no app e notificações por push via a linha de comando, você pode enviar uma única notificação através do terminal via CURL e a API de envio de mensagens. Você precisará substituir os seguintes campos pelos valores corretos para o seu caso de teste:

  • YOUR_API_KEY - disponível em Configurações > Chaves de API.
  • YOUR_EXTERNAL_USER_ID - disponível na página Pesquisar Usuários. Para saber mais, consulte atribuir IDs de usuário.
  • YOUR_KEY1 (opcional)
  • YOUR_VALUE1 (opcional)

No exemplo a seguir, a instânciaUS-01 está sendo usada. Se você não estiver nessa instância, consulte nossa documentação da API para ver em qual endpoint fazer solicitações.

1
2
3
4
5
6
7
8
9
10
11
curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer {YOUR_API_KEY}" -d '{
  "external_user_ids":["YOUR_EXTERNAL_USER_ID"],
  "messages": {
    "apple_push": {
      "alert":"Test push",
      "extra": {
        "YOUR_KEY1":"YOUR_VALUE1"
      }
    }
  }
}' https://rest.iad-01.braze.com/messages/send

Assinando atualizações de notificações por push

Para acessar as cargas úteis de notificação por push processadas pela Braze, use o método Braze.Notifications.subscribeToUpdates(payloadTypes:_:).

Você pode usar o parâmetro payloadTypes para especificar se deseja se inscrever em notificações envolvendo eventos de push abertos, eventos de push recebidos ou ambos.

1
2
3
4
5
6
// This subscription is maintained through a Braze cancellable, which will observe for changes until the subscription is cancelled.
// You must keep a strong reference to the cancellable to keep the subscription active.
// The subscription is canceled either when the cancellable is deinitialized or when you call its `.cancel()` method.
let cancellable = AppDelegate.braze?.notifications.subscribeToUpdates(payloadTypes: [.open, .received]) { payload in
  print("Braze processed notification with title '\(payload.title)' and body '\(payload.body)'")
}
1
2
3
4
5
NSInteger filtersValue = BRZNotificationsPayloadTypeFilter.opened.rawValue | BRZNotificationsPayloadTypeFilter.received.rawValue;
BRZNotificationsPayloadTypeFilter *filters = [[BRZNotificationsPayloadTypeFilter alloc] initWithRawValue: filtersValue];
BRZCancellable *cancellable = [notifications subscribeToUpdatesWithPayloadTypes:filters update:^(BRZNotificationsPayload * _Nonnull payload) {
  NSLog(@"Braze processed notification with title '%@' and body '%@'", payload.title, payload.body);
}];

Push primers

Campanhas de push primer incentivam seus usuários a ativar notificações por push em seu dispositivo para seu app. Isso pode ser feito sem personalização de SDK usando nosso Push Primer sem código.

Gerenciamento de gateway de APNs dinâmicos

O gerenciamento dinâmico do gateway do serviço de Notificações por Push da Apple (APNs) aumenta a confiabilidade e a eficiência das notificações por push do iOS, detectando automaticamente o ambiente correto de APNs. Anteriormente, você selecionava manualmente os ambientes de APNs (desenvolvimento ou produção) para suas notificações por push, o que às vezes levava a configurações incorretas de gateway, falhas de entrega e erros no site BadDeviceToken.

Com o gerenciamento dinâmico de gateway de APNs, você terá:

  • Maior confiabilidade: As notificações são sempre entregues no ambiente de APNs correto, reduzindo as falhas de entrega.
  • Configuração simplificada: Você não precisa mais gerenciar manualmente as configurações de gateway de APNs.
  • Resiliência a erros: Os valores de gateway inválidos ou ausentes são tratados com elegância, proporcionando um serviço ininterrupto.

Pré-requisitos

O Braze oferece suporte ao gerenciamento de gateway de APNs dinâmicos para notificações por push no iOS com os seguintes requisitos de versão do SDK:

Como funciona?

Quando um app iOS se integra ao Braze Swift SDK, ele envia dados relacionados ao dispositivo, incluindo aps-environment para a API do SDK do Braze, se disponível. O valor apns_gateway indica se o app está usando o ambiente de APNs de desenvolvimento (dev) ou de produção (prod).

O Braze também armazena o valor do gateway relatado para cada dispositivo. Se um novo valor de gateway válido for recebido, o Braze atualiza automaticamente o valor armazenado.

Quando o Braze envia uma notificação por push:

  • Se um valor de gateway válido (dev ou prod) for armazenado para o dispositivo, o Braze o utilizará para determinar o ambiente de APNs correto.
  • Se nenhum valor de gateway for armazenado, o Braze usará como padrão o ambiente de APNs configurado na página de configurações do app.

Perguntas frequentes

Por que esse recurso foi introduzido?

Com o gerenciamento dinâmico de gateway de APNs, o ambiente correto é selecionado automaticamente. Anteriormente, era necessário configurar manualmente o gateway de APNs, o que poderia levar a erros de BadDeviceToken, invalidação de token e possíveis problemas de limite de frequência de APNs.

Como isso afeta o desempenho da entrega de push?

Esse recurso melhora as taxas de entrega, sempre encaminhando tokens por push para o ambiente correto de APNs, evitando falhas causadas por gateways mal configurados.

Posso desativar esse recurso?

O gerenciamento de gateway de APNs dinâmicos é ativado por padrão e oferece melhorias de confiabilidade. Se tiver casos de uso específicos que exijam a seleção manual do gateway, entre em contato com o suporte da Braze.

Prerequisites

Before you can use this feature, you’ll need to integrate the Web Braze SDK.

Push protocols

Web push notifications are implemented using the W3C push standard, which most major browsers support. For more information on specific push protocol standards and browser support, you can review resources from Apple Mozilla and Microsoft.

Setting up push notifications

Step 1: Configure your service worker

In your project’s service-worker.js file, add the following snippet and set the manageServiceWorkerExternally initialization option to true when initializing the Web SDK.

Step 2: Register the browser

To immediately request push permissions from a user so their browser can receive push notifications, call braze.requestPushPermission(). To test if push is supported in their browser first, call braze.isPushSupported().

You can also send a soft push prompt to the user before requesting push permission to show your own push-related UI.

Step 3: Disable skipWaiting (optional)

The Braze service worker file will automatically call skipWaiting upon install. If you’d like to disable this functionality, add the following code to your service worker file, after importing Braze:

Unsubscribing a user

To unsubscribe a user, call braze.unregisterPush().

Alternate domains

To integrate web push, your domain must be secure, which generally means https, localhost, and other exceptions as defined in the W3C push standard. You’ll also need to be able to register a Service Worker at the root of your domain, or at least be able to control the HTTP headers for that file. This article covers how to integrate Braze Web Push on an alternate domain.

Use cases

If you can’t meet all of the criteria outlined in the W3C push standard, you can use this method to add a push prompt dialog to your website instead. This can be helpful if you want to let your users opt-in from an http website or a browser extension popup that’s preventing your push prompt from displaying.

Considerations

Keep in mind, like many workarounds on the web, browsers continually evolve, and this method may not be viable in the future. Before continuing, ensure that:

  • You own a separate secure domain (https://) and permissions to register a Service Worker on that domain.
  • Users are logged in to your website which ensures push tokens are match to the correct profile.

Setting up an alternate push domain

To make the following example clear, we’ll use use http://insecure.com and https://secure.com as our two domains with the goal of getting visitors to register for push on http://insecure.com. This example could also be applied to a chrome-extension:// scheme for a browser extension’s popup page.

Step 1: Initiate prompting flow

On insecure.com, open a new window to your secure domain using a URL parameter to pass the currently logged-in user’s Braze external ID.

http://insecure.com

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<button id="opt-in">Opt-In For Push</button>
<script>
// the same ID you would use with `braze.changeUser`:
const user_id = getUserIdSomehow();
// pass the user ID into the secure domain URL:
const secure_url = `https://secure.com/push-registration.html?external_id=${user_id}`;

// when the user takes some action, open the secure URL in a new window
document.getElementById("opt-in").onclick = function(){
    if (!window.open(secure_url, 'Opt-In to Push', 'height=500,width=600,left=150,top=150')) {
        window.alert('The popup was blocked by your browser');
    } else {
        // user is shown a popup window
        // and you can now prompt for push in this window
    }
}
</script>

Step 2: Register for push

At this point, secure.com will open a popup window in which you can initialize the Braze Web SDK for the same user ID and request the user’s permission for Web push.

https://secure.com/push-registration.html

Step 3: Communicate between domains (optional)

Now that users can opt-in from this workflow originating on insecure.com, you may want to modify your site based on if the user is already opted-in or not. There’s no point in asking the user to register for push if they already are.

You can use iFrames and the postMessage API to communicate between your two domains.

insecure.com

On our insecure.com domain, we will ask the secure domain (where push is actually registered) for information on the current user’s push registration:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!-- Create an iframe to the secure domain and run getPushStatus onload-->
<iframe id="push-status" src="https://secure.com/push-status.html" onload="getPushStatus()" style="display:none;"></iframe>

<script>
function getPushStatus(event){
    // send a message to the iframe asking for push status
    event.target.contentWindow.postMessage({type: 'get_push_status'}, 'https://secure.com');
    // listen for a response from the iframe's domain
    window.addEventListener("message", (event) => {
        if (event.origin === "http://insecure.com" && event.data.type === 'set_push_status') {
            // update the page based on the push permission we're told
            window.alert(`Is user registered for push? ${event.data.isPushPermissionGranted}`);
        }
    }   
}
</script>

secure.com/push-status.html

Frequently Asked Questions (FAQ)

Service workers

What if I can’t register a service worker in the root directory?

By default, a service worker can only be used within the same directory it is registered in. For example, if your service worker file exists in /assets/service-worker.js, it would only be possible to register it within example.com/assets/* or a subdirectory of the assets folder, but not on your homepage (example.com/). For this reason, it is recommended to host and register the service worker in the root directory (such as https://example.com/service-worker.js).

If you cannot register a service worker in your root domain, an alternative approach is to use the Service-Worker-Allowed HTTP header when serving your service worker file. By configuring your server to return Service-Worker-Allowed: / in the response for the service worker, this will instruct the browser to broaden the scope and allow it to be used from within a different directory.

Can I create a service worker using a Tag Manager?

No, service workers must be hosted on your website’s server and can’t be loaded via Tag Manager.

Site security

Is HTTPS required?

Yes. Web standards require that the domain requesting push notification permission be secure.

When is a site considered “secure”?

A site is considered secure if it matches one of the following secure-origin patterns. Braze Web push notifications are built on this open standard, so man-in-the-middle attacks are prevented.

  • (https, , *)
  • (wss, *, *)
  • (, localhost, )
  • (, .localhost, *)
  • (, 127/8, )
  • (, ::1/128, *)
  • (file, *, —)
  • (chrome-extension, *, —)

What if a secure site is not available?

While industry best practice is to make your whole site secure, customers who cannot secure their site domain can work around the requirement by using a secure modal. Read more in our guide to using Alternate push domain or view a working demo.

About push notifications for Android TV

While not a native feature, Android TV push integration is made possible by leveraging the Braze Android SDK and Firebase Cloud Messaging to register a push token for Android TV. It is, however, necessary to build a UI to display the notification payload after it is received.

Prerequisites

To use this feature, you’ll need to complete the following:

Setting up push notifications

To set up push notifications for Android TV:

  1. Create a custom view in your app to display your notifications.
  2. Create a custom notification factory. This will override the default SDK behavior and allow you to manually display the notifications. By returning null, this will prevent the SDK from processing and will require custom code to display the notification. After these steps have been completed, you can start sending push to Android TV!

  3. (Optional) To track click analytics effectively, set up click analytics tracking. This can be achieved by creating a push callback to listen for Braze push opened and received intents.

Testing Android TV push notifications

To test if your push implementation is successful, send a notification from the Braze dashboard as you would normally for an Android device.

  • If the application is closed: The push message will display a toast notification on the screen.
  • If the application is open: You have the opportunity to display the message in your own hosted UI. We recommend following the UI styling of our Android Mobile SDK in-app messages.

Best practices

For marketers using Braze, launching a campaign to Android TV will be identical to launching a push to Android mobile apps. To target these devices exclusively, we recommend selecting the Android TV App in segmentation.

The delivered and clicked response returned by FCM will follow the same convention as a mobile Android device; therefore, any errors will be visible in the message activity log.

Prerequisites

Before you can use this feature, you’ll need to integrate the Cordova Braze SDK. After you integrate the SDK, basic push notification functionality is enabled by default. To use rich push notifications and push stories, you’ll need to set them up individually.

Disabling basic push notifications (iOS only)

After you integrate the Braze Cordova SDK for iOS, basic push notification functionality is enabled by default. To disable this functionality in your iOS app, add the following to your config.xml file. For more information, see Optional configurations.

1
2
3
4
<platform name="ios">
    <preference name="com.braze.ios_disable_automatic_push_registration" value="NO" />
    <preference name="com.braze.ios_disable_automatic_push_handling" value="NO" />
</platform>

Pré-requisitos

Antes de poder usar esse recurso, você precisará integrar o Flutter Braze SDK.

Setting up push notifications

Step 1: Complete the initial setup

Step 1.1: Register for push

Register for push using Google’s Firebase Cloud Messaging (FCM) API. For a full walkthrough, refer to the following steps from the Native Android push integration guide:

  1. Add Firebase to your project.
  2. Add Cloud Messaging to your dependencies.
  3. Create a service account.
  4. Generate JSON credentials.
  5. Upload your JSON credentials to Braze.

Step 1.2: Get your Google Sender ID

First, go to Firebase Console, open your project, then select  Settings > Project settings.

The Firebase project with the "Settings" menu open.

Select Cloud Messaging, then under Firebase Cloud Messaging API (V1), copy the Sender ID to your clipboard.

The Firebase project's "Cloud Messaging" page with the "Sender ID" highlighted.

Step 1.3: Update your braze.xml

Add the following to your braze.xml file. Replace FIREBASE_SENDER_ID with the sender ID you copied previously.

1
2
<bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
<string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

Step 1.1: Upload APNs certificates

Generate an Apple Push Notification service (APNs) certificate and uploaded it to the Braze dashboard. For a full walkthrough, see Uploading your APNs certificate.

Step 1.2: Add push notification support to your app

Follow the native iOS integration guide.

Step 2: Listen for push notification events (optional)

To listen for push notification events that Braze has detected and handled, call subscribeToPushNotificationEvents() and pass in an argument to execute.

1
2
3
4
5
6
7
8
9
10
// Create stream subscription
StreamSubscription pushEventsStreamSubscription;

pushEventsStreamSubscription = braze.subscribeToPushNotificationEvents((BrazePushEvent pushEvent) {
  print("Push Notification event of type ${pushEvent.payloadType} seen. Title ${pushEvent.title}\n and deeplink ${pushEvent.url}");
  // Handle push notification events
});

// Cancel stream subscription
pushEventsStreamSubscription.cancel();
Push notification event fields

For a full list of push notification fields, refer to the table below:

Step 3: Test displaying push notifications

To test your integration after configuring push notifications in the native layer:

  1. Set an active user in the Flutter application. To do so, initialize your plugin by calling braze.changeUser('your-user-id').
  2. Head to Campaigns and create a new push notification campaign. Choose the platforms that you’d like to test.
  3. Compose your test notification and head over to the Test tab. Add the same user-id as the test user and click Send Test.
  4. You should receive the notification on your device shortly. You may need to check in the Notification Center or update Settings if it doesn’t display.

Pré-requisitos

Antes de poder usar esse recurso, você precisará integrar o Android Braze SDK.

Configuração de notificações por push

Os telefones mais novos fabricados pela Huawei vêm equipados com o Huawei Mobile Services (HMS), um serviço usado para enviar push em vez do Firebase Cloud Messaging (FCM) do Google.

Etapa 1: Crie uma conta de desenvolvedor da Huawei

Antes de começar, você precisará criar uma conta de desenvolvedor da Huawei. Em sua conta da Huawei, acesse My Projects > Project Settings > App Information (Meus projetos > Configurações do projeto > Informações do app) e anote os endereços App ID e App secret.

Etapa 2: Crie um novo app da Huawei no dashboard da Braze

No dashboard da Braze, acesse Configurações > Configurações do app.

Clique em + Adicionar app, forneça um nome (como My Huawei App) e selecione Android como a plataforma.

Depois que seu novo app da Braze tiver sido criado, localize as configurações de notificação por push e selecione Huawei como o provedor de push. Em seguida, forneça seu Huawei Client Secret e Huawei App ID.

Etapa 3: Integre o SDK de envio de mensagens da Huawei em seu app

A Huawei forneceu um codelab de integração Android detalhando a integração do Huawei Messaging Service em seu app. Siga essas etapas para começar.

Depois de concluir o codelab, você precisará criar um Huawei Message Service personalizado para obter tokens por push e encaminhar mensagens para o SDK da Braze.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class CustomPushService extends HmsMessageService {
  @Override
  public void onNewToken(String token) {
    super.onNewToken(token);
    Braze.getInstance(this.getApplicationContext()).setRegisteredPushToken(token);
  }

  @Override
  public void onMessageReceived(RemoteMessage remoteMessage) {
    super.onMessageReceived(remoteMessage);
    if (BrazeHuaweiPushHandler.handleHmsRemoteMessageData(this.getApplicationContext(), remoteMessage.getDataOfMap())) {
      // Braze has handled the Huawei push notification
    }
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
class CustomPushService: HmsMessageService() {
  override fun onNewToken(token: String?) {
    super.onNewToken(token)
    Braze.getInstance(applicationContext).setRegisteredPushToken(token!!)
  }

  override fun onMessageReceived(hmsRemoteMessage: RemoteMessage?) {
    super.onMessageReceived(hmsRemoteMessage)
    if (BrazeHuaweiPushHandler.handleHmsRemoteMessageData(applicationContext, hmsRemoteMessage?.dataOfMap)) {
      // Braze has handled the Huawei push notification
    }
  }
}

Depois de adicionar seu serviço push personalizado, adicione o seguinte em seu AndroidManifest.xml:

1
2
3
4
5
6
7
<service
  android:name="package.of.your.CustomPushService"
  android:exported="false">
  <intent-filter>
    <action android:name="com.huawei.push.action.MESSAGING_EVENT" />
  </intent-filter>
</service>

Etapa 4: Teste suas notificações por push (opcional)

Neste ponto, você criou um novo app Huawei para Android no dashboard da Braze, configurou-o com suas credenciais de desenvolvedor da Huawei e integrou os SDKs da Braze e da Huawei ao seu app.

Em seguida, podemos testar a integração testando uma nova campanha push na Braze.

Etapa 4.1: Criar uma nova campanha de notificação por push

Na página Campanhas, crie uma nova campanha e escolha Notificação por push como o tipo de mensagem.

Depois de dar um nome à sua campanha, escolha Push para Android como a plataforma de push.

O criador da campanha exibe as plataformas de push disponíveis.

Em seguida, crie sua campanha de push com um título e uma mensagem.

Etapa 4.2: Enviar um push de teste

Na guia Teste, digite o ID do usuário, que foi definido no app usando o método changeUser(USER_ID_STRING), e clique em Enviar teste para enviar um push de teste.

A guia Teste no criador de mensagens de campanha mostra que você pode enviar uma mensagem de teste para si mesmo, fornecendo seu ID de usuário e inserindo-o no campo "Add Individual Users" (Adicionar usuários individuais).

Nesse momento, você deverá receber uma notificação por push de teste da Braze em seu dispositivo Huawei (HMS).

Etapa 4.3: Configurar a segmentação da Huawei (opcional)

Como o app da Huawei no dashboard da Braze foi criado com base na plataforma de push do Android, você tem a flexibilidade de enviar push para todos os usuários do Android (Firebase Cloud Messaging e Huawei Mobile Services) ou pode optar por segmentar o público da campanha para apps específicos.

Para enviar push apenas para apps da Huawei, crie um novo segmento e selecione seu app da Huawei na seção Apps.

Claro, se quiser enviar o mesmo push para todos os provedores de push do Android, você pode optar por não especificar o app que enviará para todos os apps para Android configurados no espaço de trabalho atual.

Prerequisites

Before you can use this feature, you’ll need to integrate the React Native Braze SDK.

Configurando notificações por push

Etapa 1: Concluir a configuração inicial

Pré-requisitos

Antes de usar o Expo para notificações por push, você precisará configurar o plugin Braze Expo.

Etapa 1.1: Atualize seu arquivo app.json

Em seguida, atualize seu arquivo app.json para Android e iOS:

  • Android: Adicione a opção enableFirebaseCloudMessaging.
  • iOS: Adicione a opção enableBrazeIosPush.

Etapa 1.2: Adicione seu ID de remetente do Google

Primeiro, acesse o Firebase Console, abra seu projeto e selecione Settings > Project settings.

O projeto Firebase com o menu "Settings" (Configurações) aberto.

Selecione Envio de mensagens na nuvem e, em seguida, em Firebase Cloud Messaging API (V1), copie o ID do remetente para a área de transferência.

A página "Cloud Messaging" do projeto Firebase com o "Sender ID" destacado.

Em seguida, abra o arquivo app.json do seu projeto e defina a propriedade firebaseCloudMessagingSenderId como o ID do remetente na área de transferência. Por exemplo:

1
"firebaseCloudMessagingSenderId": "693679403398"

Etapa 1.3: Adicione a jornada ao seu JSON do Google Services

No arquivo app.json de seu projeto, adicione a jornada para seu arquivo google-services.json. Esse arquivo é necessário ao definir enableFirebaseCloudMessaging: true em sua configuração.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
{
  "expo": {
    "android": {
      "googleServicesFile": "PATH_TO_GOOGLE_SERVICES"
    },
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          "androidApiKey": "YOUR-ANDROID-API-KEY",
          "iosApiKey": "YOUR-IOS-API-KEY",
          "enableBrazeIosPush": true,
          "enableFirebaseCloudMessaging": true,
          "firebaseCloudMessagingSenderId": "YOUR-FCM-SENDER-ID",
          "androidHandlePushDeepLinksAutomatically": true
        }
      ],
    ]
  }
}

Note que será necessário usar essas configurações em vez das instruções de configuração nativas se estiver dependendo de bibliotecas adicionais de notificação por push, como a Expo Notifications.

Se você não estiver usando o plugin Braze Expo, ou se preferir configurar essas configurações nativamente, registre-se para push consultando o guia de integração de push nativo para Android.

Se você não estiver usando o plugin Braze Expo, ou se preferir configurar essas configurações nativamente, registre-se para push consultando os seguintes passos do guia de integração de push nativo para iOS:

Etapa 1.1: Solicitação de permissões de push

Se você não planeja solicitar permissões de push quando o app for iniciado, omita a chamada requestAuthorizationWithOptions:completionHandler: no seu AppDelegate. Em seguida, pule para Etapa 2. Caso contrário, siga o guia de integração nativa do iOS.

Etapa 1.2 (Opcional): Migre sua chave push

Se estava usando anteriormente o site expo-notifications para gerenciar sua chave push, execute o site expo fetch:ios:certs na pasta raiz do seu aplicativo. Isso baixará sua chave push (um arquivo .p8), que poderá ser feito upload no dashboard da Braze.

Etapa 2: Solicitar permissão para notificações por push

Use o método Braze.requestPushPermission() (disponível na versão v1.38.0 e superior) para solicitar permissão para notificações por push do usuário no iOS e no Android 13+. Para o Android 12 e versões inferiores, esse método não funciona.

Esse método recebe um parâmetro obrigatório que especifica quais permissões o SDK deve solicitar do usuário no iOS. Essas opções não têm efeito no Android.

1
2
3
4
5
6
7
8
const permissionOptions = {
  alert: true,
  sound: true,
  badge: true,
  provisional: false
};

Braze.requestPushPermission(permissionOptions);

Etapa 2.1: Ouça as notificações por push (opcional)

Além disso, você pode se inscrever em eventos em que o Braze detectou e tratou uma notificação por push recebida. Use a tecla do ouvinte Braze.Events.PUSH_NOTIFICATION_EVENT.

1
2
3
4
Braze.addListener(Braze.Events.PUSH_NOTIFICATION_EVENT, data => {
  console.log(`Push Notification event of type ${data.payload_type} seen. Title ${data.title}\n and deeplink ${data.url}`);
  console.log(JSON.stringify(data, undefined, 2));
});
Campos de eventos de notificação por push

Para obter uma lista completa dos campos de notificação por push, consulte a tabela abaixo:

Etapa 3: Ativar o deep linking (opcional)

Para permitir que o Braze gerencie links profundos dentro de componentes React quando uma notificação por push é clicada, primeiro implemente os passos descritos na biblioteca React Native Linking, ou com a solução de sua escolha. Em seguida, siga os passos adicionais abaixo.

Para saber mais sobre o que são deep linkings, consulte nosso artigo de perguntas frequentes.

Se você estiver usando o plugin Braze Expo, pode gerenciar links profundos de notificações por push automaticamente definindo androidHandlePushDeepLinksAutomatically para true no seu app.json.

Para gerenciar links profundos manualmente, consulte a documentação nativa do Android: Adicionando links profundos.

Etapa 3.1: Armazene a carga útil da notificação por push ao iniciar o app

Para iOS, adicione populateInitialPayloadFromLaunchOptions ao método didFinishLaunchingWithOptions de seu AppDelegate. Por exemplo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  self.moduleName = @"BrazeProject";
  self.initialProps = @{};

  BRZConfiguration *configuration = [[BRZConfiguration alloc] initWithApiKey:apiKey endpoint:endpoint];
  configuration.triggerMinimumTimeInterval = 1;
  configuration.logger.level = BRZLoggerLevelInfo;
  Braze *braze = [BrazeReactBridge initBraze:configuration];
  AppDelegate.braze = braze;

  [self registerForPushNotifications];
  [[BrazeReactUtils sharedInstance] populateInitialPayloadFromLaunchOptions:launchOptions];

  return [super application:application didFinishLaunchingWithOptions:launchOptions];
}

Além dos cenários básicos tratados pelo React Native Linking, implemente o método Braze.getInitialPushPayload e recupere o valor url para contabilizar links profundos de notificações por push que abrem seu app quando ele não está em execução. Por exemplo:

1
2
3
4
5
6
7
8
9
// Handles deep links when an iOS app is launched from a hard close via push click.
// This edge case is not handled in the React Native Linking library and is provided as a workaround by Braze.
Braze.getInitialPushPayload(pushPayload => {
  if (pushPayload) {
    console.log('Braze.getInitialPushPayload is ' + pushPayload);
    showToast('Initial URL is ' + pushPayload.url);
    handleOpenUrl({ pushPayload.url });
  }
});

Para ativar o suporte a linkagem universal, crie um arquivo BrazeReactDelegate.h no seu diretório iOS e adicione o seguinte trecho de código.

1
2
3
4
5
6
#import <Foundation/Foundation.h>
#import <BrazeKit/BrazeKit-Swift.h>

@interface BrazeReactDelegate: NSObject<BrazeDelegate>

@end

Em seguida, crie um arquivo BrazeReactDelegate.m e adicione o seguinte trecho de código. Substitua YOUR_DOMAIN_HOST pelo seu domínio real.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#import "BrazeReactDelegate.h"
#import <UIKit/UIKit.h>

@implementation BrazeReactDelegate

/// This delegate method determines whether to open a given URL.
///
/// Reference the `BRZURLContext` object to get additional details about the URL payload.
- (BOOL)braze:(Braze *)braze shouldOpenURL:(BRZURLContext *)context {
  if ([[context.url.host lowercaseString] isEqualToString:@"YOUR_DOMAIN_HOST"]) {
    // Sample custom handling of universal links
    UIApplication *application = UIApplication.sharedApplication;
    NSUserActivity* userActivity = [[NSUserActivity alloc] initWithActivityType:NSUserActivityTypeBrowsingWeb];
    userActivity.webpageURL = context.url;
    // Routes to the `continueUserActivity` method, which should be handled in your `AppDelegate`.
    [application.delegate application:application
                 continueUserActivity:userActivity restorationHandler:^(NSArray<id<UIUserActivityRestoring>> * _Nullable restorableObjects) {}];
    return NO;
  }
  // Let Braze handle links otherwise
  return YES;
}

@end

Depois, crie e registre seu BrazeReactDelegate em didFinishLaunchingWithOptions do arquivo AppDelegate.m do seu projeto.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import "BrazeReactUtils.h"
#import "BrazeReactDelegate.h"

@interface AppDelegate ()

// Keep a strong reference to the BrazeDelegate to ensure it is not deallocated.
@property (nonatomic, strong) BrazeReactDelegate *brazeDelegate;

@end

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  // Other setup code

  self.brazeDelegate = [[BrazeReactDelegate alloc] init];
  braze.delegate = self.brazeDelegate;
}

Para uma integração de exemplo, consulte nosso app de amostra aqui.

Etapa 4: Envie uma notificação por push de teste

Nesse ponto, você deve poder enviar notificações aos dispositivos. Siga as etapas a seguir para testar sua integração push.

  1. Defina um usuário ativo no aplicativo React Native chamando o método Braze.changeUserId('your-user-id').
  2. Vá para Campaigns (Campanhas ) e crie uma nova campanha de notificação por push. Escolha as plataformas que você gostaria de testar.
  3. Crie sua notificação de teste e vá para a guia Teste. Adicione o mesmo user-id que o usuário teste e clique em Send Test (Enviar teste). Você deverá receber a notificação em seu dispositivo em breve.

Uma campanha de push Braze mostrando que você pode adicionar seu próprio ID de usuário como um destinatário de teste para testar sua notificação por push.

Usando o plugin Expo

Depois de configurar notificações por push para Expo, você pode usá-lo para gerenciar os seguintes comportamentos de notificações por push—sem precisar escrever nenhum código nas camadas nativas do Android ou iOS.

Encaminhamento de push do Android para FMS adicionais

Se quiser usar um Firebase Messaging Service (FMS) adicional, você pode especificar um FMS fallback para chamar se o aplicativo receber um push que não seja do Braze. Por exemplo:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "expo": {
    "plugins": [
      [
        "@braze/expo-plugin",
        {
          ...
          "androidFirebaseMessagingFallbackServiceEnabled": true,
          "androidFirebaseMessagingFallbackServiceClasspath": "com.company.OurFirebaseMessagingService"
        }
      ]
    ]
  }
}

Uso de extensões de app com o Expo Application Services

Se estiver usando o Expo Application Services (EAS) e tiver ativado enableBrazeIosRichPush ou enableBrazeIosPushStories, será necessário declarar os identificadores de pacote correspondentes para cada extensão de app em seu projeto. Há várias maneiras de abordar essa etapa, dependendo de como seu projeto está configurado para gerenciar a assinatura de código com o EAS.

Uma abordagem é usar a configuração appExtensions em seu arquivo app.json seguindo a documentação de extensões de app da Expo. Como alternativa, você pode definir a configuração multitarget em seu arquivo credentials.json seguindo a documentação sobre credenciais de localização da Expo.

Solução de problemas

Esses são passos comuns de solução de problemas para integrações de notificações por push com o SDK Braze React Native e o plugin Expo.

As notificações por push pararam de funcionar

Se as notificações por push através do plugin Expo pararam de funcionar:

  1. Verifique se o SDK Braze ainda está rastreando sessões.
  2. Verifique se o SDK não foi desativado por uma chamada explícita ou implícita para wipeData.
  3. Revise quaisquer atualizações recentes para o Expo ou suas bibliotecas relacionadas, pois pode haver conflitos com sua configuração do Braze.
  4. Revise as dependências do projeto adicionadas recentemente e verifique se elas estão substituindo manualmente seus métodos de delegado de notificação por push existentes.

O token do dispositivo não será registrado no Braze

Se o token do seu dispositivo não for registrado no Braze, primeiro revise as notificações por push pararam de funcionar.

Se o seu problema persistir, pode haver uma dependência separada interferindo na configuração da notificação por push do Braze. Você pode tentar removê-la ou chamar Braze.registerPushToken manualmente em vez disso.

Prerequisites

Before you can use this feature, you’ll need to integrate the Web Braze SDK. Você também precisará configurar notificações por push para o Web SDK. Note que só é possível enviar notificações por push para usuários do iOS e iPadOS que estejam usando o Safari v16.4 ou posterior.

Configuração do Safari push para celular

Etapa 1: Criar um arquivo de manifesto

Um Manifesto de Aplicativo Web é um arquivo JSON que controla como o seu site é apresentado quando instalado na tela inicial de um usuário.

Por exemplo, é possível definir a cor do tema de fundo e o ícone que o App Switcher usa, se ele é renderizado em tela inteira para se assemelhar a um aplicativo nativo ou se o aplicativo deve ser aberto no modo paisagem ou retrato.

Crie um novo arquivo manifest.json no diretório raiz do seu site, com os seguintes campos obrigatórios.

1
2
3
4
5
6
7
8
9
{
  "name": "your app name",
  "short_name": "your app name",
  "display": "fullscreen",
  "icons": [{
    "src": "favicon.ico",
    "sizes": "128x128",
  }]
}

A lista completa de campos suportados pode ser encontrada aqui.

Adicione a seguinte tag <link> ao elemento <head> de seu site, apontando para o local onde o arquivo de manifesto está hospedado.

1
<link rel="manifest" href="/manifest.json" />

Etapa 3: Adicionar um service worker{#service-worker}

Seu site precisa ter um arquivo de service worker que importe a biblioteca de service worker da Braze, conforme descrito em nosso guia de integração de push para web.

Etapa 4: Adicionar à tela inicial

Todos os navegadores populares (como Safari, Chrome, FireFox e Edge) suportam notificações por push da Web em suas versões mais recentes. Para solicitar permissão push no iOS ou iPadOS, seu site deve ser adicionado à tela inicial do usuário selecionando Share To > Add to Home Screen. O Add to Homescreen permite que os usuários marquem seu site como favorito, adicionando seu ícone ao valioso espaço da tela inicial.

Um iPhone mostrando opções para marcar um site como favorito e salvá-lo na tela inicial

Etapa 5: Mostrar o prompt push nativo

Após o app ter sido adicionado à sua tela inicial, agora é possível solicitar permissão de push quando o usuário realizar uma ação (como clicar em um botão). Isso pode ser feito usando o método requestPushPermission ou com uma mensagem no app sem código push primer.

Um prompt push pedindo para "permitir" ou "não permitir" notificações

Por exemplo:

1
2
3
4
5
6
7
8
9
import { requestPushPermission } from "@braze/web-sdk";

button.onclick = function(){
    requestPushPermission(() => {
        console.log(`User accepted push prompt`);
    }, (temporary) => {
        console.log(`User ${temporary ? "temporarily dismissed" : "permanently denied"} push prompt`);
    });
};

Próximas etapas

Em seguida, envie a si mesmo uma mensagem de teste para validar a integração. Depois que sua integração estiver concluída, você poderá usar nossas mensagens push primárias sem código para otimizar suas taxas de aceitação push.

Pré-requisitos

Antes de poder usar esse recurso, você precisará integrar o Unity Braze SDK.

Setting up push notification

Step 1: Set up the platform

Step 1.1: Enable Firebase

To get started, follow the Firebase Unity setup documentation.

Step 1.2: Set your Firebase credentials

You need to input your Firebase Server Key and Sender ID into the Braze dashboard. To do this, log in to the Firebase Developers Console and select your Firebase project. Next, select Cloud Messaging under Settings and copy the Server Key and Sender ID:

In Braze, select your Android app on the App Settings page under Manage Settings. Next, enter your Firebase Server Key in the Firebase Cloud Messaging Server Key field and Firebase Sender ID in the Firebase Cloud Messaging Sender ID field.

Step 1.1: Verify integration method

Braze provides a native Unity solution for automating iOS push integrations. If you you’d like to set up and manage your integration manually instead, see Swift: Push Notifications.

Otherwise, continue to the next step.

Step 1.1: Enable ADM

  1. Create an account with the Amazon Apps & Games Developer Portal if you have not already done so.
  2. Obtain OAuth credentials (Client ID and Client Secret) and an ADM API key.
  3. Enable Automatic ADM Registration Enabled in the Unity Braze Configuration window.
    • Alternatively, you may add the following line to your res/values/braze.xml file to enable ADM registration:
1
  <bool name="com_braze_push_adm_messaging_registration_enabled">true</bool>

Step 2: Configure push notifications

Step 2.1: Configure push settings

The Braze SDK can automatically handle push registration with the Firebase Cloud Messaging Servers to have devices receive push notifications. In Unity, enable Automate Unity Android Integration, then configure the following Push Notification settings.

Step 2.1: Upload your APNs token

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

Step 2.2: Enable automatic push

Open the Braze Configuration Settings in the Unity Editor by navigating to Braze > Braze Configuration.

Check Integrate Push With Braze to automatically register users for push notifications, pass push tokens to Braze, track analytics for push opens, and take advantage of our default push notification handling.

Step 2.3: Enable background push (optional)

Check Enable Background Push if you want to enable background mode for push notifications. This allows the system to wake your application from the suspended state when a push notification arrives, enabling your application to download content in response to push notifications. Checking this option is required for our uninstall tracking functionality.

The Unity editor shows the Braze configuration options. In this editor, the "Automate Unity iOS integration", "Integrate push with braze", and "Enable background push" are enabled.

Step 2.4: Disable automatic registration (optional)

Users who have not yet opted-in to push notifications will automatically be authorized for push upon opening your application. To disable this feature and manually register users for push, check Disable Automatic Push Registration.

  • If Disable Provisional Authorization is not checked on iOS 12 or later, the user will be provisionally (silently) authorized to receive quiet push. If checked, the user will be shown the native push prompt.
  • If you need to configure exactly when the prompt is shown at runtime, disable automatic registration from the Braze configuration editor and use AppboyBinding.PromptUserForPushPermissions() instead.

The Unity editor shows the Braze configuration options. In this editor, the "Automate Unity iOS integration", "integrate push with braze", and "disable automatic push registration" are enabled.

Step 2.1: Update AndroidManifest.xml

If your app does not have an AndroidManifest.xml, you can use the following as a template. Otherwise, if you already have an AndroidManifest.xml, ensure that any of the following missing sections are added to your existing AndroidManifest.xml.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="REPLACE_WITH_YOUR_PACKAGE_NAME">

  <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
  <uses-permission android:name="android.permission.INTERNET" />
  <permission
    android:name="REPLACE_WITH_YOUR_PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE"
    android:protectionLevel="signature" />
  <uses-permission android:name="REPLACE_WITH_YOUR_PACKAGE_NAME.permission.RECEIVE_ADM_MESSAGE" />
  <uses-permission android:name="com.amazon.device.messaging.permission.RECEIVE" />

  <application android:icon="@drawable/app_icon" 
               android:label="@string/app_name">

    <!-- Calls the necessary Braze methods to ensure that analytics are collected and that push notifications are properly forwarded to the Unity application. -->
    <activity android:name="com.braze.unity.BrazeUnityPlayerActivity" 
      android:label="@string/app_name" 
      android:configChanges="fontScale|keyboard|keyboardHidden|locale|mnc|mcc|navigation|orientation|screenLayout|screenSize|smallestScreenSize|uiMode|touchscreen" 
      android:screenOrientation="sensor">
      <meta-data android:name="android.app.lib_name" android:value="unity" />
      <meta-data android:name="unityplayer.ForwardNativeEventsToDalvik" android:value="true" />
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>

    <receiver android:name="com.braze.push.BrazeAmazonDeviceMessagingReceiver" android:permission="com.amazon.device.messaging.permission.SEND">
      <intent-filter>
          <action android:name="com.amazon.device.messaging.intent.RECEIVE" />
          <action android:name="com.amazon.device.messaging.intent.REGISTRATION" />
          <category android:name="REPLACE_WITH_YOUR_PACKAGE_NAME" />
      </intent-filter>
    </receiver>
  </application>
</manifest>

Step 2.2: Store your ADM API key

First, generate an ADM API Key for your app, then save the key to a file named api_key.txt and add it in your project’s Assets/ directory.

Next, in your mainTemplate.gradle file, add the following:

1
2
3
4
5
6
7
task copyAmazon(type: Copy) {
    def unityProjectPath = $/file:///**DIR_UNITYPROJECT**/$.replace("\\", "/")
    from unityProjectPath + '/Assets/api_key.txt'
    into new File(projectDir, 'src/main/assets')
}

preBuild.dependsOn(copyAmazon)

Step 2.3: Add ADM Jar

The required ADM Jar file may be placed anywhere in your project according to the Unity JAR documentation.

Step 2.4: Add Client Secret and Client ID to your Braze dashboard

Lastly, you must add the Client Secret and Client ID you obtained in Step 1 to the Braze dashboard’s Manage Settings page.

Step 3: Set push listeners

Step 3.1: Enable push received listener

The push received listener is fired when a user receives a push notification. To send the push payload to Unity, set the name of your game object and push the received listener callback method under the Set Push Received Listener.

Step 3.2: Enable push opened listener

The push opened listener is fired when a user launches the app by clicking on a push notification. To send the push payload to Unity, set the name of your game object and push opened listener callback method under the Set Push Opened Listener.

Step 3.3: Enable push deleted listener

The push deleted listener is fired when a user swipes away or dismisses a push notification. To send the push payload to Unity, set the name of your game object and push deleted listener callback method under the Set Push Deleted Listener.

Push listener example

The following example implements the BrazeCallback game object using a callback method name of PushNotificationReceivedCallback, PushNotificationOpenedCallback, and PushNotificationDeletedCallback respectively.

This implementation example graphic shows the Braze configuration options mentioned in the preceding sections and a C# code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
public class MainMenu : MonoBehaviour {
  void PushNotificationReceivedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationReceivedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification received: " + pushNotification);   
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push received Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationOpenedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationOpenedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification opened: " + pushNotification);  
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push opened Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationDeletedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationDeletedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification dismissed: " + pushNotification);  
#endif
  }
}

Step 3.1: Enable push received listener

The push received listener is fired when a user receives a push notification while actively using the application (such as when the app is foregrounded). Set the push received listener in the Braze configuration editor. If you need to configure your game object listener at runtime, use AppboyBinding.ConfigureListener() and specify BrazeUnityMessageType.PUSH_RECEIVED.

The Unity editor shows the Braze configuration options. In this editor, the "Set Push Received Listener" option is expanded, and the "Game Object Name" (AppBoyCallback) and "Callback Method Name" (PushNotificationReceivedCallback) are provided.

Step 3.2: Enable push opened listener

The push opened listener is fired when a user launches the app by clicking on a push notification. To send the push payload to Unity, set the name of your game object and push opened listener callback method under the Set Push Opened Listener option:

The Unity editor shows the Braze configuration options. In this editor, the "Set Push Received Listener" option is expanded, and the "Game Object Name" (AppBoyCallback) and "Callback Method Name" (PushNotificationOpenedCallback) are provided.

If you need to configure your game object listener at runtime, use AppboyBinding.ConfigureListener() and specify BrazeUnityMessageType.PUSH_OPENED.

Push listener example

The following example implements the AppboyCallback game object using a callback method name of PushNotificationReceivedCallback and PushNotificationOpenedCallback, respectively.

This implementation example graphic shows the Braze configuration options mentioned in the preceding sections and a C# code snippet.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public class MainMenu : MonoBehaviour {
  void PushNotificationReceivedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationReceivedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification received: " + pushNotification);   
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push received Notification event: " + pushNotification);   
#endif  
  }

  void PushNotificationOpenedCallback(string message) {
#if UNITY_ANDROID
    Debug.Log("PushNotificationOpenedCallback message: " + message);
    PushNotification pushNotification = new PushNotification(message);
    Debug.Log("Push Notification opened: " + pushNotification);  
#elif UNITY_IOS
    ApplePushNotification pushNotification = new ApplePushNotification(message);
    Debug.Log("Push opened Notification event: " + pushNotification);   
#endif  
  }
}

By updating your AndroidManifest.xml in the previous step, push listeners were automatically set up when you added the following lines. So, no further setup is required.

1
2
<action android:name="com.amazon.device.messaging.intent.RECEIVE" />
<action android:name="com.amazon.device.messaging.intent.REGISTRATION" />

Optional configurations

Deep linking to in-app resources

Although Braze can handle standard deep links (such as website URLs, Android URIs, etc.) by default, creating custom deep links requires an additional Manifest setup.

For setup guidance, visit Deep Linking to In-App Resources.

Adding Braze push notification icons

To add push icons to your project, create an Android Archive (AAR) plug-in or Android library that contains the icon image files. For steps and information, refer to Unity’s documentation: Android Library Projects and Android Archive plug-ins.

Push token callback

To receive a copy of Braze device tokens from the OS, set a delegate using AppboyBinding.SetPushTokenReceivedFromSystemDelegate().

There are no optional configurations for ADM at this time.

Prerequisites

Before you can use this feature, you’ll need to integrate the Unreal Engine Braze SDK.

Configurando notificações por push

Etapa 1: Configure seu projeto

Primeiro, adicione o Firebase ao seu projeto Android. Para obter instruções passo a passo, consulte o guia de configuração do Firebase do Google.

Before you can send an iOS push notification using Braze, you need to upload your .p8 push notification file, as described in Apple’s developer documentation:

  1. In your Apple developer account, go to Certificates, Identifiers & Profiles.
  2. Under Keys, select All and click the add button (+) in the upper-right corner.
  3. Under Key Description, enter a unique name for the signing key.
  4. Under Key Services, select the Apple Push Notification service (APNs) checkbox, then click Continue. Click Confirm.
  5. Note the key ID. Click Download to generate and download the key. Make sure to save the downloaded file in a secure place, as you cannot download this more than once.
  6. In Braze, go to Settings > App Settings and upload the .p8 file under Apple Push Certificate. You can upload either your development or production push certificate. To test push notifications after your app is live in the App Store, its recommended to set up a separate workspace for the development version of your app.
  7. When prompted, enter your app’s bundle ID, key ID, and team ID. You’ll also need to specify whether to send notifications to your app’s development or production environment, which is defined by its provisioning profile.
  8. When you’re finished, select Save.

Etapa 2: Ativar notificações por push

Adicione as seguintes linhas ao arquivo engine.ini do seu projeto. Certifique-se de substituir YOUR_SEND_ID pelo ID do remetente no seu projeto Firebase.

1
2
3
bEnableFirebaseCloudMessagingSupport=true
bIsFirebaseCloudMessagingRegistrationEnabled=true
FirebaseCloudMessagingSenderIdKey=YOUR_SENDER_ID

Dentro do mesmo diretório que BrazeUPLAndroid.xml, crie um novo diretório chamado AndroidCopies e adicione seu arquivo google-services.json a ele.

No seu projeto, acesse Configurações > Configurações do Projeto > iOS > Online e marque Ativar Suporte a Notificações Remotas. Quando terminar, verifique se sua provisão tem capacidades de push ativadas.

Configurações opcionais

Definindo ícones pequenos e grandes

Para definir os ícones de notificação pequenos e grandes:

  1. Adicione ícones à pasta drawable apropriada (drawable por padrão) dentro da pasta AndroidCopies/res.
  2. Adicione braze.xml à pasta AndroidCopies/res/values para definir os ícones. Um arquivo braze.xml muito básico:
    1
    2
    3
    4
    5
    
     <?xml version="1.0" encoding="utf-8"?>
     <resources>
         <drawable name="com_braze_push_small_notification_icon">@drawable/notification_small_icon</drawable>
         <drawable name="com_braze_push_large_notification_icon">@drawable/notification_large_icon</drawable>
     </resources>
    

Notificações de lançamento remoto

A partir da versão 4.25.3 do Unreal Engine, o UE4 não possui suporte adequado para receber uma notificação remota que causa o lançamento inicial do aplicativo. Para suportar o recebimento dessa notificação, criamos dois patches git para aplicar - um para o UE4 e um para o plugin Braze SDK.

  1. No diretório Source do seu Engine UE4, aplique o patch git UE4_Engine-Cache-Launch-Remote-Notification.patch.
  2. No diretório do seu SDK Unreal Braze, aplique o patch git Braze_SDK-Read-Cached-Remote-Launch-Notification.patch.

Pré-requisitos

Antes de poder usar este recurso, você precisará integrar o SDK do Xamarin Braze.

Setting up push notifications

To integrate push notifications for Xamarin, you’ll need to complete the steps for native Android push notifications. The following steps are only a summary. For a full walkthrough, see the native push notification guide.

Step 1: Update your project

  1. Add Firebase to your Android project.
  2. Add the Cloud Messaging library to your Android project’s build.gradle:
    1
    
      implementation "google.firebase:firebase-messaging:+"
    

Step 2: Create your JSON credentials

  1. In Google Cloud, enable the Firebase Cloud Messaging API.
  2. Select Service Accounts > your project > Create Service Account, then enter a service account name, ID, and description. When you’re finished, select Create and continue.
  3. In the Role field, find and select Firebase Cloud Messaging API Admin from the list of roles.
  4. In Service Accounts, choose your project, then select  Actions > Manage Keys > Add Key > Create new key. Choose JSON, then select Create.

Step 3: Upload your JSON credentials

  1. In Braze, select  Settings > App Settings. Under your Android app’s Push Notification Settings, choose Firebase, then select Upload JSON File and upload the credentials you generated earlier. When you’re finished, select Save.
  2. Enable automatic FCM token registration, by going to Firebase Console. Open your project, then select  Settings > Project settings. Select Cloud Messaging, then under Firebase Cloud Messaging API (V1), copy the number in the Sender ID field.
  3. In your Android Studio project and the following to your braze.xml.
1
2
  <bool translatable="false" name="com_braze_firebase_cloud_messaging_registration_enabled">true</bool>
  <string translatable="false" name="com_braze_firebase_cloud_messaging_sender_id">FIREBASE_SENDER_ID</string>

Step 1: Complete the initial setup

See the Swift integration instructions for information about setting up your application with push and storing your credentials on our server. Refer to the iOS MAUI sample application for more details.

Step 2: Request push notifications permission

Our Xamarin SDK now supports automatic push set up. Set up push automation and permissions by adding the following code to your Braze instance configuration:

1
2
configuration.Push.Automation = new BRZConfigurationPushAutomation(true);
configuration.Push.Automation.RequestAuthorizationAtLaunch = false;

Refer to the iOS MAUI sample application for more details. For more details, see the Xamarin documentation for Enhanced User Notifications in Xamarin.iOS.

New Stuff!