public static IGatewayPaymentProfile MapCustomerPaymentProfileMaskTypeToGatewayPaymentProfile(this AuthorizeNet.APICore.customerPaymentProfileMaskedType response)
        {
            var result = new GatewayPaymentProfile();
            result.PaymentCardData = new PaymentCardData();
            result.Id = response.customerPaymentProfileId;
            if (response.billTo != null)
            {
                
                result.PaymentCardData.BillingAddress = response.billTo.MapCustomerAddressTypeToAddressType();
                result.PaymentCardData.CardHolderFirstName = response.billTo.firstName;
                result.PaymentCardData.CardHolderLastName = response.billTo.lastName;
            }
            var creditCard = response.payment.Item as AuthorizeNet.APICore.creditCardMaskedType;
            if (creditCard != null)
            {
                result.PaymentCardData.MaskedCardNumber = creditCard.cardNumber;
                PaymentCardType cardType = PaymentCardType.Unknown;
                Enum.TryParse<PaymentCardType>(creditCard.cardType, out cardType);
                //result.PaymentCardData.ExpirationMonth = int.Parse(creditCard.expirationDate.Substring(2, 2));
                //result.PaymentCardData.ExpirationYear = int.Parse(creditCard.expirationDate.Substring(0, 4));
               
            }

            return result;
            
            
        }
        protected string GetExpirationDate(object o)
        {
            GatewayPaymentProfile profile = o as GatewayPaymentProfile;

            if (profile.Expiry.HasValue && profile.Expiry.Value > DateTime.MinValue && profile.Expiry.Value.Year != DateTime.MaxValue.Year)
            {
                return(string.Format("{0:y}", profile.Expiry));
            }
            else
            {
                return("N/A");
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            _profileId = AlwaysConvert.ToInt(Request.QueryString["ProfileId"]);
            _profile   = GatewayPaymentProfileDataSource.Load(_profileId);

            if (_profile == null || _profile.User != AbleContext.Current.User)
            {
                Response.Redirect("PaymentTypes.aspx");
            }

            if (!Page.IsPostBack)
            {
                CardType.Text   = _profile.InstrumentType.ToString();
                CardName.Text   = _profile.NameOnCard;
                CardNumber.Text = _profile.ReferenceNumber.PadLeft(8, 'x').ToUpper();

                // POPULATE EXPIRATON DATE DROPDOWN
                int thisYear = LocaleHelper.LocalNow.Year;
                for (int i = 0; (i <= 10); i++)
                {
                    ExpirationYear.Items.Add(new ListItem((thisYear + i).ToString()));
                }

                DateTime expirationDate = _profile.Expiry ?? DateTime.MinValue;
                if (expirationDate != DateTime.MinValue)
                {
                    string   eMonth = expirationDate.Month.ToString().PadLeft(2, '0');
                    string   eYear  = expirationDate.Year.ToString();
                    ListItem item   = ExpirationYear.Items.FindByValue(eYear);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                    item = ExpirationMonth.Items.FindByValue(eMonth);
                    if (item != null)
                    {
                        item.Selected = true;
                    }
                }
            }
        }
        void control_OnEditCardInfo(object sender, CardInfoDetailEventArgs e)
        {
            GatewayPaymentProfile profile = GatewayPaymentProfileDataSource.Load(e.ProfileId);

            if (profile != null)
            {
                HiddenProfileId.Value = profile.Id.ToString();
                NameOnCardLabel.Text  = string.Format("{0}", profile.NameOnCard);
                ReferenceLabel.Text   = string.Format("Profile {0} ending in {1}", profile.InstrumentType, profile.ReferenceNumber);

                string   profileExpiry = profile.Expiry.ToString();
                string[] dateParts     = profileExpiry.Split('/');
                string   expiryMonth   = (dateParts[0].Length == 1) ? "0" + dateParts[0] : dateParts[0];
                string   expiryDay     = dateParts[1];
                string   expiryYear    = dateParts[2].Substring(0, 4);

                ListItem selectedYear = ExpirationYear.Items.FindByValue(expiryYear);
                if (selectedYear != null)
                {
                    ExpirationYear.ClearSelection();
                    selectedYear.Selected = true;
                }

                ListItem selectedMonth = ExpirationMonth.Items.FindByValue(expiryMonth);
                if (selectedMonth != null)
                {
                    ExpirationMonth.ClearSelection();
                    selectedMonth.Selected = true;
                }

                EditCardInfoPopUp.Show();
            }
            else
            {
                HiddenProfileId.Value = string.Empty;
            }
        }
 protected string GetExpiration(object o)
 {
     GatewayPaymentProfile payment = o as GatewayPaymentProfile;
     return string.Format("{0:d}", payment.LastDayOfExpiry.HasValue ? payment.LastDayOfExpiry : payment.Expiry);
 }
        protected void SaveCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                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);
                PaymentGateway gateway = method.PaymentGateway;
                if (gateway != null)
                {
                    var provider = gateway.GetInstance();
                    string customerProfileId = string.Empty;
                    var profileResult = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                        .GroupBy(p => p.CustomerProfileId)
                        .Take(1)
                        .Select(g => new { CustomerProfileId = g.Key })
                        .SingleOrDefault();

                    if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                        customerProfileId = profileResult.CustomerProfileId;

                    if (string.IsNullOrEmpty(customerProfileId))
                    {
                        try 
                        {
                            var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                            if (rsp.Successful)
                                customerProfileId = rsp.CustomerProfileId;
                            else if (rsp.ResponseCode == "E00039")
                            {
                                var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.IgnoreCase);
                                if(match.Success)
                                    customerProfileId = match.Value;
                                else
                                    ErrorMessage.Text = rsp.ResponseMessage;
                            }
                            else
                                ErrorMessage.Text = rsp.ResponseMessage;
                        }
                        catch(Exception exp)
                        {
                            ErrorMessage.Text = exp.Message;
                        }

                        if (string.IsNullOrEmpty(customerProfileId)) return;
                    }

                    try
                    {
                        var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, 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 = customerProfileId;
                            gwprofile.PaymentProfileId = rsp.PaymentProfileId;
                            gwprofile.ReferenceNumber = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                            gwprofile.User = _user;
                            gwprofile.InstrumentType = instr.InstrumentType;
                            gwprofile.PaymentMethodName = method.Name;
                            gwprofile.GatewayIdentifier = gateway.ClassId;
                            gwprofile.Save();
                            if (_user.PaymentProfiles.Count == 0)
                            {
                                _user.Settings.DefaultPaymentProfileId = gwprofile.Id;
                                _user.Settings.Save();
                            }
                            CardName.Text = string.Empty;
                            CardNumber.Text = string.Empty;
                            ExpirationMonth.SelectedIndex = 0;
                            ExpirationYear.SelectedIndex = 0;
                            BindCards();
                        }
                        else
                        {
                            ErrorMessage.Text = rsp.ResponseMessage;
                            Logger.Error(rsp.ResponseMessage);
                        }
                    }
                    catch (Exception exp)
                    {
                        ErrorMessage.Text = exp.Message;
                    }
                }
            }
        }
        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();
            }
        }
        protected GatewayPaymentProfile CreateProfile(AccountDataDictionary cardDetails)
        {
            PaymentMethod         method  = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue));
            PaymentGateway        gateway = method.PaymentGateway;
            PaymentInstrumentData instr   = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
            GatewayPaymentProfile profile = null;

            if (gateway != null)
            {
                var    provider          = gateway.GetInstance();
                string customerProfileId = string.Empty;
                var    profileResult     = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                                           .GroupBy(p => p.CustomerProfileId)
                                           .Take(1)
                                           .Select(g => new { CustomerProfileId = g.Key })
                                           .SingleOrDefault();

                if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                {
                    customerProfileId = profileResult.CustomerProfileId;
                }

                if (string.IsNullOrEmpty(customerProfileId))
                {
                    try
                    {
                        var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                        if (rsp.Successful)
                        {
                            customerProfileId = rsp.CustomerProfileId;
                        }
                        else if (rsp.ResponseCode == "E00039")
                        {
                            var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.CultureInvariant);
                            if (match.Success)
                            {
                                customerProfileId = match.Value;
                            }
                            else
                            {
                                Logger.Error(rsp.ResponseMessage);
                            }
                        }
                        else
                        {
                            Logger.Error(rsp.ResponseMessage);
                        }
                    }
                    catch (Exception exp)
                    {
                        Logger.Error(exp.Message);
                    }
                }

                try
                {
                    var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, 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 = customerProfileId;
                        gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                        gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                        gwprofile.User              = _user;
                        gwprofile.InstrumentType    = instr.InstrumentType;
                        gwprofile.PaymentMethodName = method.Name;
                        gwprofile.GatewayIdentifier = gateway.ClassId;
                        gwprofile.Save();
                        CardName.Text   = string.Empty;
                        CardNumber.Text = string.Empty;
                        ExpirationMonth.SelectedIndex = 0;
                        ExpirationYear.SelectedIndex  = 0;
                        profile = gwprofile;
                    }
                }
                catch (Exception exp)
                {
                    Logger.Error(exp.Message);
                }
            }

            return(profile);
        }
        protected void CompleteButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                bool checkOut = true;
                if (CheckingOut != null)
                {
                    CheckingOutEventArgs c = new CheckingOutEventArgs();
                    CheckingOut(this, c);
                    checkOut = !c.Cancel;
                }
                if (checkOut)
                {
                    Basket basket = AbleContext.Current.User.Basket;
                    //PROCESS THE CHECKOUT
                    ICheckoutService checkoutService  = AbleContext.Resolve <ICheckoutService>();
                    CheckoutRequest  checkoutRequest  = new CheckoutRequest(basket);
                    CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest);
                    if (checkoutResponse.Success)
                    {
                        GatewayPaymentProfile profile = null;
                        this.Visible = true;

                        if (ProfilesPH.Visible)
                        {
                            profile = GatewayPaymentProfileDataSource.Load(AlwaysConvert.ToInt(ProfilesList.SelectedValue));
                        }

                        if (CardPH.Visible)
                        {
                            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();
                            profile = CreateProfile(cardDetails);
                        }

                        if (profile != null)
                        {
                            IList <Subscription> subscriptions = SubscriptionDataSource.LoadForOrder(checkoutResponse.Order.Id);
                            foreach (Subscription subscription in subscriptions)
                            {
                                if (subscription.PaymentFrequency.HasValue && subscription.PaymentFrequencyUnit.HasValue)
                                {
                                    subscription.PaymentProfile        = profile;
                                    subscription.PaymentProcessingType = PaymentProcessingType.ArbProfileManaged;
                                    subscription.Save();
                                }
                            }
                        }

                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                        Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber));
                    }
                    else
                    {
                        IList <string> warningMessages = checkoutResponse.WarningMessages;
                        if (warningMessages.Count == 0)
                        {
                            warningMessages.Add("The order could not be submitted at this time.  Please try again later or contact us for assistance.");
                        }
                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                    }
                }
            }
        }
        protected void CreditCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                // CREATE THE PAYMENT OBJECT
                Payment payment = GetPayment();

                // PROCESS CHECKING OUT EVENT
                bool checkOut = true;
                if (CheckingOut != null)
                {
                    CheckingOutEventArgs c = new CheckingOutEventArgs(payment);
                    CheckingOut(this, c);
                    checkOut = !c.Cancel;
                }

                if (checkOut)
                {
                    // CONTINUE TO PROCESS THE CHECKOUT
                    Basket           basket           = AbleContext.Current.User.Basket;
                    ICheckoutService checkoutService  = AbleContext.Resolve <ICheckoutService>();
                    CheckoutRequest  checkoutRequest  = new CheckoutRequest(basket, payment);
                    CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest);
                    if (checkoutResponse.Success)
                    {
                        GatewayPaymentProfile profile = null;
                        if (trSaveCard.Visible && SaveCard.Checked)
                        {
                            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();
                            profile = CreateProfile(cardDetails);
                        }

                        if (AbleContext.Current.Store.Settings.ROCreateNewOrdersEnabled && OrderHelper.HasRecurringSubscriptions(checkoutResponse.Order))
                        {
                            IList <Subscription> subscriptions = SubscriptionDataSource.LoadForOrder(checkoutResponse.Order.Id);
                            foreach (Subscription subscription in subscriptions)
                            {
                                OrderItem oi = subscription.OrderItem;
                                if (oi != null && oi.Price == 0 && OrderHelper.HasRecurringSubscriptions(oi) && subscription.PaymentProfile == null)
                                {
                                    if (profile == null)
                                    {
                                        if (ProfilesPH.Visible)
                                        {
                                            profile = GatewayPaymentProfileDataSource.Load(AlwaysConvert.ToInt(ProfilesList.SelectedValue));
                                        }

                                        if (CardPH.Visible)
                                        {
                                            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();
                                            profile = CreateProfile(cardDetails);
                                        }
                                    }

                                    subscription.PaymentProfile        = profile;
                                    subscription.PaymentProcessingType = PaymentProcessingType.ArbProfileManaged;
                                    subscription.Save();
                                }
                            }
                        }

                        if (profile != null && payment.PaymentProfile == null)
                        {
                            payment.PaymentProfile = profile;
                            payment.Save();
                        }

                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                        Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber));
                    }
                    else
                    {
                        IList <string> warningMessages = checkoutResponse.WarningMessages;
                        if (warningMessages.Count == 0)
                        {
                            warningMessages.Add("The order could not be submitted at this time.  Please try again later or contact us for assistance.");
                        }
                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                    }
                }
            }
        }
