hotfy_sdk 1.0.6 copy "hotfy_sdk: ^1.0.6" to clipboard
hotfy_sdk: ^1.0.6 copied to clipboard

SDK da Hotfy para Flutter — wrapper (orquestração de ads AdMob/GAM), CDP (eventos, atribuição, ad revenue/ILAR, push) e device token (sync FCM/APNS no Console + CDP).

hotfy_sdk #

SDK da Hotfy para Flutter. Cobre:

  • Wrapper — orquestração remota de anúncios (interstitial, app open, rewarded, banner, native) integrada com AdMob/GAM, com attribution capture, daysSinceInstall, price floors + cascade e event system.
  • CDP — Customer Data Platform: eventos custom, screen views, identify, atribuição, ad revenue (ILAR), push events, offline queue.
  • Device token — registro automático do FCM/APNS no Console e no CDP, com change-detection, retry e safety re-sync.

Instalação #

flutter pub add hotfy_sdk

O pacote já traz as dependências nativas necessárias (google_mobile_ads, shared_preferences, device_info_plus, package_info_plus, android_play_install_referrer, app_links). Você ainda precisa configurar o AdMob App ID no AndroidManifest.xml (Android) e no Info.plist (iOS) — ver a doc do google_mobile_ads.


Onde pegar as API keys #

O SDK usa duas chaves distintas (sistemas diferentes):

Hotfy Console API key #

Identidade do app no Hotfy Console (mesma chave usada nos endpoints /v1/wrapper/config, /v1/devices e /v1/push-events — vai no header x-api-key).

Onde pegar: painel do Hotfy Console → seu app → Settings → "API Key". É um UUID.

Hotfy CDP API key #

Identidade do app no Customer Data Platform (sistema separado — eventos, atribuição, ad revenue).

Onde pegar: painel do Hotfy CDP → seu app → Settings → "API Keys". É um hash hex de 64 caracteres.


Inicialização #

Chame Hotfy.init(...) uma vez no boot do app (ex: no main() antes do runApp, ou no initState do widget raiz).

import 'package:hotfy_sdk/hotfy_sdk.dart';

await Hotfy.init(SdkConfig(
  cdp: CdpConfig(apiKey: hotfyCdpApiKey),
  wrapper: WrapperInitConfig(apiKey: hotfyConsoleApiKey),
  deviceToken: DeviceTokenConfig(), // herda apiKey do wrapper
));

O init() é bloqueante até o wrapper resolver a config (cache local, fetch fresco, ou response default empty). CDP roda em paralelo. Device token aguarda o app chamar setNativeToken(...) — não bloqueia.

Notas sobre defaults:

  • CdpConfig.baseUrl default: https://api.cdp.hotfy.com (override em dev/staging)
  • WrapperInitConfig.baseUrl default: https://wrapper.hotfy.com (idem)
  • WrapperInitConfig.platform detectado automaticamente (ANDROID/IOS)
  • DeviceTokenConfig.apiKey herda de wrapper.apiKey se omitido — mesma key serve

Se você não precisa de push notification via Hotfy Console, omita o deviceToken inteiro.


Mostrar anúncios #

import 'package:hotfy_sdk/hotfy_sdk.dart';

// Splash / cold start
await loadAndShowBootAd();

// Pré-carrega pool de interstitials (chame depois do init)
startAdPreload();

// Transição entre telas
await showInterstitial('home_to_offers');

// "Desbloqueio" — premiado
await showRewarded(screenKey: 'premium_unlock');

Todos os helpers resolvem sem lançar mesmo em falha (sem fill, user fechou cedo, ads off no segmento, ad unit não configurado pra essa tela). O caller pode navegar logo após — não bloqueia UX.

WrapperBanner(screenKey: 'home', size: WrapperBannerSize.banner)

Native ad #

WrapperNativeAd(screenKey: 'home')

Os ad units são resolvidos pelo Hotfy Console por (screenKey, format) — mude no painel sem rebuild do app.


Tracking de eventos (CDP) #

// Evento custom
Hotfy.track('signup', properties: {'plan': 'pro', 'source': 'home_cta'});

// Screen view
Hotfy.screen('Home');

// Identify — vincula anonymousId ao userId autenticado
await Hotfy.identify('user-123', traits: {'email': 'jane@example.com'});

// Flush manual (raramente necessário — auto-flush a cada 30s ou 20 eventos)
await Hotfy.flush();

O anonymousId é gerado no primeiro boot e persiste cross-install.


Ad revenue tracking (ILAR) #

Encaminhar PAID events do AdMob pro CDP automaticamente:

Hotfy.on<AdImpressionEvent>(WrapperEventName.impression, (e) {
  Hotfy.trackAdImpression(AdImpressionData(
    revenueMicros: e.revenueMicros ?? 0,
    currency: e.currency ?? 'USD',
    precision: e.precision ?? 'ESTIMATED',
    adUnitId: e.adUnitId,
    adSource: e.network.name,
    adFormat: e.format.name,
  ));
});

revenueMicros precisa estar em micros (USD × 1.000.000).


Integração com outros analytics #

Hotfy.on(...) permite encaminhar eventos do wrapper pra qualquer destino (Meta, Firebase, etc.). Eventos: load, show, impression, click, close, error, skip.

Cada call de Hotfy.on(...) retorna uma função pra unsubscribe — chame em dispose() se subscrever dentro de um State:

late final void Function() _unsub;

@override
void initState() {
  super.initState();
  _unsub = Hotfy.on<AdImpressionEvent>(WrapperEventName.impression, _onImpression);
}

@override
void dispose() {
  _unsub();
  super.dispose();
}

Push notification token #

