在 React.js 中制作一个paypal按钮来结帐项目?

IT技术 javascript reactjs paypal
2021-04-15 05:51:09

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

1个回答

任何有同样问题的人:这个简明的分步指南可用于编写您自己的使用 PayPal REST API 的 React 组件。

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

  1. 异步加载 API 和isScriptLoad*检查加载状态的props
  2. showButton 保持状态(可以渲染或不渲染)
  3. 绑定到 DOM
  4. componentDidMountvscomponentWillReceiveProps检查 API 的加载状态
  5. 传递给组件以管理交易的props:total、currency、env、commit、client、onSuccess、onError、onCancel
  6. payment以及authorize实际实现交易的方法

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);