无法在REACT中创建新的AdyenCheckout

时间:2019-07-08 13:42:49

标签: javascript reactjs adyen

我是Adyen的新手,而Javascript和REACT则相对较新。我试图在REACT中使用Adyen dropin组件,但无法创建新的AdyenCheckout组件。

我已使用以下代码将Adyen Javascript加载到componentDidMount中:

const script = document.createElement("script");
script.src = "https://checkoutshopper- 
test.adyen.com/checkoutshopper/sdk/3.0.0/adyen.js";
script.async = true;
document.body.appendChild(script);

我正在尝试使用以下代码创建AdyenCheckout组件:

const configuration = {
locale: "en_US",
environment: "test",
originKey: "YOUR_ORIGIN_KEY",
paymentMethodsResponse: this.state.paymentMethodsResponse,
};

const checkout = new AdyenCheckout(configuration);
const dropin = checkout
    .create('dropin', {
        onSubmit: (state, dropin) => {
        },
        onAdditionalDetails: (state, dropin) => {
        }
    })
.mount('#dropin');`

或者,通过更改 new AdyenCheckout(configuration)new window.AdyenCheckout(configuration)

过去人们似乎已经在使用此语法方面取得了成功。

  

使用new AdyenCheckout(configuration)

,出现错误AdyenCheckout is not defined

  

使用new window.AdyenCheckout(configuration)

,出现错误TypeError: window.AdyenCheckout is not a constructor

我确信这很简单,我做错了,因此,如果有人可以帮助,将不胜感激。

请帮助!

2 个答案:

答案 0 :(得分:0)

使用componentDidMount初始化AdyenCheckout对象,因为它可以访问DOM。


class AdyenDropin extend Component {
  contructor(props){
    this.checkout = {};
  }

  componentDidMount(){
    const script = document.createElement("script");
    script.src = "https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/3.0.0/adyen.js";
    script.async = true;
    document.body.appendChild(script);

    const configuration = {
      locale: "en_US",
      environment: "test",
      originKey: "YOUR_ORIGIN_KEY",
      paymentMethodsResponse: this.state.paymentMethodsResponse,
    };

    const checkout = new AdyenCheckout(configuration);
    const dropin = checkout
      .create('dropin', {
        onSubmit: (state, dropin) => {
        },
        onAdditionalDetails: (state, dropin) => {
        }
      })
      .mount('#dropin');`
    }
  }

  render(){
    return <div id="dropin"></div>
  }
}

答案 1 :(得分:0)

这是在尝试实际加载脚本之前尝试启动AdyenCheckout。

针对这些情况的最简单解决方案是在HTML文档中添加脚本标签。这样,脚本将在启动React App之前加载。

话虽如此,由于您只会在特定部分使用脚本,因此在React应用程序中添加script标签确实有意义。

要解决此问题,只需将与AdyenCheckout相关的所有功能移至脚本加载后即可调用的方法:

class AdyenDropin extends Component {
  constructor(props) {
    super(props);
    this.initAdyenCheckout = this.initAdyenCheckout.bind(this);
  }

  componentDidMount() {
    const script = document.createElement("script");
    script.src =
      "https://checkoutshopper-test.adyen.com/checkoutshopper/sdk/3.0.0/adyen.js";
    script.onload = this.initAdyenCheckout; // Wait until the script is loaded before initiating AdyenCheckout
    document.body.appendChild(script);
  }

  initAdyenCheckout() {
    // ...

这里有一个working example

干杯!