vvvirani / flutter_amazon_payfort

Flutter plugin for Amazon Payment Services (Payfort). It supports both android and iOS.
https://pub.dev/packages/amazon_payfort
MIT License
5 stars 12 forks source link

Getting initialize error #3

Closed alihassan04ali closed 2 years ago

alihassan04ali commented 2 years ago

To initialize await AmazonPayfort.initialize( PayFortOptions(environment: FortEnvironment.production), ).then((value) { print(value); //returning false });

get error below

[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: PlatformException(NOT_INITIALIZE, Ensure to initialize AmazonPayfort before accessing it. E/flutter ( 7216): Please execute the initialize method : AmazonPayfort.initialize(), null, null) E/flutter ( 7216): #0 AmazonPayfort.getDeviceId (package:amazon_payfort/amazon_payfort.dart:49:7) E/flutter ( 7216): #1 FinishPayController.payNow (package:kaffarat/app/modules/finish_pay/controllers/finish_pay_controller.dart:106:35) E/flutter ( 7216): #2 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21) E/flutter ( 7216): #3 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24) E/flutter ( 7216): #4 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11) E/flutter ( 7216): #5 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5) E/flutter ( 7216): #6 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:239:7) E/flutter ( 7216): #7 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:615:9) E/flutter ( 7216): #8 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:98:12) E/flutter ( 7216): #9 PointerRouter._dispatchEventToRoutes. (package:flutter/src/gestures/pointer_router.dart:143:9) E/flutter ( 7216): #10 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:617:13) E/flutter ( 7216): #11 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:141:18) E/flutter ( 7216): #12 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:127:7) E/flutter ( 7216): #13 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:460:19) E/flutter ( 7216): #14 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:440:22) E/flutter ( 7216): #15 RendererBinding.dispatchEvent (package:flutter/src/rendering/binding.dart:337:11) E/flutter ( 7216): #16 GestureBinding._handlePointerEventImmediately (package:flutter/src/gestures/binding.dart:395:7) E/flutter ( 7216): #17 GestureBinding.handlePointerEvent (package:flutter/src/gestures/binding.dart:357:5) E/flutter ( 7216): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:314:7) E/flutter ( 7216): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:295:7) E/flutter ( 7216): #20 _invoke1 (dart:ui/hooks.dart:167:13) E/flutter ( 7216): #21 PlatformDispatcher._dispatchPointerDataPacket (dart:ui/platform_dispatcher.dart:341:7) E/flutter ( 7216): #22 _dispatchPointerDataPacket (dart:ui/hooks.dart:94:31)

vvvirani commented 2 years ago

Can you share your example code?

alihassan04ali commented 2 years ago

import 'dart:convert'; import 'dart:ffi'; import 'dart:io'; import 'dart:math';

import 'package:amazon_payfort/amazon_payfort_platform_interface.dart'; import 'package:dio/dio.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:get/get.dart' hide FormData; import 'package:image_picker/image_picker.dart'; import 'package:kaffarat/app/core/widgets/custom_alert.dart'; import 'package:kaffarat/app/model/donation_type.dart'; import 'package:kaffarat/app/model/user.dart'; import 'package:kaffarat/app/modules/home/controllers/home_controller.dart'; import 'package:kaffarat/app/modules/home/views/tabs/cart/controllers/cart_controller.dart'; // import 'package:payfort_plugin/payfort_plugin.dart'; import 'package:amazon_payfort/amazon_payfort.dart';

import '../../../model/project.dart'; import '../../../model/token_request.dart'; import '../../../packages/custom_dio/src/custom_dio.dart'; import '../../../routes/app_pages.dart'; import '../../single_project/controllers/pay_controller.dart'; import 'package:dio/src/multipart_file.dart' as d; import 'package:network_info_plus/network_info_plus.dart';

class FinishPayController extends GetxController { late Project project; late Map<Project, List> cartProjects; late User createdUser; late int quantity; final AmazonPayfort _payfort = AmazonPayfort.instance;

final payController = Get.isRegistered() ? Get.find() : Get.put(SingleProjectController()); final cartController = Get.find(); final paymentValue = "Visa".obs; final single = true.obs; final NetworkInfo _info = NetworkInfo();

@override void onInit() async { super.onInit(); single.value = Get.arguments['single']; print("single or cart: " + single.value.toString()); if (single.value) { project = Get.arguments['p']; } else { print("p runtime type: " + Get.arguments['p'].values.runtimeType.toString()); cartProjects = Map<Project, List>.from(cartController.cartProjects); project = cartProjects.keys.toList().first; }

createdUser = Get.arguments['user'];

quantity = payController.count.value;
paymentValue.value = "Visa";
init();

}

Future init() async { /// Step 1: Initialize Amazon Payfort await AmazonPayfort.initialize( PayFortOptions(environment: FortEnvironment.production), ).then((value) { print(value); }); }

// Future initPlatformState() async {}

@override void onReady() { super.onReady(); print("ready"); }

@override void onClose() { super.onClose(); payController.count.value = 1; }

void payNow({bool visaOrApple = true}) async { try { if (kDebugMode) { print(payController.totalPrice.toString()); } CustomAlert.customLoadingDialog(); String? id = await _payfort.getDeviceId(); // final id = await PayfortPlugin.getID; bool isApplePay; if(visaOrApple) isApplePay = false; else isApplePay = true;

  FormData formData = FormData.fromMap({"device_id": id.toString(), "isApplePay": isApplePay.toString()});
  final req = await CustomDio().send(
    reqMethod: "post",
    path: "payment/tokenRequest",
    body: formData,
  );
  final requestToken = TokenRequest.fromMap(req.data['data']);

  print("tokenRequest res: " + req.toString());

  num amt = 0;
  if(isApplePay){
    amt = single.value
        ? int.parse(payController.totalPrice.value)
        : cartController.totalPrice.value;
  }
  else{
    amt = single.value
        ? int.parse(payController.totalPrice.value) * 100
        : cartController.totalPrice.value * 100;
  }
  final result = FortRequest(
    amount: amt,
    customerName: createdUser.fullName,
    customerEmail: createdUser.email,
    orderDescription: "PURCHASE",
    sdkToken: requestToken.sdkToken,
    merchantReference: 'Order ${DateTime.now().millisecondsSinceEpoch}',
    currency: 'SAR',
    customerIp: await _info.getWifiIP(),
    // paymentOption: "[MASTERCARD], [VISA], [MADA]",
    language: 'ar',
  );
  var res;
  if (visaOrApple) {
    res = await _payfort.callPayFort(result);
  } else {
    Get.back();
    res = await _payfort.callPayFortForApplePay(
      request: result,
      applePayMerchantId: "merchant.applepay.web",
    );
  }

  // if (kDebugMode) {
  print("res: " + res.toString());
  print("res project: " + project.projectId.toString());
  var payRes = res as PayFortResult;

  // }
  if (payRes.responseCode == "13029") {
    if (kDebugMode) {
      print(
          "xxxxxxxxxxxxxxx failed failed failed failed failed failed failed user cancel");
    }
    Get.back();
    CustomAlert.showDoneToast(payRes.responseMessage.toString());
  }
  var saveFormData;
  if (single.value) {
    //one project card Payment
    saveFormData = FormData.fromMap(
      {
        "donor_id": createdUser.donorId,
        "total": payController.totalPrice,
        "quantity": payController.count.value.toString(),

        "payment_method_id": "3",
        "project_id": project.projectId,
        "bankImage": null,
        "payfortResponse": res.toString(),
        "donationType": project.donationType.typeEnum.name,
        // "order_meta": jsonEncode({

        //   // 'payment_method_key': "visa"
        // }),
      },
    );

    print("saveFormData: " +
        {
          "donor_id": createdUser.donorId,
          "total": payController.totalPrice,
          "quantity": payController.count.value.toString(),

          "payment_method_id": "3",
          "project_id": project.projectId,
          "bankImage": null,
          "payfortResponse": res.toString(),
          "donationType": project.donationType.typeEnum.name,
          // "order_meta": jsonEncode({

          //   // 'payment_method_key': "visa"
          // }),
        }.toString());
  } else {
    //from cart card Payment
    // Map donationsMap = {};
    List donationsList = [];
    cartProjects.forEach((key, value) {
      // donationsMap["quantity"] = value[1].toString();
      // donationsMap["donationType"] =
      //     key.donationType.typeEnum.name.toString();
      // donationsMap["project_id"] = key.projectId.toString();
      // donationsMap["total"] = key.unitPrice.toString();

      donationsList.add(json.encode({
        "quantity": value[1].toString(),
        "donationType": key.donationType.typeEnum.name.toString(),
        "project_id": key.projectId.toString(),
        "total": key.unitPrice.toString()
      }));
    });
    print("donation List type:" + donationsList.toString());
    saveFormData = FormData.fromMap({
      "donor_id": createdUser.donorId,
      "total": cartController.totalPrice.value.toString(),
      "payment_method_id": "3",
      "payfortResponse": res.toString(),
      "donations": donationsList.toString(),
      "bankImage": null,

      // ((element) {
      //         // print("projectid from finishpay controller: " +
      //         //     element.toString());
      //         return element.toString();
      //       }).toList(),
    });
  }

  if (kDebugMode) {
    print("form data: " +
        createdUser.donorId
            .toString()); //saveFormData.fields.runtimeType.toString());
  }
  var res2;
  if (single.value) {
    res2 = await CustomDio()
        .send(reqMethod: "post", path: "orders/save", body: saveFormData);
  } else {
    // var dio = Dio();
    // final res2 = await dio.post("https://namaa.sa/api/orders/cart",
    //     data: saveFormData);
    res2 = await CustomDio()
        .send(reqMethod: "post", path: "orders/cart", body: saveFormData);
  }
  print("payfort ress:" + res.toString());
  print("caret resss:" + res2.toString());
  // if (kDebugMode) {
  //   print(
  //       "visa save data response: " + res['response_message'].toString());
  // }
  // Get.back();
  Get.back();
  if (project.thanksMessage.isEmpty) {
    CustomAlert.showDoneToast(payRes.responseMessage.toString());
    // CustomAlert.showDoneToast(
    // "طلبكم الآن قيد المراجعة .. وسوف يتم ارسال رسالة نصية فور تأكيد الطلب .. \r\nشكرا جزيلاً لكم ..\r\nجمعية نماء بمنطقة مكة المكرمة ..");
    // CustomAlert.showDoneToast(res.responseMessage.toString());

    Get.find<CartController>().clearCart();
    // Get.back();
    // Get.back();
    Get.offNamedUntil(Routes.HOME, (route) => false);
  } else {
    Get.find<CartController>().clearCart();
    CustomAlert.showDoneToast(project.thanksMessage);
  }
} catch (err) {
  Get.back();
  CustomAlert.customAlertDialog(errorMessage: err.toString());
  rethrow;
}

}

}

vvvirani commented 2 years ago
Screenshot 2022-11-08 at 9 38 25 PM

Remove this import

Screenshot 2022-11-08 at 9 39 03 PM

Call this init() function under GetXController's onInit() function

If this is not working then Can you share the full file?

alihassan04ali commented 2 years ago

controller.txt

alihassan04ali commented 2 years ago

complete file shared

vvvirani commented 2 years ago

Don't need code Need .dart file

I want a sample code. For debugging and identifying the error.

Once try to run package example code.

alihassan04ali commented 2 years ago

https://we.tl/t-CW610Sp5Ie here is .dart file

alihassan04ali commented 2 years ago

the issue comes on 2nd time when i'm going to pay. on fresh install it allow to pay after that display error everytime

vvvirani commented 2 years ago

https://www.linkedin.com/in/vishal-virani-b53171216/

Contact me. I need your remote screen access to fix the issue

alihassan04ali commented 2 years ago

plz check linkedin