Beispiel #11
0
        protected void CreditCardButton_Click(object sender, EventArgs e)
        {
            if (Page.IsValid && CustomValidation())
            {
                // CREATE THE PAYMENT OBJECT
                Payment payment = GetPayment();

                // PROCESS CHECKING OUT EVENT
                bool checkOut = true;
                if (CheckingOut != null)
                {
                    CheckingOutEventArgs c = new CheckingOutEventArgs(payment);
                    CheckingOut(this, c);
                    checkOut = !c.Cancel;
                }

                if (checkOut)
                {
                    // CONTINUE TO PROCESS THE CHECKOUT
                    Basket           basket           = AbleContext.Current.User.Basket;
                    ICheckoutService checkoutService  = AbleContext.Resolve <ICheckoutService>();
                    CheckoutRequest  checkoutRequest  = new CheckoutRequest(basket, payment);
                    CheckoutResponse checkoutResponse = checkoutService.ExecuteCheckout(checkoutRequest);
                    if (checkoutResponse.Success)
                    {
                        if (trSaveCard.Visible && SaveCard.Checked)
                        {
                            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));
                            PaymentGateway        gateway = method.PaymentGateway;
                            PaymentInstrumentData instr   = PaymentInstrumentData.CreateInstance(cardDetails, method.PaymentInstrumentType, null);
                            if (gateway != null)
                            {
                                var    provider          = gateway.GetInstance();
                                string customerProfileId = string.Empty;
                                var    profileResult     = _user.PaymentProfiles.Where(p => p.GatewayIdentifier == gateway.ClassId)
                                                           .GroupBy(p => p.CustomerProfileId)
                                                           .Take(1)
                                                           .Select(g => new { CustomerProfileId = g.Key })
                                                           .SingleOrDefault();

                                if (profileResult != null && !string.IsNullOrEmpty(profileResult.CustomerProfileId))
                                {
                                    customerProfileId = profileResult.CustomerProfileId;
                                }

                                if (string.IsNullOrEmpty(customerProfileId))
                                {
                                    try
                                    {
                                        var rsp = provider.DoCreateCustomerProfile(new CommerceBuilder.Payments.Providers.CreateCustomerProfileRequest(_user));
                                        if (rsp.Successful)
                                        {
                                            customerProfileId = rsp.CustomerProfileId;
                                        }
                                        else if (rsp.ResponseCode == "E00039")
                                        {
                                            var match = Regex.Match(rsp.ResponseMessage, @"\d+", RegexOptions.CultureInvariant);
                                            if (match.Success)
                                            {
                                                customerProfileId = match.Value;
                                            }
                                            else
                                            {
                                                Logger.Error(rsp.ResponseMessage);
                                            }
                                        }
                                        else
                                        {
                                            Logger.Error(rsp.ResponseMessage);
                                        }
                                    }
                                    catch (Exception exp)
                                    {
                                        Logger.Error(exp.Message);
                                    }
                                }

                                try
                                {
                                    var rsp = provider.DoCreatePaymentProfile(new CommerceBuilder.Payments.Providers.CreatePaymentProfileRequest(_user, instr, 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 = customerProfileId;
                                        gwprofile.PaymentProfileId  = rsp.PaymentProfileId;
                                        gwprofile.ReferenceNumber   = StringHelper.MakeReferenceNumber(cardDetails["AccountNumber"]);
                                        gwprofile.User              = _user;
                                        gwprofile.InstrumentType    = instr.InstrumentType;
                                        gwprofile.PaymentMethodName = method.Name;
                                        gwprofile.GatewayIdentifier = gateway.ClassId;
                                        gwprofile.Save();
                                        CardName.Text   = string.Empty;
                                        CardNumber.Text = string.Empty;
                                        ExpirationMonth.SelectedIndex = 0;
                                        ExpirationYear.SelectedIndex  = 0;
                                    }
                                }
                                catch (Exception exp)
                                {
                                    Logger.Error(exp.Message);
                                }
                            }
                        }

                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                        Response.Redirect(AbleCommerce.Code.NavigationHelper.GetReceiptUrl(checkoutResponse.Order.OrderNumber));
                    }
                    else
                    {
                        IList <string> warningMessages = checkoutResponse.WarningMessages;
                        if (warningMessages.Count == 0)
                        {
                            warningMessages.Add("The order could not be submitted at this time.  Please try again later or contact us for assistance.");
                        }
                        if (CheckedOut != null)
                        {
                            CheckedOut(this, new CheckedOutEventArgs(checkoutResponse));
                        }
                    }
                }
            }
        }