Phase 5 Xendit: Stages 1-7 (XENDIT_ENABLED=false; Stage 8 pending creds)

Backend
- payment_sessions → payment_requests rename across DB schema + 29 files
- payment.service.js becomes product-agnostic owner: EventEmitter +
  Xendit wrapper + requestPayment / confirmPayment public API; legacy
  aliases retained for existing chat callers
- Webhook handler at POST /api/shared/payment/webhooks/xendit, with
  constant-time token verification (8 vitest cases)
- Server-driven pairing: payment.service emits
  payment_request.confirmed → pairing subscriber starts the blast.
  Legacy POST /chat/request still works during the cutover.
- Reconciliation sweeper extended (re-emits events for confirmed rows
  with no chat session)
- SIGTERM drain + startup reconciliation pass in server.js

Customer app
- waiting_payment_screen opens xendit_invoice_url via
  LaunchMode.inAppBrowserView
- searching / no-bestie / targeted-waiting / pairing-notifier updated
  to consume the new payment_request_id contract
- pending_payments_provider + bestie-unavailable dialog migrated

Dev / testing
- XENDIT_ENABLED=false is the safe default; .env.example documents the
  four new vars
- backend/.dev/xendit-fake-webhook.sh exercises the handler without
  ngrok
- 90/92 backend tests pass (two pre-existing session-timer flakes,
  unrelated); client_app analyzer clean
- requirement/phase5-xendit-plan.md is the canonical reference

Stage 8 (live E2E) blocked on Xendit test-mode keys. The dashboard's
single-webhook-URL constraint will be worked around via a self-poll
script next session.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-25 12:52:33 +08:00
parent e6d991373e
commit 3fff4b1c6e
37 changed files with 2805 additions and 515 deletions

View File

