import 'dart:convert'; import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_inappwebview/flutter_inappwebview.dart'; import 'package:hmg_patient_app_new/core/api_consts.dart'; import 'package:hmg_patient_app_new/core/app_state.dart'; import 'package:hmg_patient_app_new/core/cache_consts.dart'; import 'package:hmg_patient_app_new/core/common_models/tamara_request_model.dart'; import 'package:hmg_patient_app_new/core/dependencies.dart'; import 'package:hmg_patient_app_new/core/utils/date_util.dart'; import 'package:hmg_patient_app_new/core/utils/utils.dart'; import 'package:hmg_patient_app_new/features/authentication/models/resp_models/authenticated_user_resp_model.dart'; enum _PAYMENT_TYPE { PACKAGES, PHARMACY, PATIENT } var _InAppBrowserOptions = InAppBrowserClassOptions( inAppWebViewGroupOptions: InAppWebViewGroupOptions( crossPlatform: InAppWebViewOptions(useShouldOverrideUrlLoading: true, transparentBackground: false), ios: IOSInAppWebViewOptions(applePayAPIEnabled: true, isFraudulentWebsiteWarningEnabled: false)), crossPlatform: InAppBrowserOptions(hideUrlBar: true, toolbarTopBackgroundColor: Colors.black), android: AndroidInAppBrowserOptions(), ios: IOSInAppBrowserOptions( hideToolbarBottom: true, toolbarBottomBackgroundColor: Colors.white, closeButtonColor: Colors.white, closeButtonCaption: "Close", presentationStyle: IOSUIModalPresentationStyle.OVER_FULL_SCREEN)); class MyInAppBrowser extends InAppBrowser { _PAYMENT_TYPE? paymentType; static String APPLE_PAY_PAYFORT_URL = 'https://hmgwebservices.com/PayFortWebLive/PayFortApi/MakeApplePayRequest'; // Payfort Payment Gateway URL LIVE // static String APPLE_PAY_PAYFORT_URL = 'https://hmgwebservices.com/PayFortWebLive/PayFortApi/MakeApplePayRequest'; // Payfort Payment Gateway URL UAT // static String SERVICE_URL = 'https://hmgwebservices.com/PayFortWeb/pages/SendPayFortRequest.aspx'; // Payfort Payment Gateway URL UAT // static String SERVICE_URL = 'https://hmgwebservices.com/PayFortWebLive/pages/SendPayFortRequest.aspx'; //Payfort Payment Gateway URL LIVE // static String SERVICE_URL = 'https://uat.hmgwebservices.com/payfortforvidaplus/pages/SendPayFortRequest.aspx'; //Payfort Payment Gateway URL UAT VIDA PLUS // static String PRESCRIPTION_PAYMENT_WITH_ORDERID = // 'https://uat.hmgwebservices.com/epharmacy/checkout/OpcCompleteRedirectionPaymentClientbyOrder?orderID='; static String PRESCRIPTION_PAYMENT_WITH_ORDERID = 'https://mdlaboratories.com/exacartapi/checkout/OpcCompleteRedirectionPaymentClientbyOrder?orderID='; //Live static List successURLS = ['success?', 'PayFortResponse', 'PayFortSucess', 'mobilepaymentcomplete', 'orderdetails', 'redirectToApplePay', 'mdlaboratories.com/?']; static List errorURLS = ['PayfortCancel', 'errorpage', 'Failed', 'orderdetails', 'redirectToApplePay', 'mdlaboratories.com/?', 'cancel', 'canceled']; final Function onExitCallback; final Function? onLoadStartCallback; final BuildContext? context; // AppSharedPreferences sharedPref = AppSharedPreferences(); // AuthProvider authProvider = new AuthProvider(); InAppBrowser browser = InAppBrowser(); // AuthenticatedUser authUser; // late AppoitmentAllHistoryResultList? appo; String deviceToken = ""; double lat = 0.0; double long = 0.0; static bool isPaymentDone = false; late AppState appState; MyInAppBrowser({required this.onExitCallback, this.onLoadStartCallback, this.context}); Future onBrowserCreated() async { print("\n\nBrowser Created!\n\n"); } @override Future onLoadStart(Uri? url) async { if (onLoadStartCallback != null) onLoadStartCallback!(url.toString()); } @override Future onLoadStop(Uri? url) async { print("\n\nStopped $url\n\n"); } @override void onLoadError(Uri? url, int code, String message) { print("Can't load $url.. Error: $message"); } @override void onProgressChanged(int progress) {} @override void onExit() { print("\n\nBrowser closed before!\n\n"); // if (onExitCallback != null) { try { onExitCallback(isPaymentDone); print("\n\nBrowser closed after!\n\n"); } catch (err) { print(err.toString()); } // } } @override Future shouldOverrideUrlLoading(NavigationAction navigationAction) { var url = navigationAction.request.url.toString(); debugPrint("redirecting/overriding to: $url"); // if (paymentType == _PAYMENT_TYPE.PACKAGES && [PACKAGES_PAYMENT_SUCCESS_URL, PACKAGES_PAYMENT_FAIL_URL].contains(url)) { // isPaymentDone = (url == PACKAGES_PAYMENT_SUCCESS_URL); // close(); // } return Future.value(NavigationActionPolicy.ALLOW); } // getLanguageID() async { // return await sharedPref.getStringWithDefaultValue(APP_LANGUAGE, 'ar'); // } // getDeviceToken() async { // String deviceToken = await sharedPref.getString(PUSH_TOKEN); // this.deviceToken = deviceToken; // } // openPackagesPaymentBrowser({required int customer_id, required int order_id}) { // paymentType = _PAYMENT_TYPE.PACKAGES; // var full_url = '$PACKAGES_REQUEST_PAYMENT_URL?customer_id=$customer_id&order_id=$order_id'; // this.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(full_url))), options: _InAppBrowserOptions); // } openPaymentBrowser(num amount, String orderDesc, String transactionID, String projId, String emailId, String paymentMethod, dynamic patientType, String patientName, dynamic patientID, AuthenticatedUser authenticatedUser, InAppBrowser browser, bool isLiveCareAppo, var servID, var LiveServID, BuildContext context, [var appoDate, var appoNo, var clinicID, var doctorID, var installments]) async { appState = getIt.get(); this.browser = browser; // await getPatientData(); if (paymentMethod == "ApplePay") { MyChromeSafariBrowser safariBrowser = MyChromeSafariBrowser(MyInAppBrowser(onExitCallback: browser.onExit), onExitCallback: browser.onExit, onLoadStartCallback: this.browser.onLoadStart); // if (context != null) GifLoaderDialogUtils.showMyDialog(context); // LiveCareService service = new LiveCareService(); // ApplePayInsertRequest applePayInsertRequest = new ApplePayInsertRequest(); // applePayInsertRequest.clientRequestID = transactionID; // applePayInsertRequest.clinicID = (clinicID != null && clinicID != "") ? clinicID : 0; // applePayInsertRequest.currency = authenticatedUser.outSA == 1 ? "AED" : "SAR"; // applePayInsertRequest.customerEmail = emailId; // applePayInsertRequest.customerID = patientID; // applePayInsertRequest.customerName = patientName; // applePayInsertRequest.deviceToken = await AppSharedPreferences().getString(PUSH_TOKEN); // applePayInsertRequest.voipToken = await AppSharedPreferences().getString(ONESIGNAL_APNS_TOKEN); // applePayInsertRequest.doctorID = (doctorID != null && doctorID != "") ? doctorID : 0; // applePayInsertRequest.projectID = projId; // applePayInsertRequest.serviceID = servID; // applePayInsertRequest.channelID = 3; // applePayInsertRequest.patientID = patientID; // applePayInsertRequest.patientTypeID = authenticatedUser.patientType; // applePayInsertRequest.patientOutSA = authenticatedUser.outSA; // applePayInsertRequest.appointmentDate = (appoDate != null && appoDate != "") ? appoDate : null; // applePayInsertRequest.appointmentNo = (appoNo != null && appoNo != "") ? appoNo : 0; // applePayInsertRequest.orderDescription = orderDesc; // applePayInsertRequest.liveServiceID = LiveServID.toString() == "" ? "0" : LiveServID.toString(); // applePayInsertRequest.latitude = this.lat.toString(); // applePayInsertRequest.longitude = this.long.toString(); // applePayInsertRequest.amount = amount.toString(); // applePayInsertRequest.isSchedule = ((appoNo != null && appoNo != "") && (appoDate != null && appoDate != "")) ? "1" : "0"; // applePayInsertRequest.language = await getLanguageID() == 'ar' ? 'ar' : 'en'; // applePayInsertRequest.userName = authenticatedUser.patientID; // applePayInsertRequest.responseContinueURL = "http://hmg.com/Documents/success.html"; // applePayInsertRequest.backClickUrl = "http://hmg.com/Documents/success.html"; // applePayInsertRequest.paymentOption = "ApplePay"; // // service.applePayInsertRequest(applePayInsertRequest, context).then((res) { // if (context != null) GifLoaderDialogUtils.hideDialog(context); // String url = "https://hmgwebservices.com/HMGApplePayLive/applepay/pay?apq=" + res['result']; // Prod // // String url = "https://uat.hmgwebservices.com/HMGApplePayLive/applepay/pay?apq=" + res['result']; // UAT // // safariBrowser.open(url: Uri.parse(url)); // this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(url))), options: _InAppBrowserOptions); // }).catchError((err) { // print(err); // if (context != null) GifLoaderDialogUtils.hideDialog(context); // AppToast.showErrorToast(message: err); // }); } else if (paymentMethod == "TAMARA") { // LiveCareService service = new LiveCareService(); TamaraRequestModel tamaraRequestModel = new TamaraRequestModel(); // if (context != null) GifLoaderDialogUtils.showMyDialog(context); tamaraRequestModel.merchantReference = transactionID; tamaraRequestModel.merchantIdentifier = "Tamara"; tamaraRequestModel.clientRequestID = transactionID; tamaraRequestModel.amount = amount; tamaraRequestModel.currency = "SR"; tamaraRequestModel.language = appState.isArabic() ? 'AR' : 'EN'; tamaraRequestModel.commandType = "PURCHASE"; tamaraRequestModel.customerEmail = emailId; tamaraRequestModel.orderDescription = orderDesc; tamaraRequestModel.isInstallment = true; tamaraRequestModel.projectID = num.parse(projId); tamaraRequestModel.accessCode = authenticatedUser.mobileNumber!; tamaraRequestModel.appointmentNo = (appoNo != null && appoNo != "") ? appoNo.toString() : "0"; tamaraRequestModel.customerName = patientName; tamaraRequestModel.fileNumber = patientID.toString(); tamaraRequestModel.patientOutSA = authenticatedUser.outSa == 1 ? true : false; tamaraRequestModel.deviceToken = await Utils.getStringFromPrefs(CacheConst.pushToken); tamaraRequestModel.latitude = appState.userLat.toString(); tamaraRequestModel.longitude = appState.userLong.toString(); tamaraRequestModel.serviceID = servID; tamaraRequestModel.liveServiceID = LiveServID; tamaraRequestModel.doctorID = (doctorID.toString() != null && doctorID != "") ? doctorID.toString() : ""; tamaraRequestModel.appointmentDate = (appoDate != null && appoDate != "") ? appoDate : null; tamaraRequestModel.isSchedule = ((appoNo != null && appoNo != "") && (appoDate != null && appoDate != "")) ? true : false; // service.tamaraInsertRequest(tamaraRequestModel, context).then((res) { // // if (context != null) GifLoaderDialogUtils.hideDialog(context); generateTamaraURL(amount, orderDesc, transactionID, projId, emailId, paymentMethod, patientType, patientName, patientID, authenticatedUser, isLiveCareAppo, servID, LiveServID, appoDate, appoNo, clinicID, doctorID, "", installments) .then((value) { paymentType = _PAYMENT_TYPE.PATIENT; this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(value))), options: _InAppBrowserOptions); }); // }).catchError((err) { // print(err); // // if (context != null) GifLoaderDialogUtils.hideDialog(context); // // AppToast.showErrorToast(message: err); // }); } else { generateURL(amount, orderDesc, transactionID, projId, emailId, paymentMethod, patientType, patientName, patientID, authenticatedUser, isLiveCareAppo, servID, LiveServID, appoDate, appoNo, clinicID, doctorID) .then((value) { paymentType = _PAYMENT_TYPE.PATIENT; this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(value))), options: _InAppBrowserOptions); }); } } // openPharmacyPaymentBrowser(OrderDetailModel order, double amount, String orderDesc, String transactionID, String emailId, String paymentMethod, String patientName, dynamic patientID, // AuthenticatedUser authenticatedUser, InAppBrowser browser) { // this.browser = browser; // MyChromeSafariBrowser safariBrowser = // new MyChromeSafariBrowser(new MyInAppBrowser(onExitCallback: browser.onExit), onExitCallback: browser.onExit, onLoadStartCallback: this.browser.onLoadStart, appo: this.appo!); // // getPatientData(); // generatePharmacyURL(order, amount, orderDesc, transactionID, emailId, paymentMethod, patientName, patientID, authenticatedUser).then((value) { // if (order.customValuesXml!.contains("ApplePay")) { // safariBrowser.open(url: WebUri.uri(Uri.parse(value))); // } else { // this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(value))), options: _InAppBrowserOptions); // } // }); // } openBrowser(String url) { this.browser = browser; this.browser.openUrlRequest(urlRequest: URLRequest(url: WebUri.uri(Uri.parse(url))), options: _InAppBrowserOptions); } Future generateURL(num amount, String orderDesc, String transactionID, String projId, String emailId, String paymentMethod, dynamic patientType, String patientName, dynamic patientID, AuthenticatedUser authUser, bool isLiveCareAppo, var servID, var LiveServID, [var appoDate, var appoNo, var clinicID, var doctorID, var patientData]) async { // getDeviceToken(); String currentLanguageID = appState.isArabic() ? 'AR' : 'EN'; String form = isLiveCareAppo ? getLiveCareForm() : getForm(); form = form.replaceFirst("EMAIL_VALUE", emailId); form = form.replaceFirst('AMOUNT_VALUE', amount.toString()); form = form.replaceFirst('ORDER_DESCRIPTION_VALUE', orderDesc); form = form.replaceFirst('ORDER_ID_VALUE', transactionID); form = form.replaceFirst('REQUEST_ID_VALUE', transactionID); form = form.replaceFirst('PROJECT_ID_VALUE', projId); form = form.replaceFirst('PAYMENT_OPTION_VALUE', paymentMethod); form = form.replaceFirst('LANG_VALUE', currentLanguageID); form = form.replaceFirst('PATIENT_OUT_SA', authUser.outSa == 0 ? false.toString() : true.toString()); form = form.replaceFirst('PATIENT_TYPE_ID', patientData == null ? patientType.toString() : "1"); Platform.isIOS ? form = form.replaceFirst('DEVICE_TOKEN', "${await Utils.getStringFromPrefs(CacheConst.pushToken)},${await Utils.getStringFromPrefs(CacheConst.apnsToken)}") : form = form.replaceFirst('DEVICE_TOKEN', await Utils.getStringFromPrefs(CacheConst.pushToken) ?? ""); // form = form.replaceFirst('DEVICE_TOKEN', await AppSharedPreferences().getString(PUSH_TOKEN) + "," + await AppSharedPreferences().getString(ONESIGNAL_APNS_TOKEN)); // form = form.replaceFirst('DEVICE_TOKEN', await sharedPref.getString(PUSH_TOKEN)); form = form.replaceFirst('LATITUDE_VALUE', this.lat.toString()); form = form.replaceFirst('LONGITUDE_VALUE', this.long.toString()); // if (servID == "4") // form = form.replaceFirst('SERVICE_URL_VALUE', MyInAppBrowser.PREAUTH_SERVICE_URL); // else form = form.replaceFirst('SERVICE_URL_VALUE', ApiConsts.SERVICE_URL); if (servID != null) { form = form.replaceFirst('SERV_ID', servID); form = form.replaceFirst('LIVE_SERVICE_ID', LiveServID.toString()); } else { form = form.replaceFirst('SERV_ID', "2"); form = form.replaceFirst('LIVE_SERVICE_ID', "2"); } form = form.replaceFirst('CUSTNAME_VALUE', patientName); form = form.replaceFirst('CUSTID_VALUE', patientID.toString()); if (isLiveCareAppo) { form = form.replaceFirst('IS_SCHEDULE_VALUE', "true"); form = form.replaceFirst('APPOINTMENT_DATE_VALUE', appoDate); form = form.replaceFirst('APPOINTMENT_NO_VALUE', appoNo.toString()); form = form.replaceFirst('DOCTOR_ID_VALUE', doctorID.toString()); form = form.replaceFirst('CLINIC_ID_VALUE', clinicID.toString()); } var bytes = utf8.encode(form); var base64Str = base64.encode(bytes); return 'data:text/html;base64,' + base64Str; } Future generateTamaraURL(num amount, String orderDesc, String transactionID, String projId, String emailId, String paymentMethod, dynamic patientType, String patientName, dynamic patientID, AuthenticatedUser authUser, bool isLiveCareAppo, var servID, var LiveServID, [var appoDate, var appoNo, var clinicID, var doctorID, var patientData, var installments]) async { // getDeviceToken(); String currentLanguageID = appState.isArabic() ? 'AR' : 'EN'; String form = getTamaraForm(); form = form.replaceFirst("EMAIL_VALUE", emailId); form = form.replaceFirst('AMOUNT_VALUE', amount.toString()); form = form.replaceFirst('ORDER_DESCRIPTION_VALUE', orderDesc); form = form.replaceFirst('ORDER_ID_VALUE', transactionID); form = form.replaceFirst('REQUEST_ID_VALUE', transactionID); form = form.replaceFirst('PROJECT_ID_VALUE', projId); form = form.replaceFirst('PAYMENT_OPTION_VALUE', paymentMethod); form = form.replaceFirst('LANG_VALUE', currentLanguageID); form = form.replaceFirst('SERVICE_URL_VALUE', ApiConsts.TAMARA_URL); form = form.replaceFirst('INSTALLMENTS_VALUE', "3"); form = form.replaceFirst('CUSTNATIONALID_VALUE', authUser.patientIdentificationNo!); form = form.replaceFirst('CUSTMOBILE_VALUE', authUser.mobileNumber!); form = form.replaceFirst('CUSTDOB_VALUE', DateUtil.getDayMonthYearDateFormatted(DateUtil.convertStringToDate(authUser.dateofBirth!))); form = form.replaceFirst('CURRENCY_VALUE', authUser.outSa == 0 ? "SAR" : "AED"); form = form.replaceFirst('COUNTRY_CODE_VALUE', authUser.outSa == 0 ? "966" : "971"); form = form.replaceFirst('CUSTNAME_VALUE', patientName); form = form.replaceFirst('CUSTLASTNAME_VALUE', patientName); form = form.replaceFirst('CUSTID_VALUE', patientID.toString()); var bytes = utf8.encode(form); var base64Str = base64.encode(bytes); return 'data:text/html;base64,' + base64Str; } String getForm() { return ' ' + '' + '' + '
' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
' + '' + '' + ''; } String getTamaraForm() { return ' ' + '' + '' + '
' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' '
' + '' + '' + ''; } String getLiveCareForm() { return ' ' + '' + '' + '
' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '' + '
' + '' + '' + ''; } safariCallBack() { print("Safari CallBack!!!"); } } class MyChromeSafariBrowser extends ChromeSafariBrowser { final Function? onExitCallback; final Function? onLoadStartCallback; // AppoitmentAllHistoryResultList? appo; // MyChromeSafariBrowser(browserFallback, {this.onExitCallback, this.onLoadStartCallback, this.appo}); MyChromeSafariBrowser(browserFallback, {this.onExitCallback, this.onLoadStartCallback}); @override void onOpened() { print("ChromeSafari browser opened"); } @override void onCompletedInitialLoad(bool? didLoadSuccessfully) { print("ChromeSafari browser initial load completed"); onLoadStartCallback!("ApplePay"); } @override void onClosed() { print("ChromeSafari browser closed"); MyInAppBrowser.isPaymentDone = true; onExitCallback!(); } }