protected void SaveCardButton_Click(object sender, EventArgs e)
        {
            int   profileId             = AlwaysConvert.ToInt(HiddenProfileId.Value);
            Label ProfileSuccessMessage = (Label)PageHelper.RecursiveFindControl(Page, "ProfileSuccessMessage");
            Label ProfileErrorMessage   = (Label)PageHelper.RecursiveFindControl(Page, "ProfileErrorMessage");

            if (profileId > 0)
            {
                var profile = GatewayPaymentProfileDataSource.Load(profileId);
                if (profile != null)
                {
                    int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                    PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);

                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            AccountDataDictionary cardDetails = new AccountDataDictionary();
                            cardDetails["AccountNumber"]   = "XXX" + profile.ReferenceNumber.Replace("x", "X");
                            cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                            cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                            cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                            PaymentMethod         method = PaymentMethodDataSource.Load(profile.InstrumentTypeId);
                            PaymentInstrumentData instr  = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                            var rsp = provider.DoUpdatePaymentProfile(new CommerceBuilder.Payments.Providers.UpdatePaymentProfileRequest(AbleContext.Current.User, instr, profile.CustomerProfileId, profile.PaymentProfileId));
                            if (rsp.Successful || rsp.ResponseCode == "E00040")
                            {
                                int id = profile.Id;
                                profile.Expiry = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                profile.Save();
                                if (ProfileSuccessMessage != null)
                                {
                                    ProfileSuccessMessage.Text    = string.Format("Profile '{0} ending in {1}' updated successfully!", profile.InstrumentType, profile.ReferenceNumber);
                                    ProfileSuccessMessage.Visible = true;
                                    ProfileErrorMessage.Visible   = false;
                                }
                            }
                            else
                            {
                                if (ProfileErrorMessage != null)
                                {
                                    ProfileErrorMessage.Text      = string.Format("Somthing went wrong! Unable to update profile '{0} ending in {1}'", profile.InstrumentType, profile.ReferenceNumber);
                                    ProfileSuccessMessage.Visible = false;
                                    ProfileErrorMessage.Visible   = true;
                                }

                                Logger.Error(rsp.ResponseMessage);
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                        }
                    }
                }
            }
            EditCardInfoPopUp.Hide();
        }
        protected void RemoveCardButton_Click(object sender, EventArgs e)
        {
            int profileId = AlwaysConvert.ToInt(PreferedCreditCard.SelectedValue);

            if (profileId > 0)
            {
                var profile = GatewayPaymentProfileDataSource.Load(profileId);
                if (profile.Subscriptions.Count == 0)
                {
                    int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                    PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            var rsp = provider.DoDeletePaymentProfile(new CommerceBuilder.Payments.Providers.DeletePaymentProfileRequest(AbleContext.Current.User, profile.CustomerProfileId, profile.PaymentProfileId));
                            if (rsp.Successful || rsp.ResponseCode == "E00040")
                            {
                                profile.Delete();
                                BindPayments();
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                        }
                    }
                }
            }
        }
        protected void Page_Init(object sender, EventArgs e)
        {
            // REDIRECT IF NO PROVIDER AVAILABLE
            _PaymentGatewayId = AlwaysConvert.ToInt(Request.QueryString["PaymentGatewayId"]);
            _PaymentGateway   = PaymentGatewayDataSource.Load(_PaymentGatewayId);
            if (_PaymentGateway == null)
            {
                Response.Redirect("Gateways.aspx");
            }
            _ProviderInstance = _PaymentGateway.GetInstance();
            if (_ProviderInstance == null)
            {
                Response.Redirect("Gateways.aspx");
            }

            // INITIALIZE THE FORM
            Caption.Text = string.Format(Caption.Text, _ProviderInstance.Name);

            // DETERMINE IF PAYMENT METHODS SHOULD SHOW FOR THIS PROVIDER
            if (ShowPaymentMethods(_PaymentGateway))
            {
                LoadPaymentMethods();
            }
            else
            {
                trPaymentMethods.Visible = false;
            }
        }
 private void SaveGateWay()
 {
     _PaymentGateway.UpdateConfigData(this.GetConfigData());
     _PaymentGateway.Save();
     _ProviderInstance = _PaymentGateway.GetInstance();
     if (ShowPaymentMethods(_PaymentGateway))
     {
         //UPDATE PAYMENT METHODS
         int index = 0;
         foreach (DataListItem item in PaymentMethodList.Items)
         {
             int           paymentMethodId = AlwaysConvert.ToInt(PaymentMethodList.DataKeys[index]);
             PaymentMethod method          = GetPaymentMethod(paymentMethodId);
             if (method != null)
             {
                 CheckBox cbMethod = (CheckBox)AbleCommerce.Code.PageHelper.RecursiveFindControl(item, "Method");
                 if (cbMethod.Checked)
                 {
                     method.PaymentGateway = PaymentGatewayDataSource.Load(_PaymentGatewayId);
                 }
                 else if (method.PaymentGateway != null && method.PaymentGateway.Id == _PaymentGatewayId)
                 {
                     method.PaymentGateway = null;
                 }
                 method.Save();
             }
             index++;
         }
     }
 }
