0
votes

guys, I'm trying to integrate brainTree in reactJs via hosted fields. Now I was able to integrate it in my project and also get it working to and was able to make a payment.

The problem that I'm facing is that when I try to enter the card number 4444 4444 4444 4444 I want to get an error like I got in dropin but it does not throw an error. If I enter 2 or 3 extra 4's with the above wrong card number I get an error. Can somebody please tell me what is it that I'm doing wrong. Thanks

please help me out I can't understand what is going wrong Here is my code:

   // Some Imports 

import BrainTree from 'braintree-web';
var dropin = require('braintree-web-drop-in');

export class Checkout extends Component {
    state = {
        valueEntered: 5,
        showSuccessMessage: false,
        showErrorMessage: false,
    };

    componentWillMount() {
        this.props.getClientToken();
    }

    checkoutPayment(nounce) {
        this.props.Checkout({
            paymentValue: this.state.valueEntered,
            paymentMethodNounce: nounce,
        });

    }


    // ONCE WE RECIEVE THE TOKEN THIS FUNCTION WILL BE CALLED SOMEHOW
    // AND HERE THE BRAINTREE WILL BE INTIALIZED
    componentWillReceiveProps(nextProps) {

        var button = document.querySelector('#submit-button');

        if (nextProps.user.clientToken && nextProps.user.clientToken != null && nextProps.user.clientToken !== this.props.user.clientToken) {
            BrainTree.client.create(
                {
                    authorization: nextProps.user.clientToken,
                },
                (err, clientInstance) => {
                    let me = this;
                    if (err) {
                        console.error(err);
                        return;
                    }

                    BrainTree.hostedFields.create(
                        {
                            client: clientInstance,
                            styles: {
                                input: {
                                    'font-size': '14px',
                                    'font-family':
                                        'helvetica, tahoma, calibri, sans-serif',
                                    color: '#3a3a3a',
                                },
                                ':focus': {
                                    color: 'black',
                                },
                            },
                            fields: {
                                number: {
                                    selector: '#card-number',
                                    placeholder: '4111 1111 1111 1111',
                                },
                                cvv: {
                                    selector: '#cvv',
                                    placeholder: '123',
                                },
                                expirationMonth: {
                                    selector: '#expiration-month',
                                    placeholder: 'MM',
                                },
                                expirationYear: {
                                    selector: '#expiration-year',
                                    placeholder: 'YY',
                                },
                                postalCode: {
                                    selector: '#postal-code',
                                    placeholder: '90210',
                                },
                            },
                        },
                        (err, hostedFieldsInstance) => {
                            if (err) {
                                console.error(err);
                                return;
                            }

                            hostedFieldsInstance.on('validityChange', function(
                                event
                            ) {
                                var field = event.fields[event.emittedBy];

                                if (field.isValid) {
                                    if (
                                        event.emittedBy === 'expirationMonth' ||
                                        event.emittedBy === 'expirationYear'
                                    ) {
                                        if (
                                            !event.fields.expirationMonth
                                                .isValid ||
                                            !event.fields.expirationYear.isValid
                                        ) {
                                            return;
                                        }
                                    } else if (event.emittedBy === 'number') {
                                        document.querySelector(
                                            '#card-number'
                                        ).nextSibling.innerHTML =
                                            '';
                                    }

                                    // Apply styling for a valid field

                                    document
                                        .querySelector('#' + field.container.id)
                                        .closest('.form-group')
                                        .classList.add('has-success');
                                } else if (field.isPotentiallyValid) {
                                    // Remove styling  from potentially valid fields
                                    document
                                        .querySelector('#' + field.container.id)
                                        .closest('.form-group')
                                        .classList.remove('has-warning');
                                    document
                                        .querySelector('#' + field.container.id)
                                        .closest('.form-group')
                                        .classList.remove('has-success');
                                    if (event.emittedBy === 'number') {
                                        document.querySelector(
                                            '#card-number'
                                        ).nextSibling.innerHTML =
                                            '';
                                    }
                                } else {
                                    // Add styling to invalid fields
                                    document
                                        .querySelector('#' + field.container.id)
                                        .closest('.form-group')
                                        .classList.add('has-warning');
                                    // Add helper text for an invalid card number
                                    if (event.emittedBy === 'number') {
                                        document.querySelector(
                                            '#card-number'
                                        ).nextSibling.innerHTML =
                                            'Looks like this card number has an error.';
                                    }
                                }
                            });

                            hostedFieldsInstance.on('cardTypeChange', function(
                                event
                            ) {
                                // Handle a field's change, such as a change in validity or credit card type

                                if (event.cards.length === 1) {
                                    document.querySelector(
                                        '#card-type'
                                    ).innerHTML =
                                        event.cards[0].niceType;
                                } else {
                                    document.querySelector(
                                        '#card-type'
                                    ).innerHTML =
                                        'Card';
                                }
                            });

                            button.addEventListener('click', event => {
                                event.preventDefault();
                                hostedFieldsInstance.tokenize(
                                    (err, payload) => {
                                        let paymentComponnet = me;
                                        if (err) {
                                            console.error(err);
                                            return;
                                        }
                                        paymentComponnet.checkoutPayment(
                                            payload.nonce
                                        );
                                        // This is where you would submit payload.nonce to your server
                                        // alert('Submit your nonce to your server here!');
                                    }
                                );
                            });
                        }
                    );
                }
            );
        }
    }
    handleChange = (field, value) => {
        this.setState({
            [field]: value,
        });
    };

