在Flutter中使用ONE store In-App Library(内部应用程序库)

概要

ONE store支付插件(plugin)通过在plotter环境中展现的应用程序(app), 为您提供ONE store 支付插件的最新功能。

本指南为你提供使用插件的方法和展现ONE store支付插件功能的方法。

安装插件

在pubspec.yaml文件中加入插件的方法

dependencids:
  ..
  flutter_onestore_inapp: ^0.1.0
  ..

点击'pub get'下载程序包或者在命令行运行'flutter pub get'。

加入build.gradle从属性

在project的build.gradle中加入maven地址

allprojects {
    repositories {
        ..
        maven { url 'https://repo.onestore.co.kr/repository/onestore-sdk-public' }
    }
}

在app的build.gradle 中加入configuration从属性

dependencies {
	..
    implementation "com.onestorecorp.sdk:sdk-configuration-kr:1.0.0"
    ..
}

在AndroidManifest.xml中加入<queries>

<manifest>
    ...
    <queries>
        <intent>
            <action android:name="com.onestore.ipc.iap.IapService.ACTION" />
        </intent>
        <intent>
            <action android:name="android.intent.action.VIEW" />

            <data android:scheme="onestore" />
        </intent>
    </queries>
    ...
    <application>
        ...
    </application>
</manifest>

请求登录

ONE store内部app支付是需要登录才能启动的服务。首次开始启动app时,在唤起购买库的API之前,先诱导登录。

可以提前预防请求购买库时出现token过期和其他各种状况。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  final OneStoreAuthClient _authClient = OneStoreAuthClient();

  Future<void> launchSignInFlow() async {
    await _authClient.launchSignInFlow().then((signInResult) {
      if (signInResult.isSuccess()) {
        // success
      }
    });
  }

在App中更新购买信息以及读取出错回复

展现PurchasesUpdatedStream 回复

本对象(object)需要在app启动时直接更新购买,所以需要使用'lazy: false',让针对本对象的'Lazy loading'处于非唤起状态。

ChangeNotifierProvider<PurchaseViewModel>(
    create: (context) => PurchaseViewModel(),
    lazy: false,
)

颁发证书(license)密钥

在ONE store研发者中心登录app,就会生成证书密钥

通过唤起PurchaseClientManager.initialize()在第一次建立对象。

在'purchasesUpdatedStream' 字符串中'listen',准备获取购买结束的回复。

以_listenToPurchasesUpdated成功购买,获取购买信息的回复。

以_updateStreamOnError ,获取购买失败的回复。

App结束时,唤起'PurchaseClientManager.dispose()' 解除内存及解除连接,同时已经读取的_purchaseUpdatedStream也需要dispose(),以此断开连接。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

class PurchaseViewModel extends ChangeNotifier {

  final OneStoreAuthClient _authClient = OneStoreAuthClient();
  final PurchaseClientManager _clientManager = PurchaseClientManager.instance;

  late StreamSubscription<List<PurchaseData>> _purchaseUpdatedStream;

  PurchaseViewModel() {
    _clientManager.initialize('input your license key');
    
    _purchaseUpdatedStream = _clientManager.purchasesUpdatedStream.listen(
      _listenToPurchasesUpdated,
      onError: _updateStreamOnError,
      onDone: () => _purchaseDataStream.cancel(),
    );
  }

  @override
  void dispose() {
    _purchaseDataStream.cancel();
    _clientManager.dispose();
    super.dispose();
  }

  void _listenToPurchasesUpdated(List<PurchaseData> purchasesList) {
    // Handle purchases here
  }

  void _updateStreamOnError(dynamic error) {
    // Handle error here
  }

  Future<IapResult> launchPurchaseFlow(ProductDetail productDetail,
      int? quantity, String? developerPayload) async {
    return await _clientManager.launchPurchaseFlow(
        productDetail: productDetail,
        quantity: quantity,
        developerPayload: developerPayload
    );
  }

