Flutter集成Axeptio SDK插件axeptio_sdk的使用

Flutter集成Axeptio SDK插件axeptio_sdk的使用

本仓库展示了如何在您的移动应用程序中实现Axeptio Flutter SDK。

该模块可以根据您的需求通过brandspublishers构建。

设置

安装

flutter pub add axeptio_sdk

Android设置

  • 最低SDK版本为26
  • 在应用的android/build.gradle文件中添加Maven GitHub仓库和凭证
repositories {
    maven {
        url = uri("https://maven.pkg.github.com/axeptio/axeptio-android-sdk")
        credentials {
           username = "[GITHUB_USERNAME]"
           password = "[GITHUB_TOKEN]"
        }
   }
}

iOS

我们支持iOS版本 >= 15。 SDK不管理App Tracking Transparency,更多信息可以在这里找到。

示例

您可以在example文件夹中找到Axeptio SDK的基本用法。 请阅读具体的文档

使用

应用启动时初始化SDK

SDK可以通过AxeptioService枚举在初始化期间配置为brandspublishers

final axeptioSdkPlugin = AxeptioSdk();
await axeptioSdkPlugin.initialize(
   AxeptioService.brands, // 或者 AxeptioService.publishers
  [your_client_id],  
  [your_cookies_version],  
  [optional_consent_token],
);
await axeptioSdkPlugin.setupUI();

App Tracking Transparency (ATT)

Axeptio SDK不会请求用户授权进行跟踪,这是由应用负责的,并且需要决定如何与Axeptio CMP和ATT权限共存。

您的应用必须遵循Apple的指南来披露应用收集的数据并请求用户的跟踪授权。

要管理App Tracking Transparency,您可以使用app_tracking_transparency库。

首先安装它:

flutter pub add app_tracking_transparency

在您的Info.plist文件中添加NSUserTrackingUsageDescription

<key>NSUserTrackingUsageDescription</key>
<string>解释为什么需要用户跟踪</string>

现在可以在设置UI之前管理ATT弹窗:

try {
  TrackingStatus status =
      await AppTrackingTransparency.trackingAuthorizationStatus;
  // 如果系统可以显示授权请求对话框
  if (status == TrackingStatus.notDetermined) {
    // 请求系统的跟踪授权对话框
    status = await AppTrackingTransparency.requestTrackingAuthorization();
  }

  if (status == TrackingStatus.denied) {
    // 调用setUserDeniedTracking
    await _axeptioSdkPlugin.setUserDeniedTracking();
  } else {
    // 如果接受则运行setupUI
    await _axeptioSdkPlugin.setupUI();
  }
} on PlatformException {
  // 在Android上运行setupUI
  await _axeptioSdkPlugin.setupUI();
}

移动应用与SDK的责任划分

移动应用职责:

  • 实现和管理App Tracking Transparency (ATT)权限流
  • 决定何时显示ATT提示相对于Axeptio CMP
  • 正确声明App Store隐私标签中的数据收集实践
  • 处理SDK事件并根据用户同意更新应用行为

Axeptio SDK职责:

  • 显示同意管理平台(CMP)界面
  • 管理和存储用户同意选择
  • 通过API发送同意状态

SDK不会自动处理ATT权限——这必须由宿主应用显式管理,如上述实现示例所示。

获取存储的同意

您可以从UserDefaults/SharedPreferences检索SDK存储的同意。

要访问UserDefaults/SharedPreferences,您可以使用shared_preferences库。

有关存储值和Cookie的详细信息,请参阅Axeptio文档

按需显示同意弹窗

此外,您可以请求按需打开同意弹窗。

axeptioSdk.showConsentScreen();

与其他WebView共享同意

注意:此功能仅适用于发布者服务。

SDK提供了一个辅助函数,用于将axeptio_token查询参数附加到任何URL。

您可以指定自定义用户令牌或使用当前存储在SDK中的令牌。

final token = await axeptioSdk.axeptioToken;
final url = await axeptioSdk.appendAxeptioTokenURL(  
  "https://myurl.com",  
  token,  
); 

将返回https://myurl.com?axeptio_token=[token]

清除用户的同意选择

axeptioSdk.clearConsent();

事件

Axeptio SDK触发各种事件以通知您用户已采取某些操作。

我们提供了一个AxeptioEventListener类,可以用来捕获事件。不要忘记将此监听器添加到AxeptioSdk中,如下所示。

var listener = AxeptioEventListener();
listener.onPopupClosedEvent = () {
  // 同意管理平台(CMP)通知隐藏
  // 从UserDefaults/SharedPreferences检索同意
  // 检查用户偏好
  // 根据用户同意运行外部进程/服务
};

listener.onConsentChanged = () {
  // 用户同意改变
  // 执行一些操作
};

listener.onGoogleConsentModeUpdate = (consents) {
  // Google Consent V2状态
  // 执行一些操作
};

// 使用可用的方法添加和移除监听器
var axeptioSdk = AxeptioSdk()
axeptioSdkPlugin.addEventListerner(listener);
axeptioSdkPlugin.removeEventListener(listener);

示例代码

// ignore_for_file: avoid_print

import 'dart:async';
import 'dart:io';

import 'package:app_tracking_transparency/app_tracking_transparency.dart';
import 'package:axeptio_sdk/axeptio_sdk.dart';
import 'package:axeptio_sdk/events/event_listener.dart';
import 'package:axeptio_sdk_example/tokendialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mobile_ads/google_mobile_ads.dart';
import 'package:axeptio_sdk/model/axeptio_service.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  MobileAds.instance.initialize();

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // ignore: unused_field
  String _platformVersion = 'Unknown';
  InterstitialAd? _interstitialAd;
  Function()? _onAdBtnPressed;

  final _axeptioSdkPlugin = AxeptioSdk();

  final adUnitId = Platform.isAndroid
      ? 'ca-app-pub-3940256099942544/1033173712'
      : 'ca-app-pub-3940256099942544/4411468910';

  /// 加载一个插屏广告。
  void loadAd() {
    InterstitialAd.load(
        adUnitId: adUnitId,
        request: const AdRequest(),
        adLoadCallback: InterstitialAdLoadCallback(
          // 成功接收到广告时调用。
          onAdLoaded: (ad) {
            print('$ad loaded.');
            // 保持对广告的引用,以便稍后展示。
            setState(() {
              _interstitialAd = ad;
              _onAdBtnPressed = () {
                _interstitialAd?.show();
                loadAd();
              };
            });
          },
          // 广告加载失败时调用。
          onAdFailedToLoad: (LoadAdError error) {
            print('InterstitialAd failed to load: $error');
            setState(() {
              _onAdBtnPressed = null;
            });
          },
        ));
  }

  [@override](/user/override)
  void initState() {
    super.initState();
    initSDK();
    loadAd();
  }

  Future<void> initSDK() async {
    try {
      await _axeptioSdkPlugin.initialize(
        AxeptioService.brands,
        '5fbfa806a0787d3985c6ee5f',
        'google cmp partner program sandbox-en-EU',
        null,
      );

      var listener = AxeptioEventListener();
      listener.onPopupClosedEvent = () {
        // 同意管理平台(CMP)通知隐藏
        loadAd();
      };
      listener.onConsentChanged = () {
        // 用户同意改变
        // 执行一些操作
      };
      listener.onGoogleConsentModeUpdate = (consents) {
        // Google Consent V2状态
        // 执行一些操作
      };
      _axeptioSdkPlugin.addEventListerner(listener);

      try {
        TrackingStatus status =
            await AppTrackingTransparency.trackingAuthorizationStatus;
        // 如果系统可以显示授权请求对话框
        if (status == TrackingStatus.notDetermined) {
          // 请求系统的跟踪授权对话框
          status = await AppTrackingTransparency.requestTrackingAuthorization();
        }

        if (status == TrackingStatus.denied) {
          await _axeptioSdkPlugin.setUserDeniedTracking();
        } else {
          // 如果接受则运行setupUI
          await _axeptioSdkPlugin.setupUI();
        }
      } on PlatformException {
        // 在Android上运行setupUI
        await _axeptioSdkPlugin.setupUI();
      }
    } catch (e) {
      print("ERROR $e");
    }
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能失败,所以我们使用try/catch PlatformException。
    // 我们还处理消息可能返回null的情况。
    try {
      platformVersion = await _axeptioSdkPlugin.getPlatformVersion() ??
          'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果小部件在异步平台消息处于飞行状态时被从树中移除,我们希望丢弃回复而不是调用setState来更新我们的非存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
        home: HomePage(
            axeptioSdk: _axeptioSdkPlugin,
            onAdBtnPressed: _onAdBtnPressed,
            onClearPressed: () {
              loadAd();
            }));
  }
}

class HomePage extends StatelessWidget {
  const HomePage(
      {super.key,
      required this.axeptioSdk,
      required this.onAdBtnPressed,
      required this.onClearPressed});

  final AxeptioSdk axeptioSdk;
  final Function()? onAdBtnPressed;
  final Function() onClearPressed;

  [@override](/user/override)
  Widget build(BuildContext context) {
    const backgroundColor = Color.fromRGBO(253, 247, 231, 1);

    const TextStyle textStyle = TextStyle(fontSize: 18, color: Colors.black);
    final ButtonStyle style = ElevatedButton.styleFrom(
      textStyle: textStyle,
      elevation: 0,
      backgroundColor: const Color.fromRGBO(247, 209, 94, 1),
    );

    final ButtonStyle clearConsentStyle = ElevatedButton.styleFrom(
      textStyle: textStyle,
      elevation: 0,
      backgroundColor: const Color.fromRGBO(205, 97, 91, 1),
    );

    return Scaffold(
      backgroundColor: const Color.fromRGBO(255, 0, 0, 1),
      body: Container(
        padding: const EdgeInsets.all(20.0),
        color: backgroundColor,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            ElevatedButton(
              style: style,
              onPressed: () {
                axeptioSdk.showConsentScreen();
              },
              child: const Text(
                '同意弹窗',
                style: textStyle,
              ),
            ),
            ElevatedButton(
              style: style,
              onPressed: onAdBtnPressed,
              child: const Text(
                '谷歌广告',
                style: textStyle,
              ),
            ),
            ElevatedButton(
              style: clearConsentStyle,
              onPressed: () {
                axeptioSdk.clearConsent();
                onClearPressed();
              },
              child: const Text(
                '清除同意',
                style: textStyle,
              ),
            ),
            ElevatedButton(
              style: style,
              onPressed: () {
                showDialog(
                    context: context,
                    builder: (BuildContext context) => TokenAppendDialog(
                          axeptioSdk: axeptioSdk,
                        ));
              },
              child: const Text(
                '显示带有令牌的WebView',
                style: textStyle,
              ),
            ),
          ],
        ),
      ),
    );
  }
}
1 回复

更多关于Flutter集成Axeptio SDK插件axeptio_sdk的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


要在 Flutter 应用中集成 Axeptio SDK 插件 axeptio_sdk,您可以按照以下步骤进行:

1. 添加依赖

首先,在 pubspec.yaml 文件中添加 axeptio_sdk 插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  axeptio_sdk: ^1.0.0  # 请检查最新版本

然后运行 flutter pub get 以安装依赖。

2. 初始化 SDK

在您的 Flutter 应用启动时初始化 Axeptio SDK。通常,您可以在 main.dart 文件中进行初始化。

import 'package:axeptio_sdk/axeptio_sdk.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化 Axeptio SDK
  await Axeptio.initialize(
    clientId: 'YOUR_CLIENT_ID',  // 替换为您的 Axeptio Client ID
    cookiesVersion: 'v1',       // 替换为您的 Cookies 版本
    language: 'en',             // 替换为您的应用语言
  );

  runApp(MyApp());
}

3. 显示 Axeptio 弹出窗口

在您希望显示 Axeptio 弹出窗口的地方,调用 Axeptio.showConsentUI() 方法。

import 'package:flutter/material.dart';
import 'package:axeptio_sdk/axeptio_sdk.dart';

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Axeptio SDK Example'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // 显示 Axeptio 弹出窗口
            await Axeptio.showConsentUI();
          },
          child: Text('Show Consent UI'),
        ),
      ),
    );
  }
}

4. 处理用户同意

您可以通过监听用户的同意状态来处理用户的选择。例如:

Axeptio.onConsentChanged.listen((consentStatus) {
  // 处理用户同意状态
  print('User consent status: $consentStatus');
});

5. 获取用户同意状态

您还可以通过 Axeptio.getConsentStatus() 方法获取用户的同意状态:

Map<String, bool> consentStatus = await Axeptio.getConsentStatus();
print('Consent status: $consentStatus');

6. 重置用户同意状态

如果需要重置用户的同意状态,可以调用 Axeptio.resetConsent() 方法:

await Axeptio.resetConsent();

7. 处理错误

您可以通过监听错误来处理 SDK 可能出现的异常:

Axeptio.onError.listen((error) {
  // 处理错误
  print('Axeptio SDK error: $error');
});

8. 其他功能

axeptio_sdk 还提供了其他功能,例如:

  • 设置用户 ID
  • 设置用户电子邮件
  • 设置用户属性

您可以根据需要查阅官方文档或 SDK 源码来使用这些功能。

9. 运行应用

完成上述步骤后,您可以运行您的 Flutter 应用,并测试 Axeptio SDK 的集成。

flutter run
回到顶部
AI 助手
你好,我是IT营的 AI 助手
您可以尝试点击下方的快捷入口开启体验!