Flutter订阅管理插件purchasely_flutter的使用

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

Flutter订阅管理插件purchasely_flutter的使用

标题

Flutter订阅管理插件purchasely_flutter的使用

内容

整理后的内容中尽量提供关于“Flutter订阅管理插件purchasely_flutter的使用”的完整示例demo。

示例代码

1 回复

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


当然,以下是如何在Flutter项目中使用purchasely_flutter插件进行订阅管理的示例代码。purchasely_flutter是一个用于集成和处理应用内购买(包括订阅)的Flutter插件。

前提条件

  1. 确保你的Flutter项目已经设置好。
  2. 在你的pubspec.yaml文件中添加purchasely_flutter依赖:
dependencies:
  flutter:
    sdk: flutter
  purchasely_flutter: ^最新版本号
  1. 运行flutter pub get来安装依赖。

初始化Purchasely

首先,你需要在你的应用中初始化Purchasely。这通常在你的主Activity或主Dart文件的initState方法中完成。

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

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

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

class PurchaselyExample extends StatefulWidget {
  @override
  _PurchaselyExampleState createState() => _PurchaselyExampleState();
}

class _PurchaselyExampleState extends State<PurchaselyExample> {
  @override
  void initState() {
    super.initState();
    _initializePurchasely();
  }

  Future<void> _initializePurchasely() async {
    try {
      // Replace 'YOUR_PUBLIC_KEY' with your actual Purchasely public key
      await PurchaselyFlutter.init('YOUR_PUBLIC_KEY');
      print('Purchasely initialized successfully');
    } catch (e) {
      print('Error initializing Purchasely: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Text('Purchasely initialized'),
    );
  }
}

获取订阅产品

在初始化Purchasely后,你可能需要获取订阅产品信息。

Future<void> _fetchSubscriptionProducts() async {
  try {
    List<PurchaselyProduct> products = await PurchaselyFlutter.getProducts([
      'subscription_product_id_1', // Replace with your actual product IDs
      'subscription_product_id_2',
    ]);
    
    products.forEach((product) {
      print('Product ID: ${product.productId}');
      print('Product Title: ${product.localizedTitle}');
      print('Product Description: ${product.localizedDescription}');
      print('Product Price: ${product.price}');
    });
  } catch (e) {
    print('Error fetching products: $e');
  }
}

购买订阅

一旦你有了产品信息,你可以让用户购买订阅。

Future<void> _purchaseSubscription(String productId) async {
  try {
    PurchaselyPurchaseResult result = await PurchaselyFlutter.purchase(productId);
    
    if (result.status == PurchaselyPurchaseStatus.purchased) {
      print('Subscription purchased successfully');
      // Handle successful purchase (e.g., update UI, save purchase token)
    } else if (result.status == PurchaselyPurchaseStatus.restored) {
      print('Subscription restored successfully');
      // Handle restored purchase (e.g., update UI)
    } else {
      print('Purchase failed: ${result.errorMessage}');
    }
  } catch (e) {
    print('Error purchasing subscription: $e');
  }
}

恢复订阅

用户可能希望恢复他们的订阅,尤其是在他们重新安装应用或换设备时。

Future<void> _restorePurchases() async {
  try {
    List<PurchaselyPurchaseResult> results = await PurchaselyFlutter.restorePurchases();
    
    results.forEach((result) {
      if (result.status == PurchaselyPurchaseStatus.restored) {
        print('Subscription restored: ${result.productId}');
        // Handle restored purchase (e.g., update UI)
      } else {
        print('Failed to restore purchase: ${result.errorMessage}');
      }
    });
  } catch (e) {
    print('Error restoring purchases: $e');
  }
}

完整示例

将上述代码片段整合到一个完整的示例中:

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

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

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

class PurchaselyExample extends StatefulWidget {
  @override
  _PurchaselyExampleState createState() => _PurchaselyExampleState();
}

class _PurchaselyExampleState extends State<PurchaselyExample> {
  @override
  void initState() {
    super.initState();
    _initializePurchasely();
  }

  Future<void> _initializePurchasely() async {
    try {
      await PurchaselyFlutter.init('YOUR_PUBLIC_KEY');
      print('Purchasely initialized successfully');
      _fetchSubscriptionProducts();
    } catch (e) {
      print('Error initializing Purchasely: $e');
    }
  }

  Future<void> _fetchSubscriptionProducts() async {
    try {
      List<PurchaselyProduct> products = await PurchaselyFlutter.getProducts([
        'subscription_product_id_1',
        'subscription_product_id_2',
      ]);
      
      // For simplicity, let's just purchase the first product
      if (products.isNotEmpty) {
        _purchaseSubscription(products.first.productId);
      }
    } catch (e) {
      print('Error fetching products: $e');
    }
  }

  Future<void> _purchaseSubscription(String productId) async {
    try {
      PurchaselyPurchaseResult result = await PurchaselyFlutter.purchase(productId);
      
      if (result.status == PurchaselyPurchaseStatus.purchased || result.status == PurchaselyPurchaseStatus.restored) {
        print('Subscription processed successfully');
        // Optionally, restore purchases on app start
        _restorePurchases();
      } else {
        print('Purchase failed: ${result.errorMessage}');
      }
    } catch (e) {
      print('Error purchasing subscription: $e');
    }
  }

  Future<void> _restorePurchases() async {
    try {
      List<PurchaselyPurchaseResult> results = await PurchaselyFlutter.restorePurchases();
      
      results.forEach((result) {
        if (result.status == PurchaselyPurchaseStatus.restored) {
          print('Subscription restored: ${result.productId}');
        } else {
          print('Failed to restore purchase: ${result.errorMessage}');
        }
      });
    } catch (e) {
      print('Error restoring purchases: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Text('Purchasely initialized and fetching products...'),
          ElevatedButton(
            onPressed: () {
              // Optionally, provide a button to restore purchases manually
              _restorePurchases();
            },
            child: Text('Restore Purchases'),
          ),
        ],
      ),
    );
  }
}

注意事项

  1. 替换占位符:确保替换所有YOUR_PUBLIC_KEYsubscription_product_id_X为实际的Purchasely公钥和订阅产品ID。
  2. 错误处理:在生产代码中,添加更详细的错误处理和用户反馈。
  3. 测试:在沙盒或测试环境中彻底测试你的购买流程。

这样,你就可以在你的Flutter应用中集成和使用purchasely_flutter插件来管理订阅了。

回到顶部