fix(compras): revocar el PRO tras un reembolso sin penalizar a quien pago
Verificacion silenciosa en segundo plano con queryPastPurchases, al abrir o volver a la app y al cargar Android Auto. Solo revoca tras dos respuestas validas de Play sin la compra separadas 12h; sin red o con error no toca nada. Reactiva el PRO automaticamente si Play confirma la compra.
This commit is contained in:
@@ -2,6 +2,7 @@ import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart' show debugPrint;
|
||||
import 'package:in_app_purchase/in_app_purchase.dart';
|
||||
import 'package:in_app_purchase_android/in_app_purchase_android.dart';
|
||||
|
||||
/// Outcome kinds the purchase stream can report (Design ADR-2). Mirrors
|
||||
/// `in_app_purchase`'s [PurchaseStatus] but stays a PluriWave-owned type so
|
||||
@@ -38,6 +39,25 @@ class EventoCompra {
|
||||
final String? mensaje;
|
||||
}
|
||||
|
||||
/// Outcome of the SILENT ownership query ([PuertoCompras.consultarPropiedad])
|
||||
/// used to re-verify the persisted premium flag (refund revocation).
|
||||
///
|
||||
/// Only [poseida] and [noPoseida] are definitive answers from Play; anything
|
||||
/// that is not a clean answer (offline, billing unavailable, query error,
|
||||
/// exception, timeout, pending purchase) is [desconocido], which the
|
||||
/// verification policy treats as "change nothing" (fail-open, ADR-2).
|
||||
enum ResultadoVerificacionLicencia {
|
||||
/// Play reports the premium product as purchased on this account.
|
||||
poseida,
|
||||
|
||||
/// Play answered successfully and the premium product is NOT among the
|
||||
/// account's purchases (e.g. refunded or revoked).
|
||||
noPoseida,
|
||||
|
||||
/// No trustworthy answer — never used to revoke.
|
||||
desconocido,
|
||||
}
|
||||
|
||||
/// Purchase I/O abstraction (Design ADR-2): [EstadoEntitlement] depends on
|
||||
/// this port, never on `in_app_purchase` directly — matches
|
||||
/// `EstadoAlarmas(android: PuertoAlarmasAndroid)`'s injection shape, and
|
||||
@@ -55,13 +75,24 @@ abstract class PuertoCompras {
|
||||
|
||||
/// Re-queries Play Billing for a prior purchase on this account.
|
||||
Future<void> restaurar();
|
||||
|
||||
/// Silently asks the store whether this account currently owns the
|
||||
/// premium product. Unlike [restaurar], it NEVER emits on [eventos] (the
|
||||
/// premium sheet listens there) and never throws: every failure maps to
|
||||
/// [ResultadoVerificacionLicencia.desconocido].
|
||||
Future<ResultadoVerificacionLicencia> consultarPropiedad();
|
||||
}
|
||||
|
||||
/// The SOLE `in_app_purchase` call site (Design ADR-2) — every other file
|
||||
/// depends on [PuertoCompras] instead.
|
||||
class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
ServicioComprasPlayBilling({InAppPurchase? inAppPurchase})
|
||||
: _iap = inAppPurchase ?? InAppPurchase.instance {
|
||||
ServicioComprasPlayBilling({
|
||||
InAppPurchase? inAppPurchase,
|
||||
Future<QueryPurchaseDetailsResponse> Function()? consultarComprasPasadas,
|
||||
Duration limiteConsultaPropiedad = const Duration(seconds: 10),
|
||||
}) : _iap = inAppPurchase ?? InAppPurchase.instance,
|
||||
_consultarComprasPasadasInyectada = consultarComprasPasadas,
|
||||
_limiteConsultaPropiedad = limiteConsultaPropiedad {
|
||||
_sub = _iap.purchaseStream.listen(
|
||||
_alRecibirCompras,
|
||||
onError: (Object error) {
|
||||
@@ -77,6 +108,15 @@ class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
static const idProducto = 'pluriwave_premium';
|
||||
|
||||
final InAppPurchase _iap;
|
||||
|
||||
/// Test seam for [consultarPropiedad]; `null` in production, where the
|
||||
/// Android platform addition's `queryPastPurchases` is used.
|
||||
final Future<QueryPurchaseDetailsResponse> Function()?
|
||||
_consultarComprasPasadasInyectada;
|
||||
|
||||
/// Upper bound for [consultarPropiedad]: a hung BillingClient connection
|
||||
/// resolves to [ResultadoVerificacionLicencia.desconocido].
|
||||
final Duration _limiteConsultaPropiedad;
|
||||
final _eventos = StreamController<EventoCompra>.broadcast();
|
||||
StreamSubscription<List<PurchaseDetails>>? _sub;
|
||||
|
||||
@@ -125,6 +165,33 @@ class ServicioComprasPlayBilling implements PuertoCompras {
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ResultadoVerificacionLicencia> consultarPropiedad() async {
|
||||
try {
|
||||
final disponible = await _iap.isAvailable().timeout(
|
||||
_limiteConsultaPropiedad,
|
||||
);
|
||||
if (!disponible) return ResultadoVerificacionLicencia.desconocido;
|
||||
final consultar =
|
||||
_consultarComprasPasadasInyectada ??
|
||||
() =>
|
||||
_iap
|
||||
.getPlatformAddition<InAppPurchaseAndroidPlatformAddition>()
|
||||
.queryPastPurchases();
|
||||
// `queryPastPurchases` reads the account's purchases straight from
|
||||
// the BillingClient: unlike `restorePurchases` it does NOT push them
|
||||
// into `purchaseStream`, so the premium sheet never sees this check.
|
||||
final respuesta = await consultar().timeout(_limiteConsultaPropiedad);
|
||||
return resultadoDesdeComprasPasadas(
|
||||
respuesta.pastPurchases,
|
||||
conError: respuesta.error != null,
|
||||
);
|
||||
} catch (e) {
|
||||
debugPrint('[PluriWave][compras] consultarPropiedad -> desconocido $e');
|
||||
return ResultadoVerificacionLicencia.desconocido;
|
||||
}
|
||||
}
|
||||
|
||||
void _alRecibirCompras(List<PurchaseDetails> compras) {
|
||||
if (compras.isEmpty) {
|
||||
// `restorePurchases()` with nothing to restore pushes an EMPTY batch
|
||||
@@ -176,6 +243,33 @@ EventoCompra eventoDesdeEstadoCompra(PurchaseStatus status, {String? mensaje}) {
|
||||
};
|
||||
}
|
||||
|
||||
/// Pure mapping from a `queryPastPurchases` answer to the typed ownership
|
||||
/// result (same port-boundary rationale as [eventoDesdeEstadoCompra]).
|
||||
///
|
||||
/// The premium product present as purchased/restored is proof of ownership
|
||||
/// even when the answer also carries an error (the query spans in-app AND
|
||||
/// subscriptions, and a failure of the latter is irrelevant here). A pending
|
||||
/// entry is not a clean answer. Absence only counts as [noPoseida] when the
|
||||
/// query succeeded without error.
|
||||
ResultadoVerificacionLicencia resultadoDesdeComprasPasadas(
|
||||
List<PurchaseDetails> compras, {
|
||||
required bool conError,
|
||||
}) {
|
||||
final delProducto = compras.where(
|
||||
(c) => c.productID == ServicioComprasPlayBilling.idProducto,
|
||||
);
|
||||
final comprada = delProducto.any(
|
||||
(c) =>
|
||||
c.status == PurchaseStatus.purchased ||
|
||||
c.status == PurchaseStatus.restored,
|
||||
);
|
||||
if (comprada) return ResultadoVerificacionLicencia.poseida;
|
||||
if (conError || delProducto.isNotEmpty) {
|
||||
return ResultadoVerificacionLicencia.desconocido;
|
||||
}
|
||||
return ResultadoVerificacionLicencia.noPoseida;
|
||||
}
|
||||
|
||||
extension<T> on List<T> {
|
||||
T? get firstOrNull => isEmpty ? null : first;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user