React js Stripe checkout is not working

后端 未结 2 682
花落未央
花落未央 2021-02-13 19:59

I am trying to render a stripe checkout default form in React js application.

2条回答
  •  不知归路
    2021-02-13 20:45

    The main issue you are probably having is loading a script within React.

    One approach is to load the checkout script only when needed (assuming some form of spa), then just directly call it. This is akin to the "custom" version on the documentation page: https://stripe.com/docs/checkout#integration-custom

    If you are already loading checkout.js (for example before your "app.js"), then the below can be simplified a bit by not manually loading in the script.

    import React from 'react';
    
    export default class Cards extends React.Component {
    
        constructor(props:Object) {
            super(props);
            this.state = {
                loading: true,
                stripeLoading: true,
            };
        }
    
        loadStripe(onload:Function) {
            if(! window.StripeCheckout) {
                const script = document.createElement('script');
                script.onload = function () {
                    console.info("Stripe script loaded");
                    onload();
                };
                script.src = 'https://checkout.stripe.com/checkout.js';
                document.head.appendChild(script);
            } else {
                onload();
            }
        }
    
        componentDidMount() {
    
            this.loadStripe(() => {
                this.stripehandler = window.StripeCheckout.configure({
                    key: 'pk_test_xxxxxxxxxxxxxxxxxxxxxxxx',
                    image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
                    locale: 'auto',
                    token: (token) => {
                        this.setState({ loading: true });
                        axios.post('/your-server-side-code', {
                            stripeToken: token.id,
                        });
                    }
                });
    
                this.setState({
                    stripeLoading: false
                });
            });
        }
    
        componentWillUnmount() {
            if(this.stripehandler) {
                this.stripehandler.close();
            }
        }
    
        onStripeUpdate(e:Object) {
            this.stripehandler.open({
                name: 'test',
                description: 'widget',
                panelLabel: 'Update Credit Card',
                allowRememberMe: false,
            });
            e.preventDefault();
        }
    
        render() {
            const { stripeLoading, loading } = this.state;
            return (
                
    {(loading || stripeLoading) ?

    loading..

    : }
    ); } }

提交回复
热议问题