Após o usuário conceder permissão, pegue o token FCM/APNS e passe ao SDK:

import 'package:hotfy_sdk/hotfy_sdk.dart';

// token vindo do firebase_messaging / flutter_local_notifications
Hotfy.setNativeToken(token, Platform.isIOS ? DevicePlatform.ios : DevicePlatform.android);

O SDK cuida de:

  • Change-detection — skip se o token não mudou e foi sincronizado nos últimos 30 dias.
  • Retry idempotente — marca pending=true em falha e re-tenta no próximo boot.
  • Sync dual — registra no Hotfy Console (/v1/devices) E no CDP, em paralelo.

Status pra UI:

final status = Hotfy.getPushTokenStatus();
// status.platform, status.hasToken,
// status.console.{synced, lastSyncedAt, pending},
// status.cdp.{synced, lastSyncedAt, pending}

Attribution #

O wrapper captura automaticamente no primeiro install:

  • Android — Google Play Install Referrer (autoritativo, com installBeginTimestamp).
  • iOS — deep link inicial via app_links.

Acesso síncrono após o init():

final attribution = Hotfy.getAttribution(); // AttributionData? — utmSource, gclid, etc.
final days = Hotfy.getDaysSinceInstall();   // int — dias desde o install

// Repassa attribution crua pro CDP (enrich + storage)
await Hotfy.captureAttribution();

Logout #

await Hotfy.reset();

Reseta o CDP — gera novo anonymousId e limpa userId. Não afeta wrapper config nem device token. (Pra resetar o wrapper em debug/QA, use Hotfy.resetWrapper().)


API completa #

Init #

Método Descrição
Hotfy.init(SdkConfig) Bootstrap — bloqueante no wrapper, CDP em paralelo

CDP — tracking, identity, revenue #

Método Descrição
Hotfy.track(event, {properties}) Evento custom
Hotfy.screen(name, {properties}) Screen view
Hotfy.identify(userId, {traits}) Vincula anonymous → user ID
Hotfy.getAnonymousId() Anonymous ID atual
Hotfy.getUserId() User ID setado via identify (ou null)
Hotfy.captureAttribution({params}) Envia attribution pro backend CDP
Hotfy.registerPushToken(token, {...}) (uso direto raro — prefira setNativeToken)
Hotfy.trackPushDelivered(sendId: ...) Reporta delivery de push
Hotfy.trackPushOpened(sendId: ...) Reporta tap em push
Hotfy.trackAdImpression(AdImpressionData) Reporta impressão paga (ILAR)
Hotfy.flush() Flush manual da queue
Hotfy.getDeviceContext() OS, advertising_id, app version, locale, timezone
Hotfy.getAdvertisingId() IDFA/AAID (Future)
Hotfy.reset() Logout — novo anonymousId
Hotfy.shutdown() Para o CDP graciosamente

Wrapper — config + eventos + attribution #

Método Descrição
Hotfy.on<E>(event, handler) Subscreve evento (retorna unsub fn)
Hotfy.off<E>(event, handler) Remove listener manualmente
Hotfy.getConfig() WrapperConfig resolvida ou null
Hotfy.getAttribution() AttributionData capturada (sync)
Hotfy.getDaysSinceInstall() Dias desde install (int)
Hotfy.getAdUnit(screen, format) Ad unit por (screen, format) ou null
Hotfy.getFallbackAdUnit(screen, format) Ad unit fallback
Hotfy.getAppOpen() Ad unit do slot app_open
Hotfy.getAppOpenType() BootAdType.appOpen | BootAdType.interstitial
Hotfy.getAppOpenFallback() / ...Type() Fallback do app_open
Hotfy.isActive() True se ads ativos no segmento
Hotfy.isReady() True quando wrapper resolveu
Hotfy.isAdShowing() True se um ad fullscreen está visível
Hotfy.refresh() Força refetch (limpa cache local)
Hotfy.disableAppOpenOnForeground() Opt-out do App Open ao voltar do background
Hotfy.resetWrapper() Reset do wrapper (debug/QA)

Device token #

Método Descrição
Hotfy.setNativeToken(token, platform) Registra FCM/APNS — dispara sync em background
Hotfy.syncIfNeeded() Manual, idempotente
Hotfy.forceSyncNow() Ignora change-detection (debug)
Hotfy.getPushTokenStatus() Status dos sync alvos (console + CDP)

Helpers de ad orchestration #

Helper Descrição
loadAndShowBootAd() App Open ad na splash
showInterstitial(screenKey) Interstitial via pool pré-carregado
showRewarded(screenKey: ...) Rewarded ad
startAdPreload() Pré-carrega pool de interstitials
WrapperBanner Widget de banner
WrapperNativeAd Widget de native ad

Eventos do wrapper #

Evento Quando
load Ad carregou
show Ad apresentado fullscreen / em tela
impression PAID event do AdMob (ILAR)
click User clicou no ad
close Ad fechou (rewarded / interstitial)
error Falha de load / show
skip Helper decidiu não mostrar (cooldown, segmento off, sem unit, etc.)

License #

UNLICENSED

1
likes
0
points
290
downloads

Publisher

verified publisherhotfy.com

Weekly Downloads

SDK da Hotfy para Flutter — wrapper (orquestração de ads AdMob/GAM), CDP (eventos, atribuição, ad revenue/ILAR, push) e device token (sync FCM/APNS no Console + CDP).

Homepage
Repository (GitHub)
View/report issues

License

unknown (license)

Dependencies

android_play_install_referrer, app_links, device_info_plus, flutter, google_mobile_ads, http, package_info_plus, shared_preferences

More

Packages that depend on hotfy_sdk

Packages that implement hotfy_sdk