0

I present my problem to you

with the following code I make a payment,

I would like that if the payment is refused I redirect to a page otherwise if the payment is accept I redirect to another page

do you have any idea how to do this?

I tried to simplify the code so that it is as clear as possible

Thanks for your help Neff

 import { Redirect } from 'react-router-dom';

 import React, { Component } from 'react';
 import { CardNumberElement, CardExpiryElement, CardCVCElement, injectStripe } from 'react- 
 stripe-elements';
 import { CardText, Col, Container, CardTitle, Button, Input, Card } from 'reactstrap';
 import './Payment.scss'


 const entrypoint = process.env.REACT_APP_API_ENTRYPOINT + '/api';

class _Form extends Component {

constructor(props) {
super(props);
this.state = {
  alertMessage: '',
  alertStyle: '',
  randomID: null,
  redirect: false,
  loading: false,
};
}

handleChange = (e) => {

this.setState({ [e.target.name]: e.target.value });
}



postbackend = () => {
 const newItems = this.props.items.map((item) => {
   const { title, quantity, } = item;
   return {
    title,
    quantity,

  };
});
const config = {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ ...this.state, items: newItems }),
};

const url = entrypoint + "/alluserpls";
fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error);
    } else {
      alert(`film ajouté avec l'ID ${res}!`);
    }
  }).catch(e => {
    console.error(e);

    }).finally(() => this.setState({ redirect: true }));
 }

 handleSubmit = async (ev) => {
ev.preventDefault();
this.setState({ loading: true });

this.props.stripe.createToken({ name: this.props.clientName })
  .then(result => {
    if (typeof (result.error) !== 'undefined') {
      this.setState({ error: result.error.message, success: '' });
      this.postbackend();
     } else {
      this.stripeCreateCharge(result.token, this.props.totalPrice).then(() => {
        this.postbackend();
      });
     }
  });
} 

stripeCreateCharge(token, amount) {
const params = { token: token.id, amount: amount };
const qParams = queryString.stringify(params);
const url = [entrypoint + "/stripe", qParams].join('?');

return fetch(url)
  .then(response => response.json())
  .then(val => {
    if (val.ok) {
      return val.message;
    } else {
      throw val.message;
    }
  })
  .then(success => {
    this.setState({ alertMessage: success, alertStyle: 'success' });
    return Promise.resolve()
  })
  .catch(error => this.setState({ alertMessage: error, alertStyle: 'danger' }));
}

render() {

const { loading } = this.state;
const redirect = this.state.redirect;

if (redirect) {
  return <Redirect to="/OderSummaryScreen" />

}
else {
  return (

    <div >
      <form method="post" onSubmit={(ev) => this.handleSubmit(ev)}>
        <Container>
          <CardTitle className='cardTitlePaymentFormComponent'>Entre ton moyen de paiement</CardTitle>

          <Card className="CardPaymenntFormComponenentCard">

            {/* <Alert msg={this.state.alertMessage} style={this.state.alertStyle} /> */}

            <div className="col12PaymentFormComponent">
              <div className="col8PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'>Numéro de Carte</CardText>
                <CardNumberElement className="cardNumberElementPaymentFormComponent" />
              </div>

              <div className="col4PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'> Expiration</CardText>
                <CardExpiryElement className="cardExpiryElementPaymentFormComponent" />
              </div>
            </div>
            <div className="col12PaymentFormComponent">
              <div className="col8PaymentFormComponent">
                <ClienInfo />
              </div>
              <div className="col4PaymentFormComponent">
                <CardText className='justOnlyForFunckingPaddindOnTextForPaymentFormComponent'>Cryptogramme</CardText>
                <CardCVCElement className="cardCVCElementPaymentFormComponent" />
              </div>
            </div>
          </Card>
        </Container>
                  <Container className='containerPaymentFooterContainer' >
                    <Col sm="12" className='col12PaymentsFooter'>

                      <Input onClick={this.handleClick} type="checkbox" required className="inputCheckboxPaymentsFooter" />{' '}
                      <CardText className='cardTextPaymentsFooter' > <a href="https://brable.io/mentions-legales/" target="blank" className="colorForLinkMaybeBlank"> Je reconnais avoir lu et pris connaissance des Termes, de la Charte de Confidentialité et des CGU, et les accepte.</a></CardText>
                    </Col>
                  </Container>
                  <Col sm="12" className='col12PaymentsFooterButtonCol12' >
                    {!loading && <div >
                      <Button className='buttonPaymentsFooterbutton' type="submit" value="Envoyer" disabled={loading} >
                        <CardTitle className="buttonPaymentsCardTitleFooter">PAYER </CardTitle>
                        <CardTitle className="buttonPaymentsCardTitleFooter" >{this.props.total} €  </CardTitle>
                      </Button>
                    </div>}
                    {loading && <div className="wtfloadingLogoHandeSpinerBro" ><Handespiner /> </div>}
                  </Col>
                </Form>
              )}
            </Formik>
          </Col>

        </Container>
      </form>
    </div>
  )
  };
 }
 }

const mapStateToProps = (state) => {
return {
items: state.addedItems,

 }
 }

 export default connect(mapStateToProps)(injectStripe(_Form))

1 Answer 1

1

In your postbackend function you can update your fetch request like this:

fetch(url, config)
  .then(res => res.json())
  .then(res => {
    if (res.error) {
      alert(res.error); 
      this.props.history.replace("/");  // Your Error Page
    } else {
      alert(`film ajouté avec l'ID ${res}!`);
      this.props.history.push("/"); // Your Success Page
    }
  }).catch(e => {
    console.error(e); 
    this.props.history.replace("/");  // Your Error Page
  }).finally(() => this.setState({
    redirect: true
  }));

The catch case will be invoked if case of any error. While your else part will take care of unsuccessful response from the server.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi man , ty for help , i got error Unhandled rejection (TypeError) :Cannot read property 'replace' of undefined
Wrap your component in a withRouter hoc from react-router-dom to have access to history. export default withRouter(connect(mapStateToProps)(injectStripe(_Form)))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.