/// Server-side only. Never compile a partner API key into Flutter/Web clients. library; import 'dart:async'; import 'dart:convert'; import 'dart:typed_data'; import 'package:http/http.dart' as http; class QrApiException implements Exception { final int statusCode; final String code; const QrApiException(this.statusCode, this.code); @override String toString() => 'QrApiException($statusCode, $code)'; } class QrOrder { final Map json; QrOrder(Map value) : json = Map.unmodifiable(value) { if (value['id'] is! String || !RegExp(r'^[a-f0-9]{20}$').hasMatch(value['id'] as String) || value['status'] is! String) { throw const QrApiException(502, 'invalid_response'); } } String get id => json['id'] as String; String get status => json['status'] as String; String get amountRub => json['amount_rub'] as String; String? get traderRate => json['trader_rate'] as String?; String? get expectedUsdt => json['expected_usdt'] as String?; String? get qrUrl => json['qr_url'] as String?; String? get paymentUrl => json['payment_url'] as String?; } class QrApi { final Uri base; final String _key; final http.Client _client; final Duration retryDelay; /// [base] includes /api/v1, e.g. https://api.cashwellpay.com/api/v1. /// Inject a client only for tests or to reuse your server's connection pool. QrApi(String baseUrl, String key, {http.Client? client, bool allowInsecureForLocalTests = false, this.retryDelay = const Duration(seconds: 1)}) : base = Uri.parse(baseUrl.replaceFirst(RegExp(r'/$'), '')), _key = key, _client = client ?? http.Client() { final local = {'127.0.0.1', 'localhost', '::1'}.contains(base.host); if ((!allowInsecureForLocalTests || !local || base.scheme != 'http') && base.scheme != 'https') { throw ArgumentError('HTTPS API base URL is required.'); } if (base.host.isEmpty || base.userInfo.isNotEmpty || base.hasQuery || base.hasFragment || base.path != '/api/v1' || key.isEmpty || key.contains(RegExp(r'[\r\n]'))) { throw ArgumentError('Invalid API configuration.'); } } void close() => _client.close(); /// Reject foreign hosts AND unexpected paths before attaching authorization. Uri checkedQrUri(QrOrder order) { final supplied = order.qrUrl; if (supplied == null) throw const QrApiException(409, 'qr_unavailable'); final uri = base.resolve(supplied); if (uri.scheme != base.scheme || uri.host != base.host || uri.port != base.port || uri.userInfo.isNotEmpty || uri.hasQuery || uri.hasFragment || uri.path != '${base.path}/orders/${order.id}/qr') { throw const QrApiException(502, 'unsafe_qr_url'); } return uri; } Future _read(http.StreamedResponse response, int maxBytes) async { final bytes = BytesBuilder(copy: false); await for (final part in response.stream.timeout(const Duration(seconds: 30))) { if (bytes.length + part.length > maxBytes) { throw const QrApiException(502, 'response_too_large'); } bytes.add(part); } return bytes.takeBytes(); } Future _json(String method, String path, {Map? body, String? idempotencyKey}) async { final relative = Uri.parse(path); final uri = base.replace(path: '${base.path}${relative.path}', query: relative.hasQuery ? relative.query : null); final encoded = body == null ? null : jsonEncode(body); for (var attempt = 0; attempt < 3; attempt++) { try { final request = http.Request(method, uri)..followRedirects = false; request.headers['Authorization'] = 'Bearer $_key'; request.headers['Accept'] = 'application/json'; if (idempotencyKey != null) request.headers['Idempotency-Key'] = idempotencyKey; if (encoded != null) { request.headers['Content-Type'] = 'application/json'; request.body = encoded; } final response = await _client.send(request).timeout(const Duration(seconds: 30)); final bytes = await _read(response, 1024 * 1024); if ((response.statusCode == 429 || response.statusCode >= 500) && attempt < 2) { final retry = int.tryParse(response.headers['retry-after'] ?? ''); await Future.delayed(retry == null ? retryDelay : Duration(seconds: retry.clamp(1, 30))); continue; } Object? value; try { value = jsonDecode(utf8.decode(bytes)); } catch (_) { throw QrApiException(response.statusCode, 'invalid_response'); } if (response.statusCode < 200 || response.statusCode >= 300) { final error = value is Map ? value['error'] : null; final code = error is Map && error['code'] is String ? error['code'] as String : 'request_failed'; throw QrApiException(response.statusCode, RegExp(r'^[a-z][a-z0-9_]{0,63}$').hasMatch(code) ? code : 'request_failed'); } if (value == null) throw const QrApiException(502, 'invalid_response'); return value; } on http.ClientException { if (attempt == 2) throw const QrApiException(0, 'transport_error'); } on TimeoutException { if (attempt == 2) throw const QrApiException(0, 'transport_timeout'); } await Future.delayed(retryDelay); } throw const QrApiException(0, 'transport_error'); } Future> _object(String method, String path, {Map? body, String? idempotencyKey}) async { final value = await _json(method, path, body: body, idempotencyKey: idempotencyKey); if (value is! Map) throw const QrApiException(502, 'invalid_response'); return value; } Future createOrder({required String externalId, required String fullName, required String bank, required String amountRub, required String idempotencyKey}) async => QrOrder(await _object('POST', '/orders', idempotencyKey: idempotencyKey, body: {'external_id': externalId, 'full_name': fullName, 'bank': bank, 'amount_rub': amountRub})); Future getOrder(String id) async { if (!RegExp(r'^[a-f0-9]{20}$').hasMatch(id)) throw ArgumentError('Invalid order ID.'); return QrOrder(await _object('GET', '/orders/$id')); } Future> listOrders({int limit = 50, int offset = 0}) => _object('GET', '/orders?limit=$limit&offset=$offset'); Future> rate() => _object('GET', '/rate'); Future> balance() => _object('GET', '/balance'); /// A timeout retains the original ID. It never creates a replacement invoice. Future waitForOrder(String id, {Duration timeout = const Duration(seconds: 90), Duration interval = const Duration(seconds: 2)}) async { final until = DateTime.now().add(timeout); while (true) { final order = await getOrder(id); if (order.status != 'creating' || !DateTime.now().isBefore(until)) return order; await Future.delayed(interval); } } Future downloadQr(QrOrder order) async { final request = http.Request('GET', checkedQrUri(order))..followRedirects = false; request.headers['Authorization'] = 'Bearer $_key'; final response = await _client.send(request).timeout(const Duration(seconds: 30)); final bytes = await _read(response, 10 * 1024 * 1024); if (response.statusCode != 200) throw QrApiException(response.statusCode, 'qr_unavailable'); const png = [137, 80, 78, 71, 13, 10, 26, 10]; if (response.headers['content-type']?.split(';').first != 'image/png' || bytes.length < 8 || !List.generate(8, (i) => bytes[i] == png[i]).every((v) => v)) { throw const QrApiException(502, 'invalid_qr_image'); } return bytes; } }