Flutter收据管理插件magic_receipts的使用

概述

Magic Receipts Flutter 插件允许将 Magic Receipts 集成到 Flutter 的 Android 和 iOS 应用程序中。本文将详细介绍如何配置和使用该插件。


前置条件

在开始之前,请确保满足以下条件:

  1. Android SDK 21 或更高版本,并使用 Google Play Services。
  2. iOS 版本 13.0 或更高版本
  3. Flutter 版本 1.20.0 或更高版本
  4. Dart SDK 版本 2.12.0 或更高版本
  5. CocoaPods 版本 1.10.0 或更高版本

快速指南

以下是集成 Magic Receipts 的步骤:

  1. 创建 Pollfish 开发者账户
  2. 在 Pollfish 开发者仪表板上注册新应用,并复制给定的 API 密钥
  3. 在您的账户中启用 Magic Receipts 功能
  4. 下载并导入 Magic Receipts 包到您的项目中
  5. 导入 Magic Receipts 包
  6. 配置并初始化 Magic Receipts SDK
  7. (可选)监听 Magic Receipts 生命周期事件
  8. (可选)控制 SDK
  9. (可选)配置回传(Postbacks)

详细步骤

1. 创建 Pollfish 开发者账户

访问 Pollfish 官网 并注册为发布商。

2. 在 Pollfish 开发者仪表板上注册新应用并复制 API 密钥

登录 Pollfish 官网,点击“添加新应用”,然后复制生成的 API 密钥以供后续使用。

3. 在账户中启用 Magic Receipts 功能

在应用设置中找到“调查结束页面上的广告”选项并启用功能开关。

启用 Magic Receipts

4. 下载并导入 Magic Receipts 包到您的项目中

在项目的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  ...
  magic_receipts: ^1.0.2

执行以下命令以获取依赖项:

flutter packages get

5. 导入 Magic Receipts 包

在 Dart 文件中导入 Magic Receipts 包:

import 'package:magic_receipts/magic_receipts.dart';

6. 配置并初始化 Magic Receipts SDK

Magic Receipts 插件必须使用一个或两个 API 密钥进行初始化,具体取决于目标平台。您可以在 Pollfish 仪表板中创建新应用时获取 API 密钥。

初始化示例代码:

MagicReceipts.initialize(
  androidApiKey: 'ANDROID_API_KEY',
  iOSApiKey: 'IOS_API_KEY',
  rewardMode: true, // 启用奖励模式
);

初始化参数说明:

  • androidApiKey: Android 平台的 API 密钥。
  • iOSApiKey: iOS 平台的 API 密钥。
  • rewardMode: 是否启用奖励模式。

6.1 使用 userId

userId 是一个唯一的用户标识符,用于跨会话识别用户。

MagicReceipts.initialize(
  androidApiKey: 'ANDROID_API_KEY',
  iOSApiKey: 'IOS_API_KEY',
  rewardMode: true,
  userId: "USER_ID", // 替换为实际用户 ID
);

6.2 使用 incentiveMode

启用激励模式后,Magic Receipts 指示器不会显示,且优惠墙会自动隐藏,直到调用 .show() 方法。

MagicReceipts.initialize(
  androidApiKey: 'ANDROID_API_KEY',
  iOSApiKey: 'IOS_API_KEY',
  rewardMode: true,
  incentiveMode: true, // 启用激励模式
);

6.3 使用 clickId

clickId 是一个透传参数,用于通过服务器到服务器回传来识别点击。

MagicReceipts.initialize(
  androidApiKey: 'ANDROID_API_KEY',
  iOSApiKey: 'IOS_API_KEY',
  rewardMode: true,
  clickId: "CLICK_ID", // 替换为实际点击 ID
);

可选部分

7. 监听 Magic Receipts 生命周期事件

您可以监听 Magic Receipts 的生命周期事件以获取实时反馈。

7.1 获取 SDK 加载完成的通知
MagicReceipts.setMagicReceiptsWallLoadedListener(_onMagicReceiptsWallLoaded);

