ente/lib/ui/payment/payment_web_page.dart

262 lines
8.5 KiB
Dart
Raw Normal View History

import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:logging/logging.dart';
2021-08-18 19:43:35 +00:00
import 'package:photos/models/subscription.dart';
import 'package:photos/services/billing_service.dart';
import 'package:photos/services/user_service.dart';
import 'package:photos/ui/common/loading_widget.dart';
import 'package:photos/ui/common/progress_dialog.dart';
import 'package:photos/utils/dialog_util.dart';
class PaymentWebPage extends StatefulWidget {
final String planId;
final String actionType;
2022-07-03 09:49:33 +00:00
const PaymentWebPage({Key key, this.planId, this.actionType})
: super(key: key);
@override
2021-08-23 10:15:45 +00:00
State<StatefulWidget> createState() => _PaymentWebPageState();
}
2021-08-23 10:15:45 +00:00
class _PaymentWebPageState extends State<PaymentWebPage> {
final _logger = Logger("PaymentWebPageState");
final UserService userService = UserService.instance;
final BillingService billingService = BillingService.instance;
final String basePaymentUrl = kWebPaymentBaseEndpoint;
ProgressDialog _dialog;
InAppWebViewController webView;
double progress = 0;
Uri initPaymentUrl;
@override
void initState() {
userService.getPaymentToken().then((token) {
initPaymentUrl = _getPaymentUrl(token);
2021-08-23 10:24:56 +00:00
setState(() {});
});
if (Platform.isAndroid && kDebugMode) {
AndroidInAppWebViewController.setWebContentsDebuggingEnabled(true);
}
super.initState();
}
@override
Widget build(BuildContext context) {
2022-05-17 11:38:21 +00:00
_dialog = createProgressDialog(context, "Please wait...");
if (initPaymentUrl == null) {
return const EnteLoadingWidget();
}
return WillPopScope(
2022-06-11 08:23:52 +00:00
onWillPop: () async => _buildPageExitWidget(context),
child: Scaffold(
appBar: AppBar(
title: const Text('Subscription'),
),
body: Column(
children: <Widget>[
2022-07-03 09:49:33 +00:00
(progress != 1.0)
? LinearProgressIndicator(value: progress)
: Container(),
2022-06-11 08:23:52 +00:00
Expanded(
child: InAppWebView(
initialUrlRequest: URLRequest(url: initPaymentUrl),
2022-07-03 09:49:33 +00:00
onProgressChanged:
(InAppWebViewController controller, int progress) {
2022-06-11 08:23:52 +00:00
setState(() {
this.progress = progress / 100;
});
},
initialOptions: InAppWebViewGroupOptions(
crossPlatform: InAppWebViewOptions(
useShouldOverrideUrlLoading: true,
),
),
2022-06-11 08:23:52 +00:00
shouldOverrideUrlLoading: (controller, navigationAction) async {
var loadingUri = navigationAction.request.url;
_logger.info("Loading url $loadingUri");
// handle the payment response
if (_isPaymentActionComplete(loadingUri)) {
await _handlePaymentResponse(loadingUri);
return NavigationActionPolicy.CANCEL;
}
return NavigationActionPolicy.ALLOW;
},
onConsoleMessage: (controller, consoleMessage) {
_logger.info(consoleMessage);
},
onLoadStart: (controller, navigationAction) async {
if (!_dialog.isShowing()) {
await _dialog.show();
}
},
onLoadError: (controller, navigationAction, code, msg) async {
if (_dialog.isShowing()) {
await _dialog.hide();
}
},
2022-07-03 09:49:33 +00:00
onLoadHttpError:
(controller, navigationAction, code, msg) async {
2022-06-11 08:23:52 +00:00
_logger.info("onHttpError with $code and msg = $msg");
},
onLoadStop: (controller, navigationAction) async {
_logger.info("loadStart" + navigationAction.toString());
if (_dialog.isShowing()) {
await _dialog.hide();
}
},
),
2022-06-11 08:23:52 +00:00
),
].where((Object o) => o != null).toList(),
),
),
);
}
@override
void dispose() {
2021-08-18 19:43:35 +00:00
_dialog.hide();
super.dispose();
}
2021-08-23 10:15:45 +00:00
Uri _getPaymentUrl(String paymentToken) {
final queryParameters = {
'productID': widget.planId,
'paymentToken': paymentToken,
'action': widget.actionType,
'redirectURL': kWebPaymentRedirectUrl,
};
var tryParse = Uri.tryParse(kWebPaymentBaseEndpoint);
if (kDebugMode && kWebPaymentBaseEndpoint.startsWith("http://")) {
return Uri.http(tryParse.authority, tryParse.path, queryParameters);
} else {
return Uri.https(tryParse.authority, tryParse.path, queryParameters);
}
}
2021-08-18 20:57:01 +00:00
// show dialog to handle accidental back press.
Future<bool> _buildPageExitWidget(BuildContext context) {
return showDialog(
2021-08-23 10:24:56 +00:00
context: context,
builder: (context) => AlertDialog(
2022-07-04 06:02:17 +00:00
title: const Text('Are you sure you want to exit?'),
2021-08-23 10:24:56 +00:00
actions: <Widget>[
TextButton(
2022-07-04 06:02:17 +00:00
child: const Text(
2022-06-11 08:23:52 +00:00
'Yes',
style: TextStyle(
color: Colors.redAccent,
),
),
2021-08-23 10:24:56 +00:00
onPressed: () => Navigator.of(context).pop(true),
),
TextButton(
child: Text(
2022-06-09 04:51:59 +00:00
'No',
2021-08-23 10:24:56 +00:00
style: TextStyle(
color: Theme.of(context).buttonColor,
2021-08-23 10:24:56 +00:00
),
),
onPressed: () => Navigator.of(context).pop(false),
),
],
),
);
2021-08-18 20:57:01 +00:00
}
2021-08-18 19:43:35 +00:00
bool _isPaymentActionComplete(Uri loadingUri) {
return loadingUri.toString().startsWith(kWebPaymentRedirectUrl);
}
2021-08-23 10:15:45 +00:00
Future<void> _handlePaymentResponse(Uri uri) async {
var queryParams = uri.queryParameters;
var paymentStatus = uri.queryParameters['status'] ?? '';
_logger.fine('handle payment response with status $paymentStatus');
if (paymentStatus == 'success') {
await _handlePaymentSuccess(queryParams);
2021-08-23 10:15:45 +00:00
} else if (paymentStatus == 'fail') {
2021-08-18 20:57:01 +00:00
var reason = queryParams['reason'] ?? '';
await _handlePaymentFailure(reason);
2021-08-18 19:43:35 +00:00
} else {
// should never reach here
_logger.severe("unexpected status", uri.toString());
2021-08-23 10:24:56 +00:00
showGenericErrorDialog(context);
2021-08-18 19:43:35 +00:00
}
}
Future<void> _handlePaymentFailure(String reason) async {
await showDialog(
2022-06-11 08:23:52 +00:00
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
2022-07-04 06:02:17 +00:00
title: const Text('Payment failed'),
2022-06-11 08:23:52 +00:00
content: Text("Unfortunately your payment failed due to $reason"),
actions: <Widget>[
TextButton(
2022-07-04 06:02:17 +00:00
child: const Text('Ok'),
2022-06-11 08:23:52 +00:00
onPressed: () {
Navigator.of(context).pop('dialog');
},
),
],
),
);
Navigator.of(context).pop(true);
}
2021-08-18 19:43:35 +00:00
// return true if verifySubscription didn't throw any exceptions
2021-08-18 20:57:01 +00:00
Future<void> _handlePaymentSuccess(Map<String, String> queryParams) async {
2021-08-18 19:43:35 +00:00
var checkoutSessionID = queryParams['session_id'] ?? '';
await _dialog.show();
try {
var response = await billingService.verifySubscription(
2022-06-11 08:23:52 +00:00
widget.planId,
checkoutSessionID,
paymentProvider: kStripe,
);
2021-08-18 20:57:01 +00:00
await _dialog.hide();
if (response != null) {
var content = widget.actionType == 'buy'
2022-06-09 04:59:23 +00:00
? 'Your purchase was successful'
: 'Your subscription was updated successfully';
await _showExitPageDialog(title: 'Thank you', content: content);
2021-08-18 20:57:01 +00:00
} else {
throw Exception("verifySubscription api failed");
}
2021-08-18 19:43:35 +00:00
} catch (error) {
_logger.severe(error);
await _dialog.hide();
2021-08-18 20:57:01 +00:00
await _showExitPageDialog(
2022-06-09 04:59:23 +00:00
title: 'Failed to verify payment status',
content: 'Please wait for sometime before retrying',
2021-08-18 20:57:01 +00:00
);
}
2021-08-18 20:57:01 +00:00
}
// warn the user to wait for sometime before trying another payment
Future<dynamic> _showExitPageDialog({String title, String content}) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (context) => AlertDialog(
title: Text(title),
content: Text(content),
actions: <Widget>[
TextButton(
2022-06-11 08:23:52 +00:00
child: Text(
'Ok',
style: TextStyle(color: Theme.of(context).buttonColor),
),
onPressed: () {
Navigator.of(context).pop('dialog');
},
),
],
),
).then((val) => Navigator.pop(context, true));
}
}