制作PayPal按钮来结帐React.js中的项目?

时间:2017-04-18 21:14:49

标签: javascript reactjs paypal

所以来自我熟悉的PayPal按钮的角度背景,我无法让它为React.js工作。为react.js构建PayPal按钮组件的方法是什么?任何建议都会有很大帮助吗?

1 个答案:

答案 0 :(得分:0)

任何有同样问题的人:这个简洁的step-by-step guide可以用来编写你自己的使用PayPal REST API的React组件。

在下面的代码片段中,请注意:

  1. 异步加载API和isScriptLoad*道具以检查加载状态
  2. showButton来保持状态(可以渲染与否)
  3. 绑定到DOM
  4. componentDidMount vs componentWillReceiveProps检查API的加载状态
  5. 将道具传递给组件以管理交易:总计,货币,环境,提交,客户,onSuccess,onError,onCancel
  6. 实际实施交易的
  7. paymentauthorize方法
  8. 
    
    import React from 'react';
    import ReactDOM from 'react-dom';
    import scriptLoader from 'react-async-script-loader';
    
    class PaypalButton extends React.Component {
      constructor(props) {
    super(props);
    
    this.state = {
      showButton: false,
    };
    
    window.React = React;
    window.ReactDOM = ReactDOM;
      }
    
      componentDidMount() {
    const {
      isScriptLoaded,
      isScriptLoadSucceed
    } = this.props;
    
    if (isScriptLoaded && isScriptLoadSucceed) {
      this.setState({ showButton: true });
    }
      }
    
      componentWillReceiveProps(nextProps) {
    const {
      isScriptLoaded,
      isScriptLoadSucceed,
    } = nextProps;
    
    const isLoadedButWasntLoadedBefore =
      !this.state.showButton &&
      !this.props.isScriptLoaded &&
      isScriptLoaded;
    
    if (isLoadedButWasntLoadedBefore) {
      if (isScriptLoadSucceed) {
        this.setState({ showButton: true });
      }
    }
      }
    
      render() {
    const {
      total,
      currency,
      env,
      commit,
      client,
      onSuccess,
      onError,
      onCancel,
    } = this.props;
    
    const {
      showButton,
    } = this.state;
    
    const payment = () =>
      paypal.rest.payment.create(env, client, {
        transactions: [
          {
            amount: {
              total,
              currency,
            }
          },
        ],
      });
    
    const onAuthorize = (data, actions) =>
      actions.payment.execute()
        .then(() => {
          const payment = {
            paid: true,
            cancelled: false,
            payerID: data.payerID,
            paymentID: data.paymentID,
            paymentToken: data.paymentToken,
            returnUrl: data.returnUrl,
          };
    
          onSuccess(payment);
        });
    
    return (
      <div>
        {showButton && <paypal.Button.react
          env={env}
          client={client}
          commit={commit}
          payment={payment}
          onAuthorize={onAuthorize}
          onCancel={onCancel}
          onError={onError}
        />}
      </div>
    );
      }
    }
    
    export default scriptLoader('https://www.paypalobjects.com/api/checkout.js')(PaypalButton);
    &#13;
    &#13;
    &#13;