提问人:Axel Carachure 提问时间:11/13/2023 更新时间:11/13/2023 访问量:30
如何在 Flutter for Android 中使用 in_app_purchase 查看订阅状态?
How can I check the status of a subscription using in_app_purchase in Flutter for Android?
问:
我想知道如何检查用户是否具有有效的订阅。在这种情况下,我创建了一个 1 个月的订阅,一切正常。但是,我可以通过什么方式确定用户的订阅是否仍处于活动状态?我正在使用 in_app_purchase 库,我注意到访问过去购买的方式已更新。在我的代码中,我将行 updating 修改为 .尽管进行了此修复,我仍然收到错误,因为未定义“PurchaserInfo”。另外,我不确定我是否以正确的方式实现了这一点,因为这是我第一次在 Flutter 中使用订阅。我提前感谢任何指导或帮助。谢谢!:)final PurchaserInfo purchaserInfo = await InAppPurchase.instance.queryPastPurchases();
InAppPurchaseConnection.instance
InAppPurchase.instance
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:shared_preferences/shared_preferences.dart';
class SubscriptionStatusChecker extends StatefulWidget {
@override
_SubscriptionStatusCheckerState createState() =>
_SubscriptionStatusCheckerState();
}
class _SubscriptionStatusCheckerState extends State<SubscriptionStatusChecker> {
bool _isSubscriptionActive = false;
@override
void initState() {
super.initState();
_checkSubscriptionStatus();
}
Future<void> _checkSubscriptionStatus() async {
try {
final PurchaserInfo purchaserInfo = await InAppPurchase.instance
.queryPastPurchases();
final List<PurchaseDetails> purchases =
purchaserInfo.purchases.toList();
for (var purchase in purchases) {
if (purchase.productID == 's2424' &&
purchase.status == PurchaseStatus.purchased) {
setState(() {
_isSubscriptionActive = true;
});
break;
}
}
} catch (e) {
Fluttertoast.showToast(
msg: 'Error: $e',
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
);
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Subscription Status Checker'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Estado de la suscripción:',
style: TextStyle(fontSize: 18),
),
Text(
_isSubscriptionActive ? 'Activa' : 'Inactiva',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
],
),
),
);
}
}
class UpdatePlan extends StatefulWidget {
@override
_UpdatePlanScreenState createState() => _UpdatePlanScreenState();
}
class _UpdatePlanScreenState extends State<UpdatePlan> {
final InAppPurchase _inAppPurchase = InAppPurchase.instance;
final FirebaseFirestore _firestore = FirebaseFirestore.instance;
static const String _productId = 's2424'
final StreamController<List<PurchaseDetails>> _purchaseUpdatedController =
StreamController<List<PurchaseDetails>>.broadcast();
Stream<List<PurchaseDetails>> get purchaseUpdatedStream =>
_purchaseUpdatedController.stream;
late StreamSubscription<List<PurchaseDetails>> _subscription;
bool _isPlanPremiumActive = false;
bool get isPlanPremiumActive => _isPlanPremiumActive;
String? _username;
@override
void initState() {
super.initState();
_loadUsername();
initialize();
}
void _loadUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
_username = prefs.getString('username');
});
}
void initialize() async {
final bool available = await _inAppPurchase.isAvailable();
if (!available) {
// The store is not available. Update the UI accordingly.
return;
}
await _inAppPurchase.restorePurchases();
_subscription = _inAppPurchase.purchaseStream.listen((purchaseDetailsList) {
_handlePurchases(purchaseDetailsList);
}, onDone: () {
_subscription.cancel();
}, onError: (error) {
// Handle errors here.
});
}
void _handlePurchases(List<PurchaseDetails> purchaseDetailsList) {
for (var purchaseDetails in purchaseDetailsList) {
if (purchaseDetails.status == PurchaseStatus.purchased) {
if (purchaseDetails.productID == _productId) {
_grantPlanPremium();
_updateFirebaseSubscription(purchaseDetails);
}
} else if (purchaseDetails.status == PurchaseStatus.error) {
Fluttertoast.showToast(
msg: 'Error al realizar la compra: ${purchaseDetails.error}',
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
);
}
}
_purchaseUpdatedController.add(purchaseDetailsList);
}
void _grantPlanPremium() {
setState(() {
_isPlanPremiumActive = true;
});
}
Future<void> purchaseProduct() async {
try {
final PurchaseParam purchaseParam =
PurchaseParam(productDetails: await _getProductDetails());
await _inAppPurchase.buyNonConsumable(purchaseParam: purchaseParam);
} catch (error) {
Fluttertoast.showToast(
msg: 'Error al iniciar la compra: $error',
gravity: ToastGravity.BOTTOM,
timeInSecForIosWeb: 1,
backgroundColor: Colors.red,
textColor: Colors.white,
);
}
}
Future<ProductDetails> _getProductDetails() async {
final Set<String> ids = <String>{_productId};
final ProductDetailsResponse response =
await _inAppPurchase.queryProductDetails(ids);
return response.productDetails.first;
}
void _updateFirebaseSubscription(PurchaseDetails purchaseDetails) {
if (_username != null) {
_firestore.collection('users').doc(_username).update({
'subscription': true,
});
}
}
@override
void dispose() {
_subscription.cancel();
_purchaseUpdatedController.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Test'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Premium Plan: ${_isPlanPremiumActive ? 'Active' : 'Inactive'}',
style: TextStyle(fontSize: 18),
),
ElevatedButton(
onPressed: () => purchaseProduct(),
child: Text('Update VIP'),
),
ElevatedButton(
onPressed: () => SubscriptionStatusChecker(),
child: Text('Status'),
),
],
),
),
);
}
}
我看到了这个线程,但是,它没有响应: 如何使用in_app_purchase检查用户是否有活动订阅 我的期望是能够确定用户是否具有活动订阅。
答: 暂无答案
评论