AhsanAyaz / flutter_stripe_connect

An example repository to teach how to implement a marketplace with Stripe Connect & Flutter.
MIT License
18 stars 8 forks source link

Struck on Please Wait #3

Open salmanmughal24 opened 1 year ago

salmanmughal24 commented 1 year ago

E/FrameEvents(13539): updateAcquireFence: Did not find frame. E/FrameEvents(13539): updateAcquireFence: Did not find frame. I/chromium(13539): [INFO:CONSOLE(1)] "Unrecognized feature: 'payment'.", source: https://js.stripe.com/v3/ (1) E/FrameEvents(13539): updateAcquireFence: Did not find frame. I/chatty (13539): uid=10156(com.example.flutter_stripe_connect) RenderThread identical 7 lines E/FrameEvents(13539): updateAcquireFence: Did not find frame. E/FrameEvents(13539): updateAcquireFence: Did not find frame. I/chatty (13539): uid=10156(com.example.flutter_stripe_connect) RenderThread identical 2 lines E/FrameEvents(13539): updateAcquireFence: Did not find frame. I/chromium(13539): [INFO:CONSOLE(1)] "Stripe.js requires 'allow-same-origin' if sandboxed.", source: https://js.stripe.com/v3/ (1) I/chromium(13539): [INFO:CONSOLE(1)] "Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.", source: https://js.stripe.com/v3/ (1)

saadzarif commented 1 year ago

@salmanmughal24 did you find any solution? Please do tell me if you did or if you have found any alternative. pura month guzra lakin hal ka pata nahi chala

saadzarif commented 1 year ago

@AhsanAyaz sir please reply. How so we solve this error. The error are "Stripe.js requires 'allow-same-origin' if sandboxed." and Uncaught SecurityError: Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs.", source: https://js.stripe.com/v3/ . also we had to use new version of the webview package because the old one is giving some sort of problem

saadzarif commented 1 year ago

@AhsanAyaz Please do reply sir

salmanmughal24 commented 1 year ago

@tariqzarif I could not solve this error, infact i changed the implementation of stripe connect, and use stripe checkout api, with uncaptured payments, because i need uncaptured in my code.

saadzarif commented 1 year ago

@salmanmughal24 I don't know what you mean by that? can you explain. Also I fixed it. very easy and there is another error too after wards which is when you register then you can't come back to the app. so instead or url_launcher i used webview. the same way used in payment. I'll add the code here now

salmanmughal24 commented 1 year ago

Yes, I did the same with Webview, this is the only solution possible, currently.

saadzarif commented 1 year ago

inside lib/pages/checkout.dart. we have to add a script. the first script you have to add it. this is the whole html.

<!DOCTYPE html>
  <html>
   <script>
                    if(!document.__defineGetter__) {
                        Object.defineProperty(document, 'cookie', {
                            get: function(){return ''},
                            set: function(){return true},
                        });
                    } else {
                        document.__defineGetter__("cookie", function() { return '';} );
                        document.__defineSetter__("cookie", function() {} );
                    }

                </script>
    <script src="https://js.stripe.com/v3/"></script>
    <style>
      body, html {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #loader {
        width: 100%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center; 
      }
    </style>
    <head><title>Stripe checkout</title></head>
    <body>
      <div id="loader">
        <span>Please wait...</span>
      </div>
    </body>
  </html>