@@ -48,14 +48,14 @@ class SessionClosure extends _$SessionClosure {
SessionClosureData build() => const ClosureInitialData();
/// Extension request is a 3-step flow with the extension cost held in its
/// own `payment_session` (never combined with a free trial). Server-side,
/// own `payment_request` (never combined with a free trial). Server-side,
/// the extension service refuses requests without an
/// `extension_payment_session_id` on a confirmed, is_extension payment session.
/// `extension_payment_request_id` on a confirmed, is_extension payment session.
///
/// 1. POST `/api/client/payment-sessions` with `is_extension: true`
/// 2. POST `/api/client/payment-sessions/:id/confirm`
/// 1. POST `/api/client/payment-requests` with `is_extension: true`
/// 2. POST `/api/client/payment-requests/:id/confirm`
/// 3. POST `/api/client/chat/session/:sessionId/extend` with the
/// extension_payment_session_id from step 2.
/// extension_payment_request_id from step 2.
///
/// Charge timing is server-side: only on actual approve / auto-approve.
/// If the mitra explicitly rejects within 10s the payment is failed back, no charge.
@@ -64,15 +64,15 @@ class SessionClosure extends _$SessionClosure {
try {
final api = ref.read(apiClientProvider);
final createResp = await api.post('/api/client/payment-sessions/', data: {
final createResp = await api.post('/api/client/payment-requests/', data: {
'duration_minutes': durationMinutes,
'is_extension': true,
});
final paymentSessionId = (createResp['data'] as Map<String, dynamic>)['id'] as String;
final paymentRequestId = (createResp['data'] as Map<String, dynamic>)['id'] as String;
// Backend rejects truly empty bodies on confirm, so always send `{}`.
await api.post(
'/api/client/payment-sessions/$paymentSessionId/confirm',
'/api/client/payment-requests/$paymentRequestId/confirm',
data: const <String, dynamic>{},
);
@@ -81,7 +81,7 @@ class SessionClosure extends _$SessionClosure {
await api.post('/api/client/chat/session/$sessionId/extend', data: {
'duration_minutes': durationMinutes,
'price': price,
'extension_payment_session_id': paymentSessionId,
'extension_payment_request_id': paymentRequestId,
});
} catch (e) {
state = const ClosureErrorData('Gagal meminta perpanjangan.');

View File

@@ -64,7 +64,7 @@ class ExtensionStatus {
ExtensionStatus._();
}
/// Session mode — chat or voice call. Mirrors backend `payment_sessions.mode`
/// Session mode — chat or voice call. Mirrors backend `payment_requests.mode`
/// (added in Phase 4 stage 1). A `call` session is functionally a chat with a
/// "voice call" badge and (eventually) a Meet link the mitra pastes manually;
/// no real audio transport is built yet.
@@ -153,7 +153,7 @@ enum PairingFailureCause {
targetedMitraOffline('targeted_mitra_offline'),
targetedMitraRejected('targeted_mitra_rejected'),
targetedMitraTimeout('targeted_mitra_timeout'),
paymentSessionExpired('payment_session_expired'),
paymentSessionExpired('payment_request_expired'),
customerCancelled('customer_cancelled'),
unknown('unknown');
@@ -165,13 +165,13 @@ enum PairingFailureCause {
}
/// Payment session lifecycle. Mirror of backend
/// `PaymentSessionStatus`.
class PaymentSessionStatus {
/// `PaymentRequestStatus`.
class PaymentRequestStatus {
static const pending = 'pending';
static const confirmed = 'confirmed';
static const consumed = 'consumed';
static const failedPairing = 'failed_pairing';
static const failedPairing = 'failed_delivery';
static const abandoned = 'abandoned';
static const expired = 'expired';
PaymentSessionStatus._();
PaymentRequestStatus._();
}

View File

@@ -23,12 +23,12 @@ class PairingInitialData extends PairingData {
/// General-blast in flight. The chat_session row exists; backend has already
/// notified all available mitras and is waiting for the first to accept.
class PairingSearchingData extends PairingData {
/// chat_session id (NOT payment_session id).
/// chat_session id (NOT payment_request id).
final String sessionId;
/// payment_session id — we keep it on the state so cancelSearch can call
/// payment_request id — we keep it on the state so cancelSearch can call
/// the payment-session-scoped cancel endpoint without re-prompting.
final String paymentSessionId;
final String paymentRequestId;
/// Carried so a retryable PAIRING_FAILED can preserve the customer's original
/// topic choice when looping back into Blast via retryBlast().
@@ -36,7 +36,7 @@ class PairingSearchingData extends PairingData {
const PairingSearchingData({
required this.sessionId,
required this.paymentSessionId,
required this.paymentRequestId,
required this.topicSensitivity,
});
}
@@ -49,7 +49,7 @@ class PairingSearchingData extends PairingData {
/// server is the source of truth for the actual auto-reject; the local timer
/// is purely cosmetic.
class PairingTargetedWaitingData extends PairingData {
final String paymentSessionId;
final String paymentRequestId;
final String mitraId;
final String mitraName;
final int secondsRemaining;
@@ -58,7 +58,7 @@ class PairingTargetedWaitingData extends PairingData {
final TopicSensitivity topicSensitivity;
const PairingTargetedWaitingData({
required this.paymentSessionId,
required this.paymentRequestId,
required this.mitraId,
required this.mitraName,
required this.secondsRemaining,
@@ -67,7 +67,7 @@ class PairingTargetedWaitingData extends PairingData {
PairingTargetedWaitingData copyWith({int? secondsRemaining}) {
return PairingTargetedWaitingData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraId: mitraId,
mitraName: mitraName,
secondsRemaining: secondsRemaining ?? this.secondsRemaining,
@@ -96,14 +96,14 @@ class PairingActiveData extends PairingData {
///
/// The UI surfaces this via the bestie-unavailable dialog.
class PairingTargetedUnavailableData extends PairingData {
final String paymentSessionId;
final String paymentRequestId;
final String mitraName;
final PairingFailureCause cause;
// Carried so the fallback-to-blast call preserves the customer's original choice.
final TopicSensitivity topicSensitivity;
const PairingTargetedUnavailableData({
required this.paymentSessionId,
required this.paymentRequestId,
required this.mitraName,
required this.cause,
required this.topicSensitivity,
@@ -114,11 +114,11 @@ class PairingTargetedUnavailableData extends PairingData {
///
/// `isRetryable=true` means the backend kept the payment session `confirmed`
/// (audit-only failure) so the customer can re-blast on the same payment via
/// `retryBlast()`. `isRetryable=false` means the payment is in `failed_pairing`
/// `retryBlast()`. `isRetryable=false` means the payment is in `failed_delivery`
/// and any retry must start from a fresh payment session.
class PairingFailedData extends PairingData {
final PairingFailureCause cause;
final String? paymentSessionId;
final String? paymentRequestId;
final bool isRetryable;
// Carried so retryBlast() can re-issue the blast with the customer's original
// topic choice. Null when the failure originated before any topic was known.
@@ -126,7 +126,7 @@ class PairingFailedData extends PairingData {
const PairingFailedData({
required this.cause,
this.paymentSessionId,
this.paymentRequestId,
this.isRetryable = false,
this.topicSensitivity,
});
@@ -156,7 +156,7 @@ class Pairing extends _$Pairing {
/// Returns once the chat_session row is created server-side; subsequent
/// transitions (paired / pairing_failed) arrive via WS.
Future<void> startSearch({
required String paymentSessionId,
required String paymentRequestId,
required TopicSensitivity topicSensitivity,
}) async {
state = const PairingInitialData();
@@ -165,7 +165,7 @@ class Pairing extends _$Pairing {
final response = await _apiClient.post(
'/api/client/chat/request',
data: {
'payment_session_id': paymentSessionId,
'payment_request_id': paymentRequestId,
'topic_sensitivity': topicSensitivity.value,
},
);
@@ -173,7 +173,7 @@ class Pairing extends _$Pairing {
final sessionId = data['id'] as String;
state = PairingSearchingData(
sessionId: sessionId,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
);
} on DioException catch (e) {
@@ -183,7 +183,7 @@ class Pairing extends _$Pairing {
// Backend already failed the payment in this case — terminal.
state = PairingFailedData(
cause: PairingFailureCause.noMitraAvailable,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
);
} else if (code == 'ALREADY_ACTIVE') {
state = const PairingErrorData('Kamu sudah memiliki sesi aktif.');
@@ -201,7 +201,7 @@ class Pairing extends _$Pairing {
/// row (payment stays confirmed) — we transition to TargetedUnavailable so
/// the UI can offer the fallback dialog.
Future<void> startTargetedSearch({
required String paymentSessionId,
required String paymentRequestId,
required String mitraId,
required String mitraName,
required TopicSensitivity topicSensitivity,
@@ -212,7 +212,7 @@ class Pairing extends _$Pairing {
final response = await _apiClient.post(
'/api/client/chat/chat-requests/returning',
data: {
'payment_session_id': paymentSessionId,
'payment_request_id': paymentRequestId,
'mitra_id': mitraId,
'topic_sensitivity': topicSensitivity.value,
},
@@ -222,7 +222,7 @@ class Pairing extends _$Pairing {
final sessionData = response['data'] as Map<String, dynamic>?;
final seconds = (sessionData?['confirmation_timeout_seconds'] as num?)?.toInt() ?? 20;
state = PairingTargetedWaitingData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraId: mitraId,
mitraName: mitraName,
secondsRemaining: seconds,
@@ -237,7 +237,7 @@ class Pairing extends _$Pairing {
// Intermediate — payment session is still confirmed; show the
// bestie-unavailable popup with a "Chat dengan bestie lain" option.
state = PairingTargetedUnavailableData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraName: mitraName,
cause: PairingFailureCause.targetedMitraOffline,
topicSensitivity: topicSensitivity,
@@ -251,17 +251,17 @@ class Pairing extends _$Pairing {
}
/// Customer-initiated cancel during a search/wait. Terminal — payment
/// session moves to `failed_pairing` server-side. We route the UI to home
/// session moves to `failed_delivery` server-side. We route the UI to home
/// (NOT to the failed-pairing screen) since the customer chose this.
Future<void> cancelSearch() async {
String? paymentSessionId;
String? paymentRequestId;
final current = state;
if (current is PairingSearchingData) {
paymentSessionId = current.paymentSessionId;
paymentRequestId = current.paymentRequestId;
} else if (current is PairingTargetedWaitingData) {
paymentSessionId = current.paymentSessionId;
paymentRequestId = current.paymentRequestId;
}
if (paymentSessionId == null) {
if (paymentRequestId == null) {
_cleanup();
state = const PairingCancelledData();
return;
@@ -269,7 +269,7 @@ class Pairing extends _$Pairing {
try {
await _apiClient.post(
'/api/client/chat/chat-requests/cancel',
data: {'payment_session_id': paymentSessionId},
data: {'payment_request_id': paymentRequestId},
);
} catch (_) {
// Best-effort. Backend will still fail the payment if/when it
@@ -283,21 +283,21 @@ class Pairing extends _$Pairing {
/// Reuses the same payment session — backend transitions back into the
/// general-blast path.
Future<void> fallbackToBlast({
required String paymentSessionId,
required String paymentRequestId,
required TopicSensitivity topicSensitivity,
}) async {
state = const PairingInitialData();
try {
await _connectWebSocket();
final response = await _apiClient.post(
'/api/client/chat/chat-requests/$paymentSessionId/fallback-to-blast',
'/api/client/chat/chat-requests/$paymentRequestId/fallback-to-blast',
data: {'topic_sensitivity': topicSensitivity.value},
);
final data = response['data'] as Map<String, dynamic>;
final sessionId = data['id'] as String;
state = PairingSearchingData(
sessionId: sessionId,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
);
} on DioException catch (e) {
@@ -306,7 +306,7 @@ class Pairing extends _$Pairing {
if (code == 'NO_MITRA_AVAILABLE') {
state = PairingFailedData(
cause: PairingFailureCause.noMitraAvailable,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
);
} else {
state = const PairingErrorData('Gagal memulai. Coba lagi.');
@@ -326,17 +326,17 @@ class Pairing extends _$Pairing {
/// `confirmed` (retryable failure). Re-blasts on the same payment session.
///
/// Caller should only invoke this when `state is PairingFailedData &&
/// state.isRetryable && paymentSessionId != null && topicSensitivity != null`.
/// state.isRetryable && paymentRequestId != null && topicSensitivity != null`.
Future<void> retryBlast() async {
final current = state;
if (current is! PairingFailedData
|| !current.isRetryable
|| current.paymentSessionId == null
|| current.paymentRequestId == null
|| current.topicSensitivity == null) {
return;
}
await startSearch(
paymentSessionId: current.paymentSessionId!,
paymentRequestId: current.paymentRequestId!,
topicSensitivity: current.topicSensitivity!,
);
}
@@ -388,7 +388,7 @@ class Pairing extends _$Pairing {
if (type == WsMessage.pairingFailed) {
final causeTag = data['cause_tag'] as String?;
final paymentSessionId = data['payment_session_id'] as String?;
final paymentRequestId = data['payment_request_id'] as String?;
// Missing flag = terminal (backward-compat with older emit sites). When
// false, the backend kept the payment confirmed and we can re-blast.
final isRetryable = data['is_terminal'] == false;
@@ -398,7 +398,7 @@ class Pairing extends _$Pairing {
_cleanup();
state = PairingFailedData(
cause: PairingFailureCause.fromString(causeTag),
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
isRetryable: isRetryable,
topicSensitivity: carriedTopic,
);
@@ -409,7 +409,7 @@ class Pairing extends _$Pairing {
// Intermediate — payment still confirmed. Show the bestie-unavailable
// dialog (UI surfaces via state listener).
_stopLocalCountdown();
final paymentSessionId = data['payment_session_id'] as String?;
final paymentRequestId = data['payment_request_id'] as String?;
// Pull mitra name + topic from the prior targeted-waiting state (we know it from
// the request payload). If we somehow lost it, fall back to safe defaults.
String mitraName = 'Bestie';
@@ -419,7 +419,7 @@ class Pairing extends _$Pairing {
carriedTopic = current.topicSensitivity;
}
state = PairingTargetedUnavailableData(
paymentSessionId: paymentSessionId ?? (current is PairingTargetedWaitingData ? current.paymentSessionId : ''),
paymentRequestId: paymentRequestId ?? (current is PairingTargetedWaitingData ? current.paymentRequestId : ''),
mitraName: mitraName,
topicSensitivity: carriedTopic,
cause: type == WsMessage.returningChatTimeout

View File

@@ -6,7 +6,7 @@ import '../../../core/pairing/pairing_notifier.dart';
/// Terminal failed-pairing screen.
///
/// Reached when the pairing notifier transitions to [PairingFailedData]
/// (terminal — payment session is `failed_pairing` server-side, audit row
/// (terminal — payment session is `failed_delivery` server-side, audit row
/// recorded). Copy is intentionally identical regardless of `cause_tag` for
/// now (the design pass will revise this later).
///

View File

@@ -70,7 +70,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
if (draft.targetedMitraId != null) {
// ignore: discarded_futures
ref.read(pairingProvider.notifier).startTargetedSearch(
paymentSessionId: draft.paymentId!,
paymentRequestId: draft.paymentId!,
mitraId: draft.targetedMitraId!,
mitraName: draft.targetedMitraName ?? 'Bestie',
topicSensitivity: draft.topicSensitivity,
@@ -80,7 +80,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
}
// ignore: discarded_futures
ref.read(pairingProvider.notifier).startSearch(
paymentSessionId: draft.paymentId!,
paymentRequestId: draft.paymentId!,
topicSensitivity: draft.topicSensitivity,
);
}
@@ -117,7 +117,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
context,
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
paymentRequestId: next.paymentRequestId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _unavailableDialogShown = false;

View File

@@ -64,7 +64,7 @@ class _TargetedWaitingScreenState extends ConsumerState<TargetedWaitingScreen> {
context,
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
paymentRequestId: next.paymentRequestId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _popupShown = false;

View File

@@ -23,7 +23,7 @@ import '../../support/widgets/tanya_admin_sheet.dart';
/// payment session exists yet, so the "cari bestie lain" CTA resets the
/// payment draft and pushes `/payment/entry` for a fresh blast-payment
/// flow. This branch never calls [Pairing.fallbackToBlast] because there's
/// no `paymentSessionId` to attach to.
/// no `paymentRequestId` to attach to.
/// - [BestieOfflineVariant.new_] — the customer triggered a general blast
/// that bottomed out (no online besties). No fallback button; just a
/// ghost `tanya admin` and a `kembali ke home` exit.
@@ -35,14 +35,14 @@ enum BestieOfflineVariant { returning, prePayReturning, new_ }
class BestieOfflinePopup extends ConsumerWidget {
final BestieOfflineVariant variant;
final String mitraName;
final String? paymentSessionId;
final String? paymentRequestId;
final TopicSensitivity? topicSensitivity;
const BestieOfflinePopup({
super.key,
required this.variant,
required this.mitraName,
this.paymentSessionId,
this.paymentRequestId,
this.topicSensitivity,
});
@@ -50,7 +50,7 @@ class BestieOfflinePopup extends ConsumerWidget {
BuildContext context, {
required BestieOfflineVariant variant,
required String mitraName,
String? paymentSessionId,
String? paymentRequestId,
TopicSensitivity? topicSensitivity,
}) {
return showDialog<void>(
@@ -60,7 +60,7 @@ class BestieOfflinePopup extends ConsumerWidget {
builder: (_) => BestieOfflinePopup(
variant: variant,
mitraName: mitraName,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
),
);
@@ -83,7 +83,7 @@ class BestieOfflinePopup extends ConsumerWidget {
final canFallbackToBlast = isReturning &&
hasOtherAvailable &&
paymentSessionId != null &&
paymentRequestId != null &&
topicSensitivity != null;
return Dialog(
@@ -145,7 +145,7 @@ class BestieOfflinePopup extends ConsumerWidget {
Navigator.of(context).pop();
// ignore: discarded_futures
ref.read(pairingProvider.notifier).fallbackToBlast(
paymentSessionId: paymentSessionId!,
paymentRequestId: paymentRequestId!,
topicSensitivity: topicSensitivity!,
);
},

View File

@@ -4,7 +4,7 @@ import '../../../core/auth/auth_notifier.dart';
/// One row in the Chat Tab > Pembayaran sub-tab.
///
/// Mirrors the response of `GET /api/client/payment-sessions/pending`. A row
/// Mirrors the response of `GET /api/client/payment-requests/pending`. A row
/// is either an initial-session payment (`isExtension == false`) — for which
/// mitra info is only present in the targeted "Curhat lagi" flow — or an
/// extension payment (`isExtension == true`) — mitra info resolved by the
@@ -80,7 +80,7 @@ final pendingPaymentsProvider =
if (customerId == null) return PendingPaymentsData.empty;
final api = ref.read(apiClientProvider);
final response =
await api.get('/api/client/payment-sessions/pending');
await api.get('/api/client/payment-requests/pending');
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()

View File

@@ -9,7 +9,7 @@ import '../../../core/theme/widgets/halo_button.dart';
import '../state/payment_draft_provider.dart';
/// "Cara bayar" — QRIS-first list of payment methods. On tap of `bayar`:
/// 1. POST `/api/client/payment-sessions` with the draft + chosen method.
/// 1. POST `/api/client/payment-requests` with the draft + chosen method.
/// 2. Push `/payment/waiting/:paymentId`.
class PaymentMethodScreen extends ConsumerStatefulWidget {
const PaymentMethodScreen({super.key});
@@ -72,7 +72,7 @@ class _PaymentMethodScreenState extends ConsumerState<PaymentMethodScreen> {
};
// Trailing slash matches the existing payment_notifier path — Fastify
// is not configured with `ignoreTrailingSlash`.
final response = await api.post('/api/client/payment-sessions/', data: body);
final response = await api.post('/api/client/payment-requests/', data: body);
final data = response['data'] as Map<String, dynamic>;
final paymentId = data['id'] as String;
ref.read(paymentDraftNotifierProvider.notifier).setPaymentId(paymentId);

View File

@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
@@ -36,6 +37,7 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
bool _initialLoading = true;
bool _terminal = false;
String? _error;
bool _invoiceUrlLaunched = false; // Phase 5: only auto-launch the Custom Tab once
Duration get _remaining {
final exp = _expiresAt;
@@ -80,11 +82,34 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
_qrPayload = (session['qr_string'] as String?) ?? widget.paymentId;
_initialLoading = false;
});
// Phase 5: when Xendit is on, the backend returns an `xendit_invoice_url`
// (Xendit's hosted checkout). Open it in a Custom Tab (Android) /
// SFSafariViewController (iOS) so the customer stays inside the app's
// browser context. Fire-and-forget — polling continues regardless.
// When Xendit is off (dev/Maestro), invoice_url is null and the QR fallback below is used.
await _maybeLaunchInvoiceUrl(session);
_maybeHandleStatus(session);
_startTicker();
_resumePolling();
}
Future<void> _maybeLaunchInvoiceUrl(Map<String, dynamic> session) async {
if (_invoiceUrlLaunched) return;
final url = (session['xendit_invoice_url'] as String?) ?? (session['invoice_url'] as String?);
if (url == null || url.isEmpty) return;
_invoiceUrlLaunched = true;
try {
await launchUrl(
Uri.parse(url),
mode: LaunchMode.inAppBrowserView, // Custom Tab on Android, SFVC on iOS
);
} catch (e) {
// Silent — polling will eventually resolve to expired if the customer can't pay.
// Don't surface an error toast; the user might have a non-Custom-Tab-capable env
// and url_launcher falls back to the system browser automatically.
}
}
void _startTicker() {
_ticker?.cancel();
_ticker = Timer.periodic(_tickInterval, (_) {
@@ -111,7 +136,7 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
Future<Map<String, dynamic>?> _fetchSession() async {
try {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/payment-sessions/${widget.paymentId}');
final response = await api.get('/api/client/payment-requests/${widget.paymentId}');
return response['data'] as Map<String, dynamic>?;
} catch (e) {
if (!mounted) return null;
@@ -122,12 +147,12 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
void _maybeHandleStatus(Map<String, dynamic> session) {
final status = session['status'] as String?;
if (status == PaymentSessionStatus.confirmed ||
status == PaymentSessionStatus.consumed) {
if (status == PaymentRequestStatus.confirmed ||
status == PaymentRequestStatus.consumed) {
_markTerminal();
_navigateTerminal('/onboarding/notif-gate');
} else if (status == PaymentSessionStatus.expired ||
status == PaymentSessionStatus.abandoned) {
} else if (status == PaymentRequestStatus.expired ||
status == PaymentRequestStatus.abandoned) {
_markTerminal();
_navigateTerminal('/payment/expired/${widget.paymentId}');
}