Files
pluriwave/lib/servicios/servicio_compras.dart
T
Javier Bautista Fernández 0b7919e72e
Build & Deploy PluriWave / Análisis de código (push) Successful in 41s
Build & Deploy PluriWave / Build APK + AAB release (push) Successful in 4m8s
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.
2026-09-18 11:45:43 +02:00

276 lines
10 KiB
Dart

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
/// [EstadoEntitlement] never imports the plugin package directly — the SAME
/// port-boundary discipline `PuertoAlarmasAndroid` already applies.
enum TipoEventoCompra {
/// A fresh purchase completed successfully.
comprada,
/// [PuertoCompras.restaurar] found a prior purchase.
restaurada,
/// The user cancelled the purchase flow before it completed.
cancelada,
/// The purchase/restore flow failed (network, billing error, etc).
error,
/// [PuertoCompras.restaurar] completed with nothing to restore — NOT an
/// error (Spec "Restore finds nothing").
noEncontrada,
/// A purchase is in-flight (billing dialog shown, awaiting the user).
pendiente,
}
/// A single purchase-stream event (Design ADR-2). [mensaje] is populated
/// only for [TipoEventoCompra.error], for diagnostics/logging — never shown
/// to the user verbatim.
class EventoCompra {
const EventoCompra(this.tipo, {this.mensaje});
final TipoEventoCompra tipo;
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
/// keeps Strict TDD viable with zero plugin channels in unit tests.
abstract class PuertoCompras {
/// Broadcasts every purchase-flow outcome (Design ADR-2) — [comprar] and
/// [restaurar] do not return the outcome directly because
/// `in_app_purchase`'s own API is stream-based (a purchase can complete
/// asynchronously well after the call that started it, e.g. after leaving
/// and returning to the app).
Stream<EventoCompra> get eventos;
/// Starts the one-time non-consumable purchase flow.
Future<void> comprar();
/// 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,
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) {
debugPrint('[PluriWave][compras] purchaseStream ERROR $error');
_eventos.add(
EventoCompra(TipoEventoCompra.error, mensaje: error.toString()),
);
},
);
}
/// The single non-consumable product id (Design "Interfaces / Contracts").
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;
@override
Stream<EventoCompra> get eventos => _eventos.stream;
@override
Future<void> comprar() async {
try {
final disponible = await _iap.isAvailable();
if (!disponible) {
_eventos.add(
const EventoCompra(
TipoEventoCompra.error,
mensaje: 'Play Billing no disponible',
),
);
return;
}
final respuesta = await _iap.queryProductDetails({idProducto});
final detalle = respuesta.productDetails.firstOrNull;
if (detalle == null) {
_eventos.add(
const EventoCompra(
TipoEventoCompra.error,
mensaje: 'Producto no encontrado en Play Console',
),
);
return;
}
final parametros = PurchaseParam(productDetails: detalle);
await _iap.buyNonConsumable(purchaseParam: parametros);
} catch (e) {
debugPrint('[PluriWave][compras] comprar ERROR $e');
_eventos.add(EventoCompra(TipoEventoCompra.error, mensaje: e.toString()));
}
}
@override
Future<void> restaurar() async {
try {
await _iap.restorePurchases();
} catch (e) {
debugPrint('[PluriWave][compras] restaurar ERROR $e');
_eventos.add(EventoCompra(TipoEventoCompra.error, mensaje: e.toString()));
}
}
@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
// (`in_app_purchase_android` does `_purchaseUpdatedController.add(
// pastPurchases)` unconditionally) — there is no per-call correlation
// in this stream, so this fires on ANY empty batch. In practice
// `restorePurchases` on an account with nothing to restore is the only
// source of an empty batch this stream would ever emit.
//
// Returning silently here (as this did before) left
// [TipoEventoCompra.noEncontrada] NEVER emitted, so
// `EstadoEntitlement._compraEnCurso` stayed `true` forever and
// `hoja_premium.dart` kept BOTH buttons disabled — restore AND buy.
// A paywall that cannot be paid.
_eventos.add(const EventoCompra(TipoEventoCompra.noEncontrada));
return;
}
for (final compra in compras) {
_eventos.add(
eventoDesdeEstadoCompra(compra.status, mensaje: compra.error?.message),
);
if (compra.pendingCompletePurchase) {
unawaited(_iap.completePurchase(compra));
}
}
}
Future<void> dispose() async {
await _sub?.cancel();
await _eventos.close();
}
}
/// Pure mapping from `in_app_purchase`'s [PurchaseStatus] to the
/// PluriWave-owned [EventoCompra] (Design ADR-2's port boundary): pulled out
/// of [ServicioComprasPlayBilling] so it is unit-testable with zero plugin
/// channels, mirroring how `servicio_audio.dart` extracts its pure mapping
/// helpers (e.g. `mapearEstadoProceso`) out of the un-instantiable handler.
EventoCompra eventoDesdeEstadoCompra(PurchaseStatus status, {String? mensaje}) {
return switch (status) {
PurchaseStatus.pending => const EventoCompra(TipoEventoCompra.pendiente),
PurchaseStatus.purchased => const EventoCompra(TipoEventoCompra.comprada),
PurchaseStatus.restored => const EventoCompra(TipoEventoCompra.restaurada),
PurchaseStatus.error => EventoCompra(
TipoEventoCompra.error,
mensaje: mensaje,
),
PurchaseStatus.canceled => const EventoCompra(TipoEventoCompra.cancelada),
};
}
/// 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;
}