    // HERE WE WILL RENDER OUR HTML
    render() {
        let paymentValue = this.state.valueEntered;

        return (
            <div styleName="organization-profile">
                <div className="form-group">
                    <label for="focusedInput">Amount</label>
                    <input
                        className="form-control"
                        id="amount"
                        name="amount"
                        type="tel"
                        min="1"
                        placeholder="Amount"
                        value={paymentValue}
                        onChange={e => {
                            this.handleChange('valueEntered', e.target.value);
                        }}
                    />
                </div>
                <div className="panel panel-default bootstrap-basic">
                    <div className="panel-heading">
                        <h3 className="panel-title">Enter Card Details</h3>
                    </div>
                    <form className="panel-body">
                        <div className="row">
                            <div className="form-group col-xs-8">
                                <label className="control-label">
                                    Card Number
                                </label>

                                <div
                                    className="form-control"
                                    id="card-number"
                                />
                                <span className="helper-text" />
                            </div>
                            <div className="form-group col-xs-4">
                                <div className="row">
                                    <label className="control-label col-xs-12">
                                        Expiration Date
                                    </label>
                                    <div className="col-xs-6">
                                        <div
                                            className="form-control"
                                            id="expiration-month"
                                        />
                                    </div>
                                    <div className="col-xs-6">
                                        <div
                                            className="form-control"
                                            id="expiration-year"
                                        />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="row">
                            <div className="form-group col-xs-6">
                                <label className="control-label">
                                    Security Code
                                </label>

                                <div className="form-control" id="cvv" />
                            </div>
                            <div className="form-group col-xs-6">
                                <label className="control-label">Zipcode</label>

                                <div
                                    className="form-control"
                                    id="postal-code"
                                />
                            </div>

                            <button
                                id="submit-button"
                                className="btn btn-success btn-lg center-block"
                            >
                                Pay with <span id="card-type">Card</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        );
    }
}



export default  Checkout;
1
What are validation rules for the credit card field?Brett DeWoody

1 Answers

1
votes

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.

The drop-in UI only displays error messages when a field loses focus. Based on your initial post, it seems like you're trying to display the error message if a user enters an invalid card number. The .on('validityChange') event is only emitted when either the isValid or isPotentiallyValid boolean changes. In your example using the number 4444 4444 4444 4444, the isValid boolean remains false and isPotentiallyValid doesn't switch from true to false until you enter the 19th digit. You can review the logic behind these checks here.

Based on what you've described, it seems like you want to use .on('blur') instead. This event is emitted when a field loses focus, at which point you'll be able to perform your checks on the card object to determine whether or not to show your error message. Additionally, you will likely want to update your conditional, because your else if (field.isPotentiallyValid) clause will catch the event - you can remove this clause to always show the error message if the card number is invalid.

hostedFieldsInstance.on('blur', function (event) {

  var field = event.fields[event.emittedBy];

  if (field.isValid) {
    // Handle valid field
  } else {
    // Add styling to invalid fields
  }

});