_onMagicReceiptsWallLoaded() {
  print("Magic Receipts 壁纸加载完成");
}
7.2 获取加载失败的通知
MagicReceipts.setMagicReceiptsWallLoadFailedListener(_onMagicReceiptsWallLoadFailed);

_onMagicReceiptsWallLoadFailed(MagicReceiptsLoadError error) {
  print("加载失败: ${error.message}");
}
7.3 获取优惠墙打开的通知
MagicReceipts.setMagicReceiptsWallShowedListener(_onMagicReceiptsWallShowed);

_onMagicReceiptsWallShowed() {
  print("Magic Receipts 优惠墙已打开");
}
7.4 获取优惠墙显示失败的通知
MagicReceipts.setMagicReceiptsWallShowFailedListener(_onMagicReceiptsWallShowFailed);

_onMagicReceiptsWallShowFailed(MagicReceiptsShowError error) {
  print("优惠墙显示失败: ${error.message}");
}
7.5 获取优惠墙关闭的通知
MagicReceipts.setMagicReceiptsWallHiddenListener(_onMagicReceiptsWallHid);

_onMagicReceiptsWallHid() {
  print("Magic Receipts 优惠墙已关闭");
}

8. 控制 SDK

8.1 手动显示/隐藏 Magic Receipts 视图
// 显示优惠墙
MagicReceipts.show();

// 隐藏优惠墙
MagicReceipts.hide();
8.2 检查 SDK 是否准备就绪
MagicReceipts.isReady().then((isReady) {
  print("SDK 是否准备就绪: $isReady");
});

回传(Postbacks)

9.1 配置回传 URL

您可以通过 Pollfish 开发者仪表板设置服务器到服务器的回传 URL。每次转化时,我们将向此 URL 发送 HTTP GET 请求。

配置回传 URL

注意: 如果您奖励用户,请务必使用此回调来验证转化,这是最准确和安全的方式。

9.2 唯一标识转化并避免重复

为了避免重复回调,请检查 tx_id 参数,它在每次转化中都是唯一的。

9.3 保护回传

通过在回传 URL 中添加签名模板参数来保护回调。例如:

http://www.example.com/callback?tx_id=[[tx_id]]&cpa=[[cpa]]&device=[[device_id]]&click_id=[[click_id]]&sig=[[signature]]

9.3.1 签名是如何生成的?

签名是通过对包含参数的字符串应用 HMAC-SHA1 函数生成的。签名仅对指定的参数进行加密,而不包括其他 URL 参数。

9.3.2 如何验证签名?

验证签名的步骤详见官方文档。

9.4 查看回传日志

您可以通过导航到仪表板中的“End Page Ads -> 监控页面”来查看回传日志。

回传日志


示例代码

以下是一个完整的示例代码,展示如何使用 Magic Receipts 插件:

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

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

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

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

class _MyAppState extends State<MyApp> {
  static const String _androidApiKey = "ANDROID_API_KEY";
  static const String _iOSApiKey = "IOS_API_KEY";

  String? _logMessage;
  bool _incentiveMode = false;

  _initializePollfish() {
    MagicReceipts.setMagicReceiptsWallLoadedListener(_onMagicReceiptsWallLoaded);
    MagicReceipts.setMagicReceiptsWallLoadFailedListener(
        _onMagicReceiptsWallLoadFailed);
    MagicReceipts.setMagicReceiptsWallShowedListener(
        _onMagicReceiptsWallShowed);
    MagicReceipts.setMagicReceiptsWallShowFailedListener(
        _onMagicReceiptsWallShowFailed);

    MagicReceipts.initialize(
      androidApiKey: _androidApiKey,
      iosApiKey: _iOSApiKey,
      incentiveMode: _incentiveMode,
      userId: "pollfish-fotis",
    );
  }

  _onMagicReceiptsWallLoaded() {
    setState(() {
      _logMessage = "Wall loaded";
    });
  }