  Future<SignInResult> launchSignInFlow() async {
     return await _authClient.launchSignInFlow();
  }
}

查询商品详细信息

使用'await _clientManager.queryProductDetails(List<String>, ProductType)'请求获取ONE store研发者中心登录的内部app商品的详细信息。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  static const consumableIds = ['p500', 'p510'];
  static const subscriptionIds = ['week', 'month', 'three_month'];
  
  final List<ProductDetail> _products = [];
  
  Future<void> fetchProductDetails() async {
    var responses = await Future.wait(<Future<ProductDetailsResponse>>[
      _clientManager.queryProductDetails(
          productIds: consumableIds, productType: ProductType.inapp),
      _clientManager.queryProductDetails(
          productIds: subscriptionIds, productType: ProductType.subs)
    ]);
  
    if (responses.first.iapResult.isSuccess()) {
      final List<ProductDetail> result =
          responses.expand((element) => element.productDetailsList).toList();
      _products.clear();
      _products.addAll(result);
      notifyListeners();
    } else {
      _handleError('fetchProductDetails', responses.first.iapResult);
    }
  
    /// WARNING! 请求信息太多时,若一次请求可能会产生回复延迟。
    /// 但是请求信息少时,一次性请求更有效率。
    // var allResponse = await _clientManager.queryProductDetails(
    //     productIds: (consumableIds + subscriptionIds),
    //     productType: ProductType.all);
    // 
    // if (allResponse.iapResult.isSuccess()) {
    //   final List<ProductDetail> result = allResponse.productDetailsList;
    //   _products.clear();
    //   _products.addAll(result);
    //   notifyListeners();
    // } else {
    //   _handleError('fetchProductDetails', allResponse.iapResult);
    // }
  }

请求购买

使用'await _clientManager.launchPurchaseFlow(ProductDetail)'请求商品购买。

Parameter

Type

Description

productDetail

ProductDetail

将购买商品的详细信息

quantity

Int

重复购买时使用

基本参数 : 1

developerPayload

String

作为研发公司输入信息的需要信息,若在请求购买时被同时传送,购买结果(PurchaseData.developerPayload )中(该信息)也将被包含一起传送。

限制事项 : max 200byte

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<IapResult> launchPurchaseFlow(ProductDetail productDetail,
      int? quantity, String? developerPayload) async {
    return await _clientManager.launchPurchaseFlow(
        productDetail: productDetail,
        quantity: quantity,
        developerPayload: developerPayload);
  }

购买后处理

若购买成功,可以通过“在APP中更新购买信息以及读取出错回复”中登录的'_listenToPurchasesUpdated' 获取回复。

当然购买失败的回复也可以通过'_updateStreamOnError'获取。

若在store中获取到购买结束的回复,接下来消费(consume)或确认(acknowledge)的工作非常重要。

若3天内购买没有确认(acknowledge)或消费(consume),会判断为未向用户支付商品,自动返款给用户。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  List<ProductDetail> get consumableProducts;
  List<ProductDetail> get subscriptionProducts

  Future<void> _listenToPurchasesUpdated(List<PurchaseData> purchasesList) async {
    for (var element in purchasesList) {
      if (consumableProducts.any((p) => p.productId == element.productId)) {
        /// [ProductType.inapp] 상품은 [consumePurchase] 호출을 하여 소비 해야합니다.
        await consumePurchase(element);
      } else if (subscriptionProducts.any((p) => p.productId == element.productId)) {
        /// [ProductType.subs] 상품은 [acknowledgePurchase] 호출을 하여 확인 해야합니다.
        await acknowledgePurchase(element);
      }
    }
    notifyListeners();
  }

购买消费(consume)

