Как импортировать файл html со скриптом в файле реаги. js? - PullRequest
0 голосов
/ 06 марта 2020

В моем Reactjs проекте с nodejs я пытаюсь интегрировать PayPal. Поэтому я создал файл .html с кнопкой PayPal, и мне нужно поместить эту кнопку PayPal в один из моих файлов js. enter image description here

Как показано на рисунке, мне нужно сделать кнопку PayPal и что у меня есть:

test. html

    <div id="paypal-button"></div>
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>
    <script>
           paypal.Button.render(
{
  // Configure environment
  env: "sandbox",
  client: {
    sandbox: "demo_sandbox_client_id",
    production: "demo_production_client_id"
  },
  // Customize button (optional)
  locale: "en_US",
  style: {
    size: "small",
    color: "gold",
    shape: "pill"
  },

  // Enable Pay Now checkout flow (optional)
  commit: true,

  // Set up a payment
  payment: function(data, actions) {
    return actions.payment.create({
      transactions: [
        {
          amount: {
            total: "0.01",
            currency: "USD"
          }
        }
      ]
    });
  },
  // Execute the payment
  onAuthorize: function(data, actions) {
    return actions.payment.execute().then(function() {
      // Show a confirmation message to the buyer
      window.alert("Thank you for your purchase!");
    });
  }
},
"#paypal-button"
);

paymentOptions. js

  import htmlContent from "path to/test.html";----->Trying to import that html file but fails with error.
 render = () => {
       <div className="ui middle aligned animated celled selection list">
                      {payment.cards.map(card => (
                        <div
                          className={
                            (selectedCard === card._id ? "disabled " : "") +
                            "item"
                          }
                          key={card._id}
                          onClick={() => {
                            selectCard(card._id);
                          }}
                        >
                          {selectedCard === card._id && (
                            <i className="green check icon" />
                          )}
                          <div className="content">
                            <div className="header">
                              {card.brand} ending in {card.last4}
                            </div>
                            {card.name && (
                              <div className="description">
                                Name: {card.name}
                              </div>
                            )}
                          </div>
                        </div>
                      ))}
                      <div
                        className={
                          ("" === selectedCard ? "disabled " : "") + "item"
                        }
                        key="newCard"
                        onClick={() => {
                          selectCard("");
                        }}
                      >
                        {"" === selectedCard && (
                          <i className="green check icon" />
                        )}
                        <div className="content">
                          <div className="header">New card</div>
                        </div>
                      </div>

                      <div
                        className={
                          (selectedCard === "paypal" ? "disabled " : "") +
                          "item"
                        }
                        key="paypal"

                      >
                        {selectedCard === "paypal" && (
                          <i className="green check icon" />
                        )}
                        <div className="content">
                          Paypal

                        </div>
                      </div>
                    </div>
 }

И ошибка:

   Module parse failed: Unexpected token (1:0)
   You may need an appropriate loader to handle this file type.
   | <div id="paypal-button"></div>
   | <script src="https://www.paypalobjects.com/api/checkout.js"></script>
   | <script>

Как я могу решить эту проблему и выполнить кнопку PayPal?

1 Ответ

1 голос
/ 06 марта 2020

Вы можете использовать реагировать-асин c -скрипт-загрузчик

Поскольку вы работаете с продуктом reactjs, вы можете написать компонент реагирования, чтобы сделать то же самое вместо использование HTML файла.

здесь https://cubettech.com/resources/blog/integrating-paypal-rest-api-with-react-js/ является хорошим примером этого.

компонент PayPal:

import React from 'react';
import ReactDOM from 'react-dom';
import scriptLoader from 'react-async-script-loader';
import PropTypes from 'prop-types';

class PaypalButton extends React.Component {
    constructor(props) {
        super(props);
        window.React = React;
        window.ReactDOM = ReactDOM;
        this.state = {
            showButton: false,
            env: 'sandbox', // Or 'sandbox'
            client: {
                sandbox: 'xxxxxxxxx', // sandbox client ID
                production: 'xxxxxxxxx' // production client ID
            },
            commit: true, // Show a 'Pay Now' button
        };
    }

    componentDidMount() {
        const {isScriptLoaded, isScriptLoadSucceed} = this.props;
        if (isScriptLoaded && isScriptLoadSucceed) {
            this.setState({showButton: true});
        }
    }

    componentWillReceiveProps({isScriptLoaded, isScriptLoadSucceed}) {
        if (!this.state.show) {
            if (isScriptLoaded && !this.props.isScriptLoaded) {
                if (isScriptLoadSucceed) {
                    this.setState({showButton: true});
                } else {
                    console.log('Cannot load Paypal script!');
                    this.props.onError();
                }
            }
        }
    }

    render() {
        const payment = () => paypal.rest.payment.create(this.props.env, this.props.client, {
            transactions: [
                {amount: {total: this.props.total, currency: this.props.currency}},
            ],
        });

        const onAuthorize = (data, actions) => actions.payment.execute().then(() => {
            const payment = Object.assign({}, this.props.payment);
            payment.paid = true;
            payment.cancelled = false;
            payment.payerID = data.payerID;
            payment.paymentID = data.paymentID;
            payment.paymentToken = data.paymentToken;
            payment.returnUrl = data.returnUrl;
            this.props.onSuccess(payment);
        });

        let ppbtn = '';
        if (this.state.showButton) {
            ppbtn = (<paypal.Button.react
                env={this.state.env}
                client={this.state.client}
                payment={payment}
                commit
                onAuthorize={onAuthorize}
                onCancel={this.props.onCancel}
            />);
        }
        return <div>{ppbtn}</div>;
    }
}

PaypalButton.propTypes = {
    currency: PropTypes.string.isRequired,
    total: PropTypes.number.isRequired,
    client: PropTypes.object.isRequired,
};

PaypalButton.defaultProps = {
    env: 'sandbox',
    onSuccess: (payment) => {
        console.log('The payment was succeeded!', payment);
    },
    onCancel: (data) => {
        console.log('The payment was cancelled!', data);
    },
    onError: (err) => {
        console.log('Error loading Paypal script!', err);
    },
};

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

Компонент приложения

import React from 'react';
import PaypalExpressBtn from './PayPalExpressCheckOut';

export default class MyApp extends React.Component {
    render() {      
        const onSuccess = (payment) => {
            console.log("Your payment was succeeded!", payment);
        }           
        const onCancel = (data) => {
            // User pressed "cancel" or close Paypal's popup! 
            console.log('You have cancelled the payment!', data);
        }           
        const onError = (err) => {
 // The main Paypal's script cannot be loaded or somethings block the loading of that script! 
            console.log("Error!", err);
// Since the Paypal's main script is loaded asynchronously from "https://www.paypalobjects.com/api/checkout.js" 
// => sometimes it may take about 0.5 second for everything to get set, or for the button to appear          
        }                   
        let currency = 'USD'; // or you can set this value from your props or state   
        let total = 1; // same as above, this is the total amount (based on currency) to be paid by using Paypal express checkout 
 return (
            <PaypalExpressBtn 
currency={currency}
total={total}
onError={onError}
onSuccess={onSuccess}
onCancel={onCancel}
 />
        );
    }  
 }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...