Search code examples
angularbraintree

How can I reset the credit card fields on failure transaction in Braintree sdk


I have implemented Braintree sdk for credit card payment.

How can I reset the credit card information on failure of the transaction?

I got the response as processor_declined.

On error, I want to remove the existing card information and reset the fields.

enter image description here

Thanks

$scope.getToken= function()
{
var data = { 'action': 'GETTOKEN'};
var dataJson =  JSON.stringify(data);
var url = 'api/db/getToken.php';
$http.post( url,dataJson)
.success(function(res) {
  if(res)
  {
    if(swal)
      swal.close();

    var authorization = 'production_xxxxxxxx';
    var response = angular.fromJson(res.value);
    if(res.result === 'Success')
    {
      if(res.value){
        $scope.clientToken =res.value.token;
        var submitButton = document.querySelector('#shopin_subscribe');
        braintree.dropin.create({
          authorization: $scope.clientToken,
          selector: '#dropin-container',
          paymentOptionPriority: ['card']
        }, function (err, dropinInstance) {
          if(submitButton){
            submitButton.addEventListener('click', function () {
              dropinInstance.requestPaymentMethod(function (err, payload) {
               if (err) {
                 console.info("Error", err);
                  return;
                }
                $scope.payForPlan(payload.nonce);
              });
            });
          }

         if (dropinInstance.isPaymentMethodRequestable()) {
            // this will be true if you generated the client token
           // with a customer ID and there is a saved payment method
           // available to tokenize with that customer
            submitButton.removeAttribute('disabled');
           if($scope.planId === $scope.currentPlan[0]) {
                $scope.disablePayButton=true;
                if(submitButton){
                  submitButton.setAttribute('disabled', true);
                }
                return;
            }
         }

         dropinInstance.on('paymentMethodRequestable', function (event) 
         {
           event.type; // the type of Payment Method, IE CreditCard, PayPalAccount
           submitButton.removeAttribute('disabled');
           if($scope.planId === $scope.currentPlan[0]) {
                $scope.disablePayButton=true;
                if(submitButton){
                  submitButton.setAttribute('disabled', true);
                }
                return;
            }
         });
         dropinInstance.on('noPaymentMethodRequestable', function () {
           submitButton.setAttribute('disabled', true);
         });
       });        
     }
   }
 }
}) ;
}
$scope.payForPlan = function(nonce)
{
swal({   title: "Payment Processing",   timer:10000, text: htmldiv,   html: true,  type: "warning", showCancelButton: false, showConfirmButton: false,  confirmButtonColor: "#DD6B55",   confirmButtonText: "Please wait ...",   closeOnConfirm: false }, function(){    });
   var data = { 'action': 'PROCESS','userId': $scope.user.hashID, 'plan': $scope.planSelected[0],'payment_method_nonce':nonce};
var dataJson =  JSON.stringify(data);

console.info ("JSON String get data"+ dataJson);
var url = 'api/db/btpay.php';

$http.post( url,data)
.success(function(res) {
  if($scope.checkout){
    $scope.checkout.teardown(function () {
      $scope.checkout = null;
    });
  }
  if(res) {
    //swal.close();
    console.info ('checkout response received :' +JSON.stringify(res));
    var response = angular.fromJson(res.value);

    if(res.result === 'Success') {
      var planName = $scope.plansList[response.subscription.planId][1];
      var planString="Congrats! you plan changed to "+ planName;
      $scope.vm.user.planType=response.subscription.planId;
      $rootScope.user.planType=response.subscription.planId;
      $scope.currentPlan=$scope.plansList[response.subscription.planId];
      $scope.currentPlanSubscription = response.subscription;
      $scope.tappedOnPlan = false;
      $rootScope.user.subscriptionId = $scope.vm.user.subscriptionId = response.subscription.id;
      $scope.updateOperation = true;
      $rootScope.globals = JSON.stringify($rootScope.user);

      $cookies['globals'] = $rootScope.globals;

      var submitButton = document.querySelector('#shopin_subscribe');
      submitButton.setAttribute('disabled', true);
      $location.path('app/profile');
      swal("", planString, "success");
    }
    else {
      var failureStr=response.message;
      swal("", failureStr, "error");
    }
  } else {
    swal.close();
    console.info ('checkoutfailed :');
  }
});
return false;
}

Solution

  • You'll need to update to the latest version of Drop-in (as of this writing, 1.6.0) and use clearSelectedPaymentMethod. Here are the docs for it: https://braintree.github.io/braintree-web-drop-in/docs/current/Dropin.html#clearSelectedPaymentMethod

    Here's the example from the documentation:

    dropinInstance.requestPaymentMethod(function (requestPaymentMethodError, payload) {
      if (requestPaymentMethodError) {
        // handle errors
        return;
      }
    
      functionToSendNonceToServer(payload.nonce, function (transactionError, response) {
        if (transactionError) {
          // transaction sale with selected payment method failed
          // clear the selected payment method and add a message
          // to the checkout page about the failure
          dropinInstance.clearSelectedPaymentMethod();
          divForErrorMessages.textContent = 'my error message about entering a different payment method.';
        } else {
          // redirect to success page
        }
      });
    });
    

    Obviously, you fill in the functionToSendNonceToServer with your $http.post('api/db/btpay.php',data) bit.