  _onMagicReceiptsWallLoadFailed(MagicReceiptsLoadError error) {
    setState(() {
      _logMessage = "Wall load failed with error: ${error.message}";
    });
  }

  _onMagicReceiptsWallShowed() {
    setState(() {
      _logMessage = "Wall Showed";
    });
  }

  _onMagicReceiptsWallShowFailed(MagicReceiptsShowError error) {
    setState(() {
      _logMessage = "Wall load failed with error: ${error.message}";
    });
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('Magic Receipts sample app'),
        ),
        body: Container(
          width: double.infinity,
          height: double.infinity,
          padding: const EdgeInsets.all(8),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              TextButton(
                child: const Text('Initialize'),
                onPressed: () => _initializePollfish(),
              ),
              Row(
                mainAxisSize: MainAxisSize.max,
                children: [
                  Expanded(
                    child: ElevatedButton(
                        onPressed: () => MagicReceipts.show(),
                        child: const Text("Show")),
                  ),
                  const SizedBox(
                    width: 8,
                  ),
                  Expanded(
                    child: ElevatedButton(
                        onPressed: () => MagicReceipts.hide(),
                        child: const Text("Hide")),
                  )
                ],
              ),
              Row(
                children: [
                  const Text("Incentive mode"),
                  const Spacer(),
                  Switch(
                      value: _incentiveMode,
                      onChanged: (value) {
                        setState(() {
                          _incentiveMode = value;
                        });
                      })
                ],
              ),
              const SizedBox(
                width: 8,
              ),
              ElevatedButton(
                  onPressed: () {
                    MagicReceipts.isReady().then((value) => {
                          setState(() {
                            _logMessage = value ? "SDK is ready" : "SDK is not ready";
                          });
                        });
                  },
                  child: const Text("Is Ready?")),
              const SizedBox(
                width: 8,
              ),
              _logMessage != null
                  ? Text("Last log: $_logMessage")
                  : const SizedBox.shrink(),
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter收据管理插件magic_receipts的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter收据管理插件magic_receipts的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


magic_receipts 是一个用于 Flutter 的收据管理插件,它可以帮助开发者轻松地集成收据扫描、管理和上传功能。以下是如何使用 magic_receipts 插件的基本步骤:

1. 添加依赖

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

dependencies:
  flutter:
    sdk: flutter
  magic_receipts: ^1.0.0  # 请使用最新版本

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

2. 初始化插件

在你的 Flutter 应用中初始化 magic_receipts 插件。通常,你可以在 main.dart 文件中进行初始化:

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

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  
  // 初始化 magic_receipts
  await MagicReceipts.initialize(apiKey: 'YOUR_API_KEY');
  
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Magic Receipts Demo',
      home: ReceiptScreen(),
    );
  }
}

3. 扫描收据

使用 MagicReceipts 提供的 API 来扫描收据。你可以调用 scanReceipt 方法来启动收据扫描:

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

class ReceiptScreen extends StatelessWidget {
  Future<void> _scanReceipt() async {
    try {
      final receipt = await MagicReceipts.scanReceipt();
      print('Receipt scanned: ${receipt.toJson()}');
    } catch (e) {
      print('Error scanning receipt: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Magic Receipts'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _scanReceipt,
          child: Text('Scan Receipt'),
        ),
      ),
    );
  }
}

4. 处理扫描结果

scanReceipt 方法会返回一个 Receipt 对象,你可以从中获取收据的详细信息,如金额、日期、商家等:

final receipt = await MagicReceipts.scanReceipt();
print('Amount: ${receipt.amount}');
print('Date: ${receipt.date}');
print('Merchant: ${receipt.merchant}');

5. 上传收据

你可以将扫描的收据上传到服务器或进行其他处理:

Future<void> _uploadReceipt(Receipt receipt) async {
  try {
    await MagicReceipts.uploadReceipt(receipt);
    print('Receipt uploaded successfully');
  } catch (e) {
    print('Error uploading receipt: $e');
  }
}
回到顶部