使用'_clientManager.consumePurchase(PurchaseData)'请求管理型商品的消费。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<void> consumePurchase(PurchaseData purchaseData) async {
    await _clientManager
        .consumePurchase(purchaseData: purchaseData)
        .then((iapResult) {
      // iapResult 를 통해 해당 API의 성공 여부를 판단할 수 있습니다.
      if (iapResult.isSuccess()) {
        fetchPurchases([ProductType.inapp]);
      }
    });
  }

购买确认(acknowledge)

使用'_clientManager.acknowledgePurchase(PurchaseData)'请求管理型商品或订阅商品的确认。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<void> acknowledgePurchase(PurchaseData purchaseData) async {
    await _clientManager
        .acknowledgePurchase(purchaseData: purchaseData)
        .then((iapResult) {
      // iapResult 를 통해 해당 API의 성공 여부를 판단할 수 있습니다.
      if (iapResult.isSuccess()) {
        fetchPurchases([ProductType.subs]);
      }
    });
  }

查询购买明细

使用'_clientManager.queryPurchases(ProductType)',请求未消费的购买明细。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<void> fetchPurchases([List<ProductType>? types]) async {
    types ??= <ProductType>[ProductType.inapp, ProductType.subs];
    for (var element in types) {
      await _clientManager
          .queryPurchases(productType: element)
          .then((response) {
        if (response.iapResult.isSuccess()) {
          if (element == ProductType.inapp) {
            for (var purchaseData in response.purchasesList) {
              consumePurchase(purchaseData);
            }
          } else if (element == ProductType.subs) {
            for (var purchaseData in response.purchasesList) {
              if (!purchaseData.isAcknowledged) {
                acknowledgePurchase(purchaseData);
              }
            }
          }
          notifyListeners();
        } else {
          _handleError('fetchPurchases($element)', response.iapResult);
        }
      });
    }
  }

更新或下载更新

使用'_clientManager.launchUpdateSubscription(ProductDetail, PurchaseData, ProrationMode)' 将购买的定期支付商品变更为新商品。

Upgrade or Downgrade 和请求购买流程相同,所以和“请求购买”的回复处理方式相同。

可以通过'_listenToPurchasesUpdated'获取回复。

Parameter

Type

Description

productDetail

ProductDetail

将变更的订阅商品的信息

oldPurchseData

PurchaseData

将成为变更对象的订阅商品的购买信息

prorationMode

ProrationMode

变更原有订阅购买信息时可以适用的模式

(详细信息参考原有指南)

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<IapResult> launchUpdateSubscription(ProductDetail productDetail,
      PurchaseData oldPurchaseData, ProrationMode prorationMode) async {
    return await _clientManager.launchUpdateSubscription(
        productDetail: productDetail,
        oldPurchaseData: oldPurchaseData,
        prorationMode: prorationMode);
  }

打开定期支付管理画面

使用'_clientManager.launchManageSubscription(PurchaseData?)'可以移动到购买的订阅商品的详细内容网页。

订阅商品的设置变更是用户处理,管理菜单中能做的如下。

  • 支付方式变更

  • 订阅状态变更(解除预约,取消)

  • 同意原有订阅商品的价格变更

PurchaseData请求null时,将不出现购买商品的详细内容网页,而是移动到定期支付目录画面。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<void> launchManageSubscription(PurchaseData? purchaseData) async {
    await _clientManager.launchManageSubscription(purchaseData);
  }

安装 ONE store服务

ONE store服务无法安装或不是v21 SDK中支持的最低版本时,RESULT_NEED_UPDATE中会发生错误(error)。

收到相应错误(error)时,使用'_clientManager.launchUpdateOrInstall()',请求安装ONE store服务。

import 'package:flutter_onestore_inapp/onestore_in_app_wrappers.dart';

  Future<void> launchUpdateOfInstall() async {
    await _clientManager.launchUpdateOrInstall().then((iapResult) {
      if (iapResult.isSuccess()) {
        fetchPurchases();
        fetchProductDetails();
      }
    });
  }

Last updated