после успешной оплаты, ошибка броска PayPal - Нет ответа из окна. убрано - PullRequest
1 голос
/ 25 октября 2019

Я внедряю платежный шлюз Paypal с React. Я следую инструкции от robinwieruch.de .

. Я могу завершить процедуру оплаты, но после оплаты она выдает no response from window. cleaned up. в firefox мое приложение вылетает, но в chrome оно только регистрирует ошибку на консоли (без сбоев). No response from window, PayPal error

Cart.js

import Paypal from '../common/Paypal';

const imgStyle = {
    width: `150px`,
    height: `60px`
}

class Cart extends Component{
    state = {
        courierClass: ''
    }
    isValidPayment = (e)=>{
        e.preventDefault();
        if(!this.props.isAuthenticated){
            this.props.errorHandler('please signin to continue');
            this.props.history.push('/user/signin');
        }
        else {
            return true;
        }
    }

    addOrders = (payment) => {
        this.props.successHandler('payment successful. we are processing you order request');
        this.setState({
            isSubmitting: true
        })

        this.props.orderHandler(send order data to server)
        .then(()=>{
            this.setState({
                isSubmitting: false
            })
            this.props.history.push('/')
        })
        .catch(()=> this.setState({
            isSubmitting: false
        }))
    }

    onPaymentCancel = (data) => {
        this.props.errorHandler('you cancel the payment');
        console.log('The payment was cancelled!', data);
    }

    onPaymentError = (err) => {
        console.log(err, 'error');
        this.props.errorHandler(`we can't process your payment now.`)
    }


    render(){
        let { isAuthenticated,} = this.props;
        let {courierClass, isSubmitting} = this.state;
        let totalPrice = 0;
        cart.items.forEach(({item, item_quantity})=>{
            totalPrice += (item.price * item_quantity)
        })

        let env = 'sandbox';
        let currency = 'GBP';
        let style={
            shape: 'rect',
            size: 'medium',
            label: 'checkout',
            tagline: false
        } 
        // let total = totalPrice; 
        const client = {
            sandbox: process.env.REACT_APP_SANDBOX_APP_ID,
        }

        return (
            <div className="container">
                { courierClass ? <Paypal 
                    env={env} 
                    client={client} 
                    currency={currency} 
                    total={totalPrice}
                    style={style}
                    onClick={this.isValidPayment}
                    onError={this.onPaymentError} 
                    onSuccess={this.addOrders} 
                    onCancel={this.onPaymentCancel} /> : null
                }

            </div>
        )
    }
}

function mapStateToProps(state){
    return {
        isAuthenticated: state.currentUser.isAuthenticated
    }
}

export default connect(mapStateToProps, {})(Cart)

** Paypal.js **

import React from 'react';
import ReactDOM from 'react-dom';
import scriptLoader from 'react-async-script-loader';
const {NODE_ENV, REACT_APP_SANDBOX_APP_ID, REACT_APP_PAYPAL_APP_ID } = process.env
class Paypal 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 });
            }
        }
    }

    componentWillUnmount(){
        // this.setState({
        //  showButton: false
        // });
        // this.paypal = null
    }

    render() {
        const paypal = window.PAYPAL;
        const { total, commit, onSuccess, onError, onCancel,} = this.props;
        const { showButton} = this.state;
        // let style = {
        //  size: 'small',
        //  color: 'gold',
        //  shape: 'pill',
        //  label: 'checkout: Just $2.99!'
        // }
        let env = NODE_ENV === 'production' ? 'live' : 'sandbox'  ;
        let currency = 'GBP';
        const client = {
            sandbox: REACT_APP_SANDBOX_APP_ID,
            live: REACT_APP_PAYPAL_APP_ID
        }
        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 (
            showButton ? <paypal.Button.react
                env={env}
                client={client}
                commit={commit}
                payment={payment}
                onAuthorize={onAuthorize}
                onCancel={onCancel}
                onError={onError}
                style={{
                    shape: 'rect',
                    size: 'medium',
                    label: 'pay',
                    tagline: false
                }}
            /> : null
        );
    }
}

export default scriptLoader('https://www.paypalobjects.com/api/checkout.js')(Paypal);

IЯ использую этот Paypal.js и в других компонентах, такая же проблема есть. пожалуйста помоги. сейчас это стало головной болью для меня, и я должен развернуть это сегодня.

Я также ищу его на странице PayPal GitHub, но они сказали, что они решили проблему Проблема PayPal .

Нужно ли мне обновить Payapl, как описано в PayPal Docs

Обновление

Мой payment.returnUrl имеет ошибку https://www.paypal.com/checkoutnow/error?paymentId=PAYID-syufsaddhew&token=EC-shdgasdPayerID=dasgda,Я установил обратный URL на localhost

...