我正在为PayPal小部件实现智能按钮,我想知道如何去做。我现在的想法是制作一个按钮,看看我是否可以在其中放入脚本标签,从而使我付款。到目前为止,这是我的代码:
这是来自index.js文件
<button>Donate Here Plz</button>
这是我跳到项目之前已经编写的reactjs文件。
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,
price: 1.0,
priceError: true
};
window.React = React;
window.ReactDOM = ReactDOM;
}
componentDidMount() {
const { isScriptLoaded, isScriptLoadSucceed } = this.props;
if (isScriptLoaded && isScriptLoadSucceed) {
this.setState({ showButton: true });
}
}
handleInputChange = e => {
const re = /^\d*\.?\d{0,2}$/;
if (e.target.value === "" || re.test(e.target.value)) {
this.setState({ price: e.target.value });
}
if (this.state.price >= 1) {
this.state.priceError = false;
} else {
this.state.priceError = true;
}
console.log(this.state.priceError);
};
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 paypal = window.PAYPAL;
const {
currency,
env,
commit,
client,
onSuccess,
onError,
onCancel
} = this.props;
const { showButton, price } = this.state;
const payment = () =>
paypal.rest.payment.create(env, client, {
transactions: [
{
amount: {
total: price,
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);
});
const style = {
layout: "vertical", // horizontal | vertical
size: "medium", // medium | large | responsive
shape: "rect", // pill | rect
color: "gold" // gold | blue | silver | white | black
};
return (
<React.Fragment>
<form>
<h3 style={{ justifySelf: "center" }}>Donate Amount</h3>
<input
name="donate"
type="text"
placeholder="Minimum $1.00"
value={this.state.price}
onChange={this.handleInputChange}
className="donationInput"
/>
</form>
<br />
{showButton && (
<paypal.Button.react
style={style}
env={env}
client={client}
commit={commit}
payment={payment}
onAuthorize={onAuthorize}
onCancel={onCancel}
onError={onError}
/>
)}
</React.Fragment>
);
}
}
export default scriptLoader("https://www.paypalobjects.com/api/checkout.js")(
PaypalButton
);```
No error messages show up, but the button does not lead to anything.
答案 0 :(得分:0)
在我看来,您正在尝试使用旧版Checkout API。您可以在Paypal Checkout Buttons这里查看新版本V2。
如果需要,可以在NPM react-paypal-button-v2上查看新的V2按钮的npm软件包。
这表示您可以执行以下操作,该操作取自react-paypal-button-v2 github此处的npm软件包github,但没有打字稿,并且采用了功能组件形式:
import React, { useState, useEffect} from 'react';
import ReactDOM from 'react-dom';
const PaypalButton = props => {
const [sdkReady, setSdkReady] = useState(false);
const addPaypalSdk = () => {
const clientID =
'Your-Paypal-Client-ID';
const script = document.createElement('script');
script.type = 'text/javascript';
script.src = `https://www.paypal.com/sdk/js?client-id=${clientID}`;
script.async = true;
script.onload = () => {
setSdkReady(true);
};
script.onerror = () => {
throw new Error('Paypal SDK could not be loaded.');
};
document.body.appendChild(script);
};
useEffect(() => {
if (window !== undefined && window.paypal === undefined) {
addPaypalSdk();
} else if (
window !== undefined &&
window.paypal !== undefined &&
props.onButtonReady
) {
props.onButtonReady();
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
//amount goes in the value field we will use props of the button for this
const createOrder = (data, actions) => {
return actions.order.create({
purchase_units: [
{
amount: {
currency_code: 'USD',
value: props.amount,
}
}
]
});
};
const onApprove = (data, actions) => {
return actions.order
.capture()
.then(details => {
if (props.onSuccess) {
return props.onSuccess(data);
}
})
.catch(err => {
console.log(err)
});
};
if (!sdkReady && window.paypal === undefined) {
return (
<div>Loading...</div>
);
}
const Button = window.paypal.Buttons.driver('react', {
React,
ReactDOM
});
//you can set your style to whatever read the documentation for different styles I have put some examples in the style tag
return (
<Button
{...props}
createOrder={
amount && !createOrder
? (data, actions) => createOrder(data, actions)
: (data, actions) => createOrder(data, actions)
}
onApprove={
onSuccess
? (data, actions) => onApprove(data, actions)
: (data, actions) => onApprove(data, actions)
}
style={{
layout: 'vertical',
color: 'blue',
shape: 'rect',
label: 'paypal'
}}
/>
);
};
export default PaypalButton;
然后您可以像这样在组件中使用它:
const onSuccess = payment => {
console.log(payment)
}
const onCancel = data => {
console.log(data)
};
const onError = err => {
console.log(err);
};
<PaypalButton
amount="1.00"
onError={onError}
onSuccess={onSuccess}
onCancel={onCancel}
/>
请注意,这未经测试,我只是从npm软件包github中提取了它,并删除了打字稿,以便于阅读,但它应该使您了解如何操作以及如何向按钮添加捐赠逻辑。我强烈建议您阅读Paypals文档。经过是痛苦的,但必须这样做。如果您不希望自己创建按钮那么麻烦,则只需添加npm程序包,即可轻松进行操作。