将HtmlElementView与PayPal结合使用 [英] Using HtmlElementView With PayPal

查看:281
本文介绍了将HtmlElementView与PayPal结合使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Flutter Web项目.我需要将以下HTML脚本放入 HtmlElementView :

I have a Flutter Web project. I have the following HTML script that I need to put into HtmlElementView:

<script src="https://www.paypal.com/sdk/js?client-id=YOUR_CLIENT_ID"></script>
<script>paypal.Buttons().render('body');</script>

来自此处.我已经尝试过了:

from here. I have tried this:

Widget build(BuildContext context) {
    // ignore: undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'paypal-button',
        (int viewId) => IFrameElement()
        ..width = '500'
        ..height = '500'
        ..src = '''
        <div id="paypal-button-container"></div>
        <script src="https://paypal.com/sdk/js?client-id=MY_CLIENT_ID"></script>
        <script>
        paypal.Buttons({

            // Set up the transaction
            createOrder: function(data, actions) {
                return actions.order.create({
                    purchase_units: [{
                        amount: {
                            value: '0.01'
                        }
                    }]
                });
            },

            // Finalize the transaction
            onApprove: function(data, actions) {
                return actions.order.capture().then(function(details) {
                    // Show a success message to the buyer
                    alert('Transaction completed by ' + details.payer.name.given_name + '!');
                });
            }


        }).render('#paypal-button-container');
    </script>
        '''
    );
    return SizedBox(
      height: 300,
      width: 500,
      child: Center(
        child: HtmlElementView(
          viewType: 'paypal-button',
        ),
      ),
    );
  }

注意:此代码用于 https://developer.paypal. com/demo/checkout/#/pattern/client

此代码不显示任何按钮,并出现以下错误:

This code doesn't show any buttons and gives the following errors:

状态不佳:未来已经完成

Bad state: Future already completed

URL包含删除的空白字符(\n\r\t)和小于字符(<)的资源请求被阻止.请删除换行符,并从元素属性值之类的地方编码少于字符,以便加载这些资源.有关更多详细信息,请参见 https://www.chromestatus.com/feature/5735596811091091968 .. >

Resource requests whose URLs contained both removed whitespace (\n, \r, \t) characters and less-than characters (<) are blocked. Please remove newlines and encode less-than characters from places like element attribute values in order to load these resources. See https://www.chromestatus.com/feature/5735596811091968 for more details.

我需要知道的是如何显示此代码段作为Widget,以便Flutter Web项目能够接受Paypal付款.感谢您的帮助!

What I need to know is how can I display this code snippet as a Widget in order for my Flutter Web project to be able to accept Paypal payments. Thanks for any help!

推荐答案

当前,将PayPal按钮集成到flutter web的唯一方法是将它们包装在IFrame容器中:

Currently, the only way to integrate PayPal buttons into flutter web is to wrap them in an IFrame container:

class PayPalWidget extends StatefulWidget {
  @override
  _PayPalState createState() => _PayPalState();
}

class _PayPalState extends State<PayPalWidget> {
  html.IFrameElement _element;

  @override
  void initState() {
    _element = html.IFrameElement()
      ..width = "200px"
      ..height = "200px"
      ..style.border = 'none'
      ..srcdoc = """
        <!DOCTYPE html>
        <html>
          <body>
            <script src="https://www.paypal.com/sdk/js?client-id=sb"></script>
            <script>
              paypal.Buttons(
                {
                  createOrder: function(data, actions) {
                    return actions.order.create({
                      purchase_units: parent.purchase_units
                    });
                  },
                  onApprove: function(data, actions) {
                    return actions.order.capture().then(function(details) {
                      parent.flutter_feedback('Transaction completed by ' + details.payer.name.given_name);
                    });
                  }
                }

              ).render('body');
            </script>
          </body>
        </html>
        """;

    js.context["purchase_units"] = js.JsObject.jsify([
      {
        'amount': {'value': '0.02'}
      }
    ]);
    js.context["flutter_feedback"] = (msg) {
      Scaffold.of(context).showSnackBar(SnackBar(content: Text(msg)));
    };

    // ignore:undefined_prefixed_name
    ui.platformViewRegistry.registerViewFactory(
      'PayPalButtons',
      (int viewId) => _element,
    );

    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 220,
      height: 220,
      child: HtmlElementView(viewType: 'PayPalButtons'),
    );
  }
}

但是请记住,这种方法远非理想,因为每次更新小部件时都会重新创建IFrame.我添加了代码来证明这种不利影响:

But keep in mind that this method is far from ideal, since the IFrame is re-created every time the widget is updated. I added code to demonstrate this downside effect:

import 'dart:ui' as ui;
import 'dart:js' as js;
import 'package:universal_html/html.dart' as html;
import 'package:flutter/material.dart';

class NextLabPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          leading: BackButton(),
          title: Text('PayPal integration'),
          centerTitle: true,
        ),
        body: Center(
          child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Noise(),
                PayPalWidget(),
              ]),
        ),
      ),
    );
  }
}

class Noise extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(
        child: Text('Make Noise'),
        onPressed: () {
          Scaffold.of(context).showSnackBar(
            SnackBar(
              content:
                  Text("PayPal buttons will be re-created when I disappear"),
            ),
          );
        },
      ),
    );
  }
}

// PayPalWidget code
// ...

按下发出声音"按钮以显示小吃栏-当消息消失时,这些按钮也消失.或将鼠标悬停在AppBar中的后退箭头"上,然后移开以显示相同的效果.

Push 'Make sound' button to show snackbar - when message disappears, the buttons disappear too. Or hover your mouse over the "back arrow" in the AppBar and move away to show the same effect.

这篇关于将HtmlElementView与PayPal结合使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