49 lines
1.2 KiB
Dart
49 lines
1.2 KiB
Dart
import 'dart:async';
|
|
import 'dart:js_interop';
|
|
|
|
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
|
import 'package:web/web.dart' as web;
|
|
|
|
const String _defaultGatewayScriptUrl =
|
|
'https://test-gateway.mastercard.com/static/checkout/checkout.min.js';
|
|
|
|
@JS('Checkout')
|
|
external JSAny? _checkout;
|
|
|
|
@JS('configure')
|
|
external void configure(String sessionID);
|
|
|
|
@JS('showEmbeddedPage')
|
|
external void showEmbeddedPage();
|
|
|
|
Future<void> ensureCheckoutScriptLoaded() async {
|
|
final existing = web.document.querySelector('#mastercard-checkout-script');
|
|
if (existing is web.HTMLScriptElement) {
|
|
await _waitForCheckout();
|
|
return;
|
|
}
|
|
|
|
final scriptUrl =
|
|
dotenv.env['GATEWAY_SCRIPT_URL'] ?? _defaultGatewayScriptUrl;
|
|
|
|
final scriptElement = web.HTMLScriptElement()
|
|
..id = 'mastercard-checkout-script'
|
|
..src = scriptUrl
|
|
..async = true;
|
|
|
|
web.document.head?.append(scriptElement);
|
|
await _waitForCheckout();
|
|
}
|
|
|
|
Future<void> _waitForCheckout() async {
|
|
const maxAttempts = 100;
|
|
for (var attempt = 0; attempt < maxAttempts; attempt++) {
|
|
if (_checkout != null) {
|
|
return;
|
|
}
|
|
await Future.delayed(const Duration(milliseconds: 100));
|
|
}
|
|
|
|
throw StateError('Mastercard Checkout script failed to load before timeout.');
|
|
}
|