Also the webview package is updated. so you can't use webview and instead use a controller with webviewwidget. you have to change it in two places. one in registering and one in payments. this one is for registering. some code is commented so you make changes according to your requirements. This is in lib/pages/register.dart in trycatch of elevated button.

  late WebViewController _controller = WebViewController()
                ..setJavaScriptMode(JavaScriptMode.unrestricted)
                // ..setBackgroundColor(const Color(0x00000000))
                ..setNavigationDelegate(
                  NavigationDelegate(
                    onProgress: (int progress) {
                      // Update loading bar.
                      print('progress==>$progress');
                    },
                    onPageStarted: (String url) {
                      print('url==>$url');
                    },
                    // onPageFinished: (String url) {
                    //   print('url==>$url');
                    // Navigator.of(context).pop();
                    // if (url == initialUrl) {
                    //   _redirectToStripe();
                    // }
                    // },
                    // onUrlChange: (change) {
                    //   Navigator.of(context).pop();
                    // },
                    onWebResourceError: (WebResourceError error) {
                      debugPrint('''
              Page resource error:
              code: ${error.errorCode}
              description: ${error.description}
              errorType: ${error.errorType}
              isForMainFrame: ${error.isForMainFrame}
                      ''');
                    },
                    onNavigationRequest: (NavigationRequest request) {
                      if (request.url
                          .startsWith('plate://deeplinks/register-success')) {
                        final data = Uri.parse(request.url)
                                .queryParameters['account_id'] ??
                            '';
                            print('data========================================>$data');// this will print stripe if of //the seller
                        Navigator.pop(context, data); // <-- Handle success case
                      } else if (request.url
                          .startsWith('plate://deeplinks/register-fail')) {
                        Navigator.of(context)
                            .pop('cancel'); // <-- Handle cancel case
                      }
                      return NavigationDecision.navigate;
                    },
                  ),
                )
                ..loadRequest(Uri.parse(response.url));

              Navigator.of(context).push(MaterialPageRoute(
                builder: (context) => WebViewWidget(controller: _controller),
              ));
              // await canLaunchUrl(Uri.parse(response.url))
              //     ? await launchUrl(Uri.parse(response.url))
              //     : throw 'Could not launch URL';

for payments. lib/pages/checkout.dart. change the whole class with this for shortcut.

class _CheckoutPageState extends State<CheckoutPage> {
  //  late WebViewController _controller ;
  late WebViewController _controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    // ..setBackgroundColor(const Color(0x00000000))
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          // Update loading bar.
          print('progress==>$progress');
        },
        onPageStarted: (String url) {
          print('url==>$url');
        },
        onPageFinished: (String url) {
          print('url==>$url');
          if (url == initialUrl) {
            _redirectToStripe();
          }
        },
        onWebResourceError: (WebResourceError error) {
          debugPrint('''
  Page resource error:
  code: ${error.errorCode}
  description: ${error.description}
  errorType: ${error.errorType}
  isForMainFrame: ${error.isForMainFrame}
          ''');
        },
        onNavigationRequest: (NavigationRequest request) {
          if (request.url.startsWith(checkoutSuccessUrl)) {
            Navigator.of(context).pop('success'); // <-- Handle success case
          } else if (request.url.startsWith(checkoutFailureUrl)) {
            Navigator.of(context).pop('cancel'); // <-- Handle cancel case
          }
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse(initialUrl));

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: WebViewWidget(
        controller: _controller,
        gestureRecognizers: <Factory<OneSequenceGestureRecognizer>>[
          Factory<VerticalDragGestureRecognizer>(
            () => VerticalDragGestureRecognizer(),
          ),
        ].toSet(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          var cookies = 'a';
          cookies = (await _controller
                  .runJavaScriptReturningResult('document.cookie'))
              .toString();
          print(cookies);
        },
        child: Icon(Icons.web_outlined),
      ),
    );
  }

  String get initialUrl =>
      'data:text/html;base64,${base64Encode(Utf8Encoder().convert(stripeHtmlPageScaffold))}';

  void _redirectToStripe() {
    final redirectToCheckoutJs = '''
      var stripe = Stripe(\'$stripePublicKey\');
      stripe.redirectToCheckout({
        sessionId: '${widget.sessionId}'
      }).then(function (result) {
        result.error.message = 'Error'
      });
    ''';
    try {
      _controller.runJavaScript(
          redirectToCheckoutJs); //<--- call the JS function on controller
    } catch (e) {
      print(e.toString());
    }
  }
}