gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:07 25 4
gpt4 key购买 nike

因此,来 self 熟悉的 PayPal 按钮的 Angular 背景,我无法让它为 React.js 工作。为有效的 react.js 构建 PayPal 按钮组件的方法是什么?有什么建议会有很大帮助吗?

最佳答案

有同样问题的 friend :这个简洁step-by-step guide可用于编写您自己的使用 PayPal REST API 的 React 组件。

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

  1. API 异步加载和 isScriptLoad* Prop 检查加载状态
  2. showButton 保持状态(可以渲染也可以不渲染)
  3. 绑定(bind)到DOM
  4. componentDidMount 对比 componentWillReceiveProps 检查 API 的加载状态
  5. 要传递给组件以管理交易的 Prop :total、currency、env、commit、client、onSuccess、onError、onCancel
  6. paymentauthorize 方法实际实现交易

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

关于javascript - 在 React.js 中制作一个 Paypal 按钮来结帐项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43482310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com