Exemple #5
0
 protected void SaveButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         PaymentMethod _PaymentMethod = PaymentMethodDataSource.Load(PaymentMethodId);
         _PaymentMethod.Name = Name.Text;
         _PaymentMethod.PaymentInstrumentType = (PaymentInstrumentType)AlwaysConvert.ToInt16(PaymentInstrumentList.SelectedValue);
         _PaymentMethod.PaymentGateway        = PaymentGatewayDataSource.Load(AlwaysConvert.ToInt(GatewayList.SelectedValue));
         _PaymentMethod.AllowSubscriptions    = AllowSubscriptionPayments.Checked;
         //GROUP RESTRICTION
         _PaymentMethod.Groups.Clear();
         _PaymentMethod.Save();
         if (UseGroupRestriction.SelectedIndex > 0)
         {
             foreach (ListItem item in GroupList.Items)
             {
                 Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                 if (item.Selected)
                 {
                     _PaymentMethod.Groups.Add(group);
                 }
             }
         }
         _PaymentMethod.Save();
         //TRIGER ANY EVENT ATTACHED TO THE UPDATE
         if (ItemUpdated != null)
         {
             ItemUpdated(this, new PersistentItemEventArgs(PaymentMethodId, _PaymentMethod.Name));
         }
     }
 }
Exemple #6
0
        public static PayPalProvider GetPayPalProvider()
        {
            int gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(Misc.GetClassId(typeof(PayPalProvider)));

            if (gatewayId != 0)
            {
                PaymentGateway gateway = PaymentGatewayDataSource.Load(gatewayId);
                return((PayPalProvider)gateway.GetInstance());
            }
            return(null);
        }
        private bool PayOrder(Payment payment)
        {
            bool hasGateway = false;

            if (payment.PaymentMethod != null)
            {
                hasGateway = (payment.PaymentMethod.PaymentGateway != null);
            }
            else if (payment.PaymentProfile != null)
            {
                int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(payment.PaymentProfile.GatewayIdentifier);
                PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
                hasGateway = (gateway != null);
            }

            if (hasGateway)
            {
                // PRESERVE ACCOUNT DATA FOR PROCESSING
                string accountData = payment.AccountData;
                payment.AccountData = string.Empty;

                // SAVE PAYMENT
                this.Order.Payments.Add(payment);
                this.Order.Save(true, true);

                // PROCESS PAYMENT WITH SAVED ACCOUNT DATA
                payment.AccountData = accountData;
                payment.Authorize(false);
                if (payment.PaymentStatus == PaymentStatus.AuthorizationFailed)
                {
                    // VOID PAYMENT AND SHOW ERRORS TO CUSTOMER
                    payment.Void();
                    List <string> errorList = new List <string>();
                    errorList.Add(payment.Transactions[0].ResponseMessage);
                    WarningMessageList.DataSource = errorList;
                    WarningMessageList.DataBind();
                    return(false);
                }
                else
                {
                    return(true);
                }
            }
            else
            {
                //SAVE PAYMENT
                this.Order.Payments.Add(payment);
                this.Order.Save(true, true);
                return(true);
            }
        }
Exemple #8
0
        public static GoogleCheckout GetInstance()
        {
            int gwID = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(Utility.Misc.GetClassId(typeof(GoogleCheckout)));

            if (gwID == 0)
            {
                return(null);
            }
            else
            {
                PaymentGateway gateway          = PaymentGatewayDataSource.Load(gwID);
                GoogleCheckout _GatewayInstance = (GoogleCheckout)gateway.GetInstance();
                return(_GatewayInstance);
            }
        }
Exemple #9
0
        protected void CardsList_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            if (e.CommandName == "DELETE_PROFILE")
            {
                int profileId = AlwaysConvert.ToInt(e.CommandArgument);
                if (profileId > 0 && CanBeDeleted(profileId))
                {
                    var profile = GatewayPaymentProfileDataSource.Load(profileId);
                    if (profile.Subscriptions.Count == 0)
                    {
                        int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                        PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
                        if (gateway != null)
                        {
                            var provider = gateway.GetInstance();
                            try
                            {
                                var rsp = provider.DoDeletePaymentProfile(new CommerceBuilder.Payments.Providers.DeletePaymentProfileRequest(AbleContext.Current.User, profile.CustomerProfileId, profile.PaymentProfileId));
                                if (rsp.Successful || rsp.ResponseCode == "E00040")
                                {
                                    int id = profile.Id;
                                    profile.Delete();
                                    BindCards();
                                }
                                else
                                {
                                    DeleteMessage.Text = string.Format("Somthing went wrong! Unable to remove profile '{0} ending in {1}'", profile.InstrumentType, profile.ReferenceNumber);
                                    Logger.Error(rsp.ResponseMessage);
                                }
                            }
                            catch (Exception exp)
                            {
                                Logger.Error(exp.Message);
                            }
                        }
                    }
                }
            }

            if (e.CommandName == "EDIT_PROFILE")
            {
                Response.Redirect(string.Format("~/Members/EditPaymentType.aspx?ProfileId={0}", e.CommandArgument));
            }
        }
 protected void UpdateButton_Click(object sender, EventArgs e)
 {
     if (Page.IsValid)
     {
         int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(_profile.GatewayIdentifier);
         PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
         if (gateway != null)
         {
             var provider = gateway.GetInstance();
             try
             {
                 AccountDataDictionary cardDetails = new AccountDataDictionary();
                 cardDetails["AccountNumber"]   = _profile.ReferenceNumber.PadLeft(8, 'x').ToUpper();
                 cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedValue;
                 cardDetails["ExpirationYear"]  = ExpirationYear.SelectedValue;
                 cardDetails["SecurityCode"]    = SecurityCode.Text;
                 PaymentInstrumentData instr = PaymentInstrumentData.CreateInstance(cardDetails, _profile.InstrumentType, null);
                 var rsp = provider.DoUpdatePaymentProfile(new CommerceBuilder.Payments.Providers.UpdatePaymentProfileRequest(AbleContext.Current.User, instr, _profile.CustomerProfileId, _profile.PaymentProfileId));
                 if (rsp.Successful || rsp.ResponseCode == "E00040")
                 {
                     _profile.Expiry = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedValue), AlwaysConvert.ToInt(ExpirationMonth.SelectedValue), 1));
                     _profile.Save();
                     SuccessMessage.Text    = string.Format(SuccessMessage.Text, LocaleHelper.LocalNow);
                     SuccessMessage.Visible = true;
                 }
                 else
                 {
                     ErrorMessage.Visible = true;
                     Logger.Error(rsp.ResponseMessage);
                 }
             }
             catch (Exception exp)
             {
                 Logger.Error(exp.Message);
             }
         }
     }
 }
        protected void AddButton_Click(object sender, System.EventArgs e)
        {
            PaymentMethod method = new PaymentMethod();

            method.Name = Name.Text;
            method.PaymentInstrumentType = (PaymentInstrumentType)AlwaysConvert.ToInt16(PaymentInstrumentList.SelectedValue);
            method.PaymentGateway        = PaymentGatewayDataSource.Load(AlwaysConvert.ToInt(GatewayList.SelectedValue));
            method.AllowSubscriptions    = AllowSubscriptionPayments.Checked;
            //GROUP RESTRICTION
            if (UseGroupRestriction.SelectedIndex > 0)
            {
                foreach (ListItem item in GroupList.Items)
                {
                    Group group = GroupDataSource.Load(AlwaysConvert.ToInt(item.Value));
                    if (item.Selected)
                    {
                        method.Groups.Add(group);
                    }
                }
            }
            method.OrderBy = (short)PaymentMethodDataSource.GetNextOrderBy();
            method.Save();
            //UPDATE THE ADD MESSAGE
            AddedMessage.Text    = string.Format(AddedMessage.Text, method.Name);
            AddedMessage.Visible = true;
            //RESET THE ADD FORM
            PaymentInstrumentList.SelectedIndex = -1;
            Name.Text = string.Empty;
            GatewayList.SelectedIndex         = -1;
            AllowSubscriptionPayments.Checked = false;
            UseGroupRestriction.SelectedIndex = 0;
            BindGroups();
            //TRIGER ANY EVENT ATTACHED TO THE UPDATE
            if (ItemAdded != null)
            {
                ItemAdded(this, new PersistentItemEventArgs(method.Id, method.Name));
            }
        }
        protected void SaveCardButton_Click(Object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                GatewayPaymentProfile profile = _Subscription.PaymentProfile;
                if (profile != null)
                {
                    AccountDataDictionary cardDetails = new AccountDataDictionary();
                    cardDetails["AccountName"]     = CardName.Text.Trim();
                    cardDetails["AccountNumber"]   = CardNumber.Text.Trim();
                    cardDetails["ExpirationMonth"] = ExpirationMonth.SelectedItem.Value;
                    cardDetails["ExpirationYear"]  = ExpirationYear.SelectedItem.Value;
                    cardDetails["SecurityCode"]    = SecurityCode.Text.Trim();
                    PaymentMethod         method = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
                    PaymentInstrumentData instr  = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                    int            gatewayId     = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(_Subscription.PaymentProfile.GatewayIdentifier);
                    PaymentGateway gateway       = PaymentGatewayDataSource.Load(gatewayId);
                    if (gateway != null)
                    {
                        var provider = gateway.GetInstance();
                        try
                        {
                            var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_Subscription.User, instr, profile.CustomerProfileId)
                            {
                                ValidateProfile = true
                            });
                            if (rsp.Successful)
                            {
                                GatewayPaymentProfile gwprofile = new GatewayPaymentProfile();
                                gwprofile.NameOnCard        = CardName.Text.Trim();;
                                gwprofile.Expiry            = Misc.GetStartOfDate(new DateTime(AlwaysConvert.ToInt(ExpirationYear.SelectedItem.Value), AlwaysConvert.ToInt(ExpirationMonth.SelectedItem.Value), 1));
                                gwprofile.CustomerProfileId = profile.CustomerProfileId;
                                gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                                gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                                gwprofile.User              = _Subscription.User;
                                gwprofile.InstrumentType    = instr.InstrumentType;
                                gwprofile.GatewayIdentifier = profile.GatewayIdentifier;
                                gwprofile.Save();
                                BindPayments(gwprofile.Id);
                                CardName.Text   = string.Empty;
                                CardNumber.Text = string.Empty;
                                ExpirationMonth.SelectedIndex = 0;
                                ExpirationYear.SelectedIndex  = 0;
                                AddCardPopup.Hide();
                            }
                            else
                            {
                                ErrorMessage.Text = rsp.ResponseMessage;
                                AddCardPopup.Show();
                            }
                        }
                        catch (Exception exp)
                        {
                            Logger.Error(exp.Message);
                            ErrorMessage.Text = exp.Message;
                            AddCardPopup.Show();
                        }
                    }

                    BindPayments(profile.Id);
                }
            }
            else
            {
                AddCardPopup.Show();
            }
        }
Exemple #13
0
        /// <summary>
        /// Binds the order details in the payment column
        /// </summary>
        protected void BindPaymentColumn()
        {
            // bind status
            OrderTotal.Text           = _order.TotalCharges.LSCurrencyFormat("lc");
            OrderBalance.Text         = _order.GetBalance(false).LSCurrencyFormat("lc");
            CurrentPaymentStatus.Text = _order.PaymentStatus.ToString();
            if (_order.PaymentStatus == OrderPaymentStatus.Paid)
            {
                CurrentPaymentStatus.CssClass = "goodCondition";
            }
            else
            {
                CurrentPaymentStatus.CssClass = "errorCondition";
            }


            // check for the last payment record
            Payment payment = GetLastPayment();

            if (payment != null)
            {
                // bind static payment info
                LastPaymentAmount.Text    = payment.Amount.LSCurrencyFormat("lc");
                LastPaymentStatus.Text    = StringHelper.SpaceName(payment.PaymentStatus.ToString());
                LastPaymentReference.Text = payment.PaymentMethodName;
                if (!string.IsNullOrEmpty(payment.ReferenceNumber))
                {
                    LastPaymentReference.Text += " " + payment.ReferenceNumber;
                }

                // bind transaction details
                Transaction lastAuthorization = payment.Transactions.GetLastAuthorization();
                if (lastAuthorization == null)
                {
                    lastAuthorization = payment.Transactions.GetLastRecurringAuthorization();
                }
                if (lastAuthorization != null)
                {
                    string friendlyCVV = AbleCommerce.Code.StoreDataHelper.TranslateCVVCode(lastAuthorization.CVVResultCode);
                    if (!string.IsNullOrEmpty(lastAuthorization.CVVResultCode))
                    {
                        friendlyCVV += " (" + lastAuthorization.CVVResultCode + ")";
                    }
                    LastPaymentCVV.Text = friendlyCVV;
                    string friendlyAVS = AbleCommerce.Code.StoreDataHelper.TranslateAVSCode(lastAuthorization.AVSResultCode);
                    if (!string.IsNullOrEmpty(lastAuthorization.AVSResultCode))
                    {
                        friendlyAVS += " (" + lastAuthorization.AVSResultCode + ")";
                    }
                    LastPaymentAVS.Text = friendlyAVS;
                }
                else
                {
                    TransactionPanel.Visible = false;
                }

                PaymentGateway gateway = null;
                if (payment.PaymentMethod != null)
                {
                    gateway = payment.PaymentMethod.PaymentGateway;
                }

                if (gateway == null && payment.PaymentProfile != null)
                {
                    int gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(payment.PaymentProfile.GatewayIdentifier);
                    gateway = PaymentGatewayDataSource.Load(gatewayId);
                }

                IPaymentProvider      provider = (gateway != null ? gateway.GetInstance() : null);
                SupportedTransactions supportedTransactions = SupportedTransactions.None;
                if (provider != null)
                {
                    supportedTransactions = provider.SupportedTransactions;
                }

                // bind payment buttons
                ReceivedButton.Visible = (payment.PaymentStatus == PaymentStatus.Unprocessed);
                if ((supportedTransactions & SupportedTransactions.Void) == SupportedTransactions.Void)
                {
                    VoidLink.Visible     = ((payment.PaymentStatus == PaymentStatus.Unprocessed) || (payment.PaymentStatus == PaymentStatus.Authorized) || (payment.PaymentStatus == PaymentStatus.AuthorizationFailed) || (payment.PaymentStatus == PaymentStatus.CaptureFailed));
                    VoidLink.NavigateUrl = "Payments/VoidPayment.aspx?PaymentId=" + payment.Id.ToString();
                }
                else
                {
                    VoidLink.Visible = false;
                }

                if ((((supportedTransactions & SupportedTransactions.Capture) == SupportedTransactions.Capture) || ((supportedTransactions & SupportedTransactions.AuthorizeCapture) == SupportedTransactions.AuthorizeCapture)))
                {
                    CaptureLink.Visible     = (payment.PaymentStatus == PaymentStatus.Authorized);
                    CaptureLink.NavigateUrl = "Payments/CapturePayment.aspx?PaymentId=" + payment.Id.ToString();
                }
                else
                {
                    VoidLink.Visible = false;
                }

                ButtonPanel.Visible = ReceivedButton.Visible || VoidLink.Visible || CaptureLink.Visible;
            }
            else
            {
                LastPaymentPanel.Visible = false;
            }

            // IP details
            if (!string.IsNullOrEmpty(_order.RemoteIP))
            {
                CustomerIP.Text               = _order.RemoteIP;
                CustomerIPBlocked.Visible     = BannedIPDataSource.IsBanned(CustomerIP.Text);
                BlockCustomerIP.Visible       = (!CustomerIPBlocked.Visible && (_order.RemoteIP != Request.UserHostAddress));
                BlockCustomerIP.OnClientClick = string.Format(BlockCustomerIP.OnClientClick, _order.RemoteIP);
            }
            else
            {
                CustomerIPPanel.Visible = false;
            }

            //Refferrer url
            if (!string.IsNullOrEmpty(_order.Referrer))
            {
                if (_order.Referrer.Length > UrlMaxLenght)
                {
                    OrderReferrer.NavigateUrl = _order.Referrer;
                    OrderReferrer.Text        = _order.Referrer.Substring(0, UrlMaxLenght) + "...";
                }
                else
                {
                    OrderReferrer.NavigateUrl = _order.Referrer;
                    OrderReferrer.Text        = _order.Referrer.Replace("/", "/<wbr />").Replace("_", "_<wbr />");
                }
            }

            // affiliate details
            if (_order.AffiliateId != 0)
            {
                Affiliate.Text = _order.Affiliate.Name;
            }
            else
            {
                AffiliatePanel.Visible = false;
            }
            TaxExemptionMessagePanel.Visible = this._order.Items.TotalPrice(OrderItemType.Tax) == 0 && !string.IsNullOrEmpty(this._order.TaxExemptionReference);
        }
Exemple #14
0
        protected void FixProfiles()
        {
            IList <GatewayPaymentProfile> profiles = NHibernateHelper.CreateCriteria <GatewayPaymentProfile>()
                                                     .Add(new Disjunction().Add(Restrictions.IsNull("PaymentProfileId")).Add(Restrictions.Eq("PaymentProfileId", "")))
                                                     .List <GatewayPaymentProfile>();
            WebClient     client = new WebClient();
            StringBuilder log    = new StringBuilder();

            log.Append("Total Profiles To Fix: " + profiles.Count + Environment.NewLine);

            foreach (var profile in profiles)
            {
                int            gatewayId = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(profile.GatewayIdentifier);
                PaymentGateway gateway   = PaymentGatewayDataSource.Load(gatewayId);
                if (gateway != null)
                {
                    var           configData = gateway.ParseConfigData();
                    StringBuilder sb         = new StringBuilder();
                    sb.Append("<?xml version='1.0' encoding='utf-8'?>");
                    sb.Append("<getCustomerProfileRequest xmlns='AnetApi/xml/v1/schema/AnetApiSchema.xsd'>");
                    sb.Append("  <merchantAuthentication>");
                    sb.Append(string.Format("    <name>{0}</name>", configData["MerchantLogin"]));
                    sb.Append(string.Format("    <transactionKey>{0}</transactionKey>", configData["TransactionKey"]));
                    sb.Append("  </merchantAuthentication>");
                    sb.Append(string.Format("  <customerProfileId>{0}</customerProfileId>", profile.CustomerProfileId));
                    sb.Append("</getCustomerProfileRequest>");

                    string url                = UseSandBox.Checked ? "https://apitest.authorize.net/xml/v1/request.api" : "https://api.authorize.net/xml/v1/request.api";
                    byte[] data               = client.UploadData(url, Encoding.UTF8.GetBytes(sb.ToString()));
                    string response           = Encoding.UTF8.GetString(data);
                    string _byteOrderMarkUtf8 = Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble());
                    if (response.StartsWith(_byteOrderMarkUtf8))
                    {
                        response = response.Remove(0, _byteOrderMarkUtf8.Length);
                    }

                    response = response.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", string.Empty);
                    response = response.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", string.Empty);
                    response = response.Replace("xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"", string.Empty);


                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(response);
                    XmlNodeList xmlProfiles = doc.DocumentElement.SelectNodes("profile/paymentProfiles");
                    if (xmlProfiles != null && xmlProfiles.Count > 0)
                    {
                        foreach (XmlNode xmlProfile in xmlProfiles)
                        {
                            XmlNode firstNameNode      = xmlProfile.SelectSingleNode("billTo/firstName");
                            XmlNode lastNameNode       = xmlProfile.SelectSingleNode("billTo/lastName");
                            XmlNode paymentProfileNode = xmlProfile.SelectSingleNode("customerPaymentProfileId");
                            XmlNode cardNumberNode     = xmlProfile.SelectSingleNode("payment/creditCard/cardNumber");

                            string firstName = firstNameNode != null?firstNameNode.InnerText.Trim() : string.Empty;

                            string lastName = lastNameNode != null?lastNameNode.InnerText.Trim() : string.Empty;

                            string cardNumber = cardNumberNode != null?cardNumberNode.InnerText.Trim() : string.Empty;

                            string paymentProfileId = paymentProfileNode != null?paymentProfileNode.InnerText.Trim() : string.Empty;

                            if (cardNumber.EndsWith(profile.ReferenceNumber, StringComparison.InvariantCultureIgnoreCase) &&
                                profile.NameOnCard.Equals(string.Format("{0} {1}", firstName, lastName), StringComparison.InvariantCultureIgnoreCase))
                            {
                                if (string.IsNullOrEmpty(profile.PaymentProfileId) && !string.IsNullOrEmpty(paymentProfileId))
                                {
                                    profile.PaymentProfileId = paymentProfileId;
                                    profile.Save();

                                    log.Append(string.Format("{0} - {1} - {2} => [{3}]", profile.CustomerProfileId, profile.NameOnCard, profile.ReferenceNumber, profile.PaymentProfileId));
                                    log.Append(Environment.NewLine);
                                }
                            }
                        }
                    }
                }

                FixLog.Text = log.ToString();
            }
        }