Flutter广告追踪插件flutter_poolakey的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter广告追踪插件flutter_poolakey的使用

flutter_poolakey

pub package

简介

flutter_poolakey 是一个用于在 Flutter 应用中集成 Cafe Bazaar 应用商店内购功能的插件。它是 Poolakey 的 Flutter 封装。

开始使用

添加依赖

在你的 pubspec.yaml 文件中添加 flutter_poolakey 依赖:

dependencies:
  flutter_poolakey: ^2.2.0

然后运行以下命令来获取依赖:

flutter packages get

导入插件

在你的 Dart 代码中导入 flutter_poolakey

import 'package:flutter_poolakey/flutter_poolakey.dart';

使用方法

更多关于 flutter_poolakey 的使用信息,请参阅 Wiki 页面

示例代码

以下是一个完整的示例应用,展示了如何使用 flutter_poolakey 进行内购操作。

main.dart

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

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Trivial Example for Flutter-Poolakey',
      theme: ThemeData(
        primarySwatch: Colors.green,
        brightness: Brightness.dark,
      ),
      home: const MyHomePage(title: 'Trivial Example for Flutter-Poolakey'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final dynamicPriceTokenController = TextEditingController();
  final productIdController = TextEditingController();
  bool connected = false;
  String status = "";
  bool consume = true;

  @override
  void initState() {
    _initShop();
    super.initState();
  }

  Future<void> _initShop() async {
    var rsaKey =
        "MIHNMA0GCSqGSIb3DQEBAQUAA4G7ADCBtwKBrwDbkRScfggn+JSs+DzcZK20ZbxKPKv060aekC4dxqapamlgf9PncC5/4sqhUU4SdeKE770H1s7dJhmV5QEnzLawJTgiTzD3RFcadl2H4dduro/KxVyAe5nNKE/Xg+uRalLU/Hw9Or44m2xDyWESWj8sqweaGDUnsoHWJFsyVwwIj15fx3cDX6kjObC0gYns1o79x+COWCqyIlDwE2Pf7Xum55FASKFH8lqlYpEzR38CAwEAAQ== ";
    try {
      connected = await FlutterPoolakey.connect(
        rsaKey,
        onDisconnected: () => showSnackBar("Poolakey disconnected!"),
      );
    } on Exception catch (e) {
      showSnackBar(e.toString());
      setState(() {
        status = "Service: Failed to Connect";
      });
    }

    setState(() {
      if (!connected) {
        status = "Service: Not Connected";
      } else {
        status = "Service: Connected";
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Padding(
          padding: const EdgeInsets.symmetric(horizontal: 16.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text(status),
              const SizedBox(height: 8),
              TextField(
                controller: productIdController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Product id',
                ),
              ),
              const SizedBox(height: 8),
              TextField(
                controller: dynamicPriceTokenController,
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                  hintText: 'Dynamic price token',
                ),
              ),
              Row(
                children: [
                  Text('Consume Purchase'),
                  Spacer(),
                  Switch(
                      value: consume,
                      onChanged: (checked) {
                        setState(() {
                          consume = checked;
                        });
                      }),
                ],
              ),
              FilledButton(
                  onPressed: () {
                    purchaseProduct(
                      productIdController.text,
                      "purchasePayload",
                      dynamicPriceTokenController.text,
                    );
                  },
                  child: Text('Purchase')),
              FilledButton(
                  onPressed: () {
                    subscribeProduct(
                      productIdController.text,
                      "subscribePayload",
                      dynamicPriceTokenController.text,
                    );
                  },
                  child: Text('Subscribe')),
              FilledButton(
                  onPressed: checkUserPurchasedItem,
                  child: Text('Check if user purchased this item')),
              FilledButton(
                  onPressed: checkUserSubscribedItem,
                  child: Text('Check if user subscribed this item')),
              FilledButton(
                  onPressed: () {
                    getSkuDetailOfInAppItem(productIdController.text);
                  },
                  child: Text('Get Sku detail of in-app item')),
              FilledButton(
                  onPressed: () {
                    getSkuDetailOfSubscriptionItem(productIdController.text);
                  },
                  child: Text('Get Sku detail of subscription item')),
              FilledButton(
                  onPressed: checkTrialSubscription,
                  child: Text('Check Trial subscription'))
            ],
          ),
        ),
      ),
    );
  }

  Future<void> subscribeProduct(
    String productId,
    String payload,
    String? dynamicPriceToken,
  ) async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      PurchaseInfo? response = await FlutterPoolakey.subscribe(productId,
          payload: payload, dynamicPriceToken: dynamicPriceToken ?? "");
    } catch (e) {
      showSnackBar("subscribeProduct ${e.toString()}");
      return;
    }
  }

  Future<void> purchaseProduct(
    String productId,
    String payload,
    String? dynamicPriceToken,
  ) async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }
    try {
      PurchaseInfo? response = await FlutterPoolakey.purchase(productId,
          payload: payload, dynamicPriceToken: dynamicPriceToken ?? "");
      if (consume) {
        consumePurchasedItem(response.purchaseToken);
      }
    } catch (e) {
      showSnackBar("purchaseProduct ${e.toString()}");
      return;
    }
  }

  Future<void> checkUserSubscribedItem() async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      List<PurchaseInfo>? response =
          await FlutterPoolakey.getAllSubscribedProducts();
      bool result = response
          .any((element) => element.productId == productIdController.text);
      if (result) {
        showSnackBar("User has bought this item");
      } else {
        showSnackBar("User has not bought this item");
      }
    } catch (e) {
      showSnackBar("checkUserSubscribedItem ${e.toString()}");
      return;
    }
  }

  Future<void> checkUserPurchasedItem() async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      List<PurchaseInfo>? response =
          await FlutterPoolakey.getAllPurchasedProducts();
      bool result = response
          .any((element) => element.productId == productIdController.text);
      if (result) {
        showSnackBar("User has bought this item");
      } else {
        showSnackBar("User has not bought this item");
      }
    } catch (e) {
      showSnackBar("checkUserPurchasedItem ${e.toString()}");
      return;
    }
  }

  Future<void> getSkuDetailOfSubscriptionItem(String skuValueInput) async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      List<SkuDetails>? response =
          await FlutterPoolakey.getSubscriptionSkuDetails([skuValueInput]);
      showSnackBar("Detail Of Subscription Item ${response.toString()}");
    } catch (e) {
      showSnackBar("getSkuDetailOfSubscriptionItem ${e.toString()}");
      return;
    }
  }

  Future<void> getSkuDetailOfInAppItem(String skuValueInput) async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      List<SkuDetails>? response =
          await FlutterPoolakey.getInAppSkuDetails([skuValueInput]);
      showSnackBar("Detail Of InApp Item ${response.toString()}");
    } catch (e) {
      showSnackBar("getSkuDetailOfInAppItem ${e.toString()}");
      return;
    }
  }

  Future<void> checkTrialSubscription() async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      Map response = await FlutterPoolakey.checkTrialSubscription();
      showSnackBar("isAvailable ${response["isAvailable"].toString()}");
    } catch (e) {
      showSnackBar("checkTrialSubscription ${e.toString()}");
      return;
    }
  }

  Future<void> consumePurchasedItem(String purchaseToken) async {
    if (!connected) {
      showSnackBar('Service: Not Connected');
      return;
    }

    try {
      bool? response = await FlutterPoolakey.consume(purchaseToken);
      showSnackBar("consumePurchasedItem success $response");
    } catch (e) {
      showSnackBar(e.toString());
      return;
    }
  }

  void showSnackBar(String message) {
    ScaffoldMessenger.of(context)
        .showSnackBar(SnackBar(content: Text(message)));
  }

  @override
  void dispose() {
    dynamicPriceTokenController.dispose();
    productIdController.dispose();
    super.dispose();
  }
}

说明

  1. 初始化:在 initState 方法中调用 _initShop 方法,连接到 Cafe Bazaar 的内购服务。
  2. 购买产品:通过 purchaseProduct 方法购买一次性商品。
  3. 订阅产品:通过 subscribeProduct 方法购买订阅商品。
  4. 检查用户是否购买了某个商品:通过 checkUserPurchasedItemcheckUserSubscribedItem 方法检查用户是否已经购买了某个商品或订阅。
  5. 获取 SKU 详细信息:通过 getSkuDetailOfInAppItemgetSkuDetailOfSubscriptionItem 方法获取商品的详细信息。
  6. 检查试用订阅:通过 checkTrialSubscription 方法检查用户是否有试用订阅。
  7. 消耗已购买的商品:通过 consumePurchasedItem 方法消耗已购买的一次性商品。

希望这个示例能帮助你更好地理解和使用 flutter_poolakey 插件。如果你有任何问题,欢迎在 GitHub 仓库 提交 issue 或 PR。


更多关于Flutter广告追踪插件flutter_poolakey的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter广告追踪插件flutter_poolakey的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是如何在Flutter项目中集成和使用flutter_poolakey插件来进行广告追踪的一个示例代码案例。flutter_poolakey是一个用于广告追踪的Flutter插件,可以帮助你更好地管理广告标识符(如IDFA或AAID)。

1. 添加依赖

首先,你需要在你的pubspec.yaml文件中添加flutter_poolakey的依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_poolakey: ^最新版本号  # 请替换为实际发布的最新版本号

2. 导入插件

在你的Dart文件中(比如main.dart),导入flutter_poolakey插件:

import 'package:flutter_poolakey/flutter_poolakey.dart';

3. 初始化插件

在应用的入口点(比如main.dartmain函数中),初始化插件:

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterPoolakey.init();
  runApp(MyApp());
}

4. 获取广告标识符

你可以使用FlutterPoolakey.getAdvertisingIdInfo方法来获取广告标识符和是否启用了限制广告追踪的信息。

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await FlutterPoolakey.init();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Poolakey Example'),
        ),
        body: Center(
          child: AdvertisingIdInfoWidget(),
        ),
      ),
    );
  }
}

class AdvertisingIdInfoWidget extends StatefulWidget {
  @override
  _AdvertisingIdInfoWidgetState createState() => _AdvertisingIdInfoWidgetState();
}

class _AdvertisingIdInfoWidgetState extends State<AdvertisingIdInfoWidget> {
  String? advertisingId;
  bool? isLimitAdTrackingEnabled;

  @override
  void initState() {
    super.initState();
    _getAdvertisingIdInfo();
  }

  Future<void> _getAdvertisingIdInfo() async {
    try {
      var info = await FlutterPoolakey.getAdvertisingIdInfo();
      setState(() {
        advertisingId = info.id;
        isLimitAdTrackingEnabled = info.isLimitAdTrackingEnabled;
      });
    } catch (e) {
      print('Error fetching advertising ID info: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        Text('Advertising ID: ${advertisingId ?? 'Loading...'}'),
        Text('Limit Ad Tracking Enabled: ${isLimitAdTrackingEnabled ?? 'Loading...'}'),
      ],
    );
  }
}

5. 运行应用

确保你已经连接了一个支持广告追踪的设备或模拟器,然后运行你的Flutter应用:

flutter run

这个示例展示了如何在Flutter应用中集成flutter_poolakey插件,并获取广告标识符和限制广告追踪的状态。你可以根据实际需求进一步处理这些广告追踪信息。

注意:在实际应用中,处理广告标识符时应遵守相关的隐私政策和法规,确保用户的隐私安全。

回到顶部