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)); } } }
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; } }
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); } } } } }
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++; } } }
protected IList <PaymentGateway> LoadGateways() { string classId = GetGiftCertPayGatewayId(); ICriteria criteria = NHibernateHelper.CreateCriteria <PaymentGateway>(); criteria.Add(Restrictions.Not(Restrictions.Eq("Name", "Gift Certificate Payment Provider"))); criteria.Add(Restrictions.Not(Restrictions.Eq("ClassId", StringHelper.SafeSqlString((classId))))); List <PaymentGateway> filteredGateways = new List <PaymentGateway>(); IList <PaymentGateway> gateways = PaymentGatewayDataSource.LoadAll(); for (int i = gateways.Count - 1; i >= 0; i--) { if (gateways[i].Name.Equals("Gift Certificate Payment Provider")) { continue; } if (gateways[i].ClassId.Equals(classId)) { continue; } filteredGateways.Add(gateways[i]); } return(filteredGateways); }
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 Page_Load(object sender, EventArgs e) { if (AbleContext.Current.Store.Settings.EnablePaymentProfilesStorage) { if (!Page.IsPostBack && !_user.IsAnonymous) { var profiles = _user.PaymentProfiles .Where(p => (!p.LastDayOfExpiry.HasValue || p.LastDayOfExpiry > LocaleHelper.LocalNow) && PaymentGatewayDataSource.GetPaymentGatewayIdByClassId(p.GatewayIdentifier) > 0) .ToDictionary(p => p.Id, p => string.Format("{0} ending in {1}", p.InstrumentType, p.ReferenceNumber)); if (profiles.Count > 0) { CardPH.Visible = false; ProfilesPH.Visible = true; profiles.Add(-1, "Add New Payment"); ProfilesList.Items.Clear(); foreach (var profile in profiles) { ProfilesList.Items.Add(new ListItem() { Text = profile.Value, Value = profile.Key.ToString() }); } ListItem item = ProfilesList.Items.FindByValue(_user.Settings.DefaultPaymentProfileId.ToString()); if (item != null) { item.Selected = true; } } else { CardPH.Visible = true; ProfilesPH.Visible = false; } } CardType.AutoPostBack = true; } // UPDATE MAX PAYMENT AMOUNT TO ORDER TOTAL IF NO VALUE IS SPECIFIED if (this.MaxPaymentAmount == 0) { this.MaxPaymentAmount = AbleContext.Current.User.Basket.Items.TotalPrice(); } if (Page.IsPostBack) { // VALIDATE IF CORRECT PAYMENT METHOD TYPE IS SELECTED PaymentMethod paymentMethod = PaymentMethodDataSource.Load(AlwaysConvert.ToInt(CardType.SelectedValue)); if (paymentMethod != null) { // INITIALIZE SELECTED CARD TYPE FOR VALIDATION PaymentInstrumentType paymentInstrumentType = paymentMethod.PaymentInstrumentType; CardNumberValidator1.AcceptedCardType = paymentInstrumentType.ToString(); } } }
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); } }
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); } }
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)); } }
/// <summary> /// Homogenizes the list of items to the same concretee type /// for binding in the datagrid. /// </summary> /// <returns>List of gateway items</returns> private IList <GatewayItem> LoadGateways() { IList <PaymentGateway> configuredGateways = PaymentGatewayDataSource.LoadAll(); List <GatewayItem> gatewayItems = new List <GatewayItem>(); IList <IPaymentProvider> providers = PaymentProviderDataSource.GetProviders(true); string epayProviderClassId = Misc.GetClassId(typeof(CommerceBuilder.Payments.Providers.EPaymentIntegrator.EPayProvider)); foreach (var provider in providers) { string classId = Misc.GetClassId(provider.GetType()); // PROVIDER IS NOT CONFIGURED ALREADY, ALLOW MULTIPLE INSTANCES OF IBIZ PROVIDER if (!configuredGateways.Any(g => g.ClassId == classId) || classId == epayProviderClassId) { gatewayItems.Add(new GatewayItem(Misc.GetClassId(provider.GetType()), provider.Name, provider.GetLogoUrl(Page.ClientScript), GetSupportedTransactions(provider))); } } return(gatewayItems); }
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 Page_Load(object sender, System.EventArgs e) { Store store = AbleContext.Current.Store; StoreSettingsManager settings = store.Settings; // FULLTEXT SEARCH bool ftsIsInstalled = KeywordSearchHelper.IsFullTextSearchInstalled(false); bool ftsIsEnabled = false; if (ftsIsInstalled) { ftsIsEnabled = KeywordSearchHelper.IsFullTextSearchEnabled(false); if (!ftsIsEnabled) { // ATTEMPT TO ENABLE FULLTEXT SEARCH IF POSSIBLE KeywordSearchHelper.EnableFullTextSearch(false); ftsIsEnabled = KeywordSearchHelper.IsFullTextSearchEnabled(false); } } ListItem sqlFtsProviderItem = SearchProvider.Items.FindByValue("SqlFtsSearchProvider"); if (sqlFtsProviderItem != null && !(ftsIsInstalled && ftsIsEnabled)) { SearchProvider.Items.Remove(sqlFtsProviderItem); } bool authorizeNetCIMEnabled = PaymentGatewayDataSource.GetPaymentGatewayIdByClassId("CommerceBuilder.Payments.Providers.AuthorizeNetCIM.AuthNetCIMProvider, CommerceBuilder.AuthorizeNetCIM") > 0; if (!authorizeNetCIMEnabled) { tdPaymentStorage.Attributes.Add("class", "inactive"); PaymentStorageLabel.Text = "Only available with Authorize.Net CIM gateway"; } PaymentStorage.Enabled = authorizeNetCIMEnabled; if (!Page.IsPostBack) { // GENERAL StoreName.Text = store.Name; if (AbleContext.Current.User.IsSecurityAdmin) { StoreUrl.Text = store.StoreUrl; StoreUrlLiteral.Visible = false; } else { StoreUrlLiteral.Text = store.StoreUrl; StoreUrl.Visible = false; } if (!string.IsNullOrEmpty(settings.SiteDisclaimerMessage)) { SiteDisclaimerMessage.Text = settings.SiteDisclaimerMessage; } // VOLUME DISCOUNTS DiscountMode.SelectedIndex = (int)store.VolumeDiscountMode; // INVENTORY EnableInventory.Checked = settings.EnableInventory; InventoryPanel.Visible = settings.EnableInventory; CurrentInventoryDisplayMode.SelectedIndex = settings.InventoryDisplayDetails ? 1 : 0; InStockMessage.Text = settings.InventoryInStockMessage; OutOfStockMessage.Text = settings.InventoryOutOfStockMessage; InventoryAvailabilityMessage.Text = settings.InventoryAvailabilityMessage; RestockNotificationLink.Text = settings.InventoryRestockNotificationLink; IList <EmailTemplate> emailTemplates = EmailTemplateDataSource.LoadAll(); foreach (EmailTemplate template in emailTemplates) { RestockNotificationEmail.Items.Add(new ListItem(template.Name, template.Id.ToString())); } RestockNotificationEmail.ClearSelection(); ListItem item = RestockNotificationEmail.Items.FindByValue(settings.InventoryRestockNotificationEmailTemplateId.ToString()); if (item != null) { item.Selected = true; } // ORDER SETTINGS UpdateNextOrderNumber(store); OrderIdIncrement.Text = store.OrderIdIncrement.ToString(); OrderMinAmount.Text = (settings.OrderMinimumAmount > 0) ? settings.OrderMinimumAmount.ToString() : string.Empty; OrderMaxAmount.Text = (settings.OrderMaximumAmount > 0) ? settings.OrderMaximumAmount.ToString() : string.Empty; EnableOnePageCheckout.Checked = settings.EnableOnePageCheckout; // GUEST CHECKOUT OPTIONS AllowGuestCheckout.Checked = settings.AllowAnonymousCheckout; LimitedGuestCheckout.Checked = !settings.AllowAnonymousCheckoutForDigitalGoods && settings.AllowAnonymousCheckout; DisableGuestCheckout.Checked = !settings.AllowAnonymousCheckout; // CHECKOUT PAYMENT SETTINGS AllowOnlyFullPayments.Checked = !settings.AcceptOrdersWithInvalidPayment; IgnoreFailedPayments.Checked = settings.AcceptOrdersWithInvalidPayment; AllowPartialPaymnets.Checked = settings.EnablePartialPaymentCheckouts && !settings.AcceptOrdersWithInvalidPayment; EnableShipMessage.Checked = settings.EnableShipMessage; EnableShipToMultipleAddresses.Checked = settings.EnableShipToMultipleAddresses; if (!string.IsNullOrEmpty(settings.CheckoutTermsAndConditions)) { CheckoutTerms.Text = settings.CheckoutTermsAndConditions; } EnableOrderNotes.Checked = settings.EnableCustomerOrderNotes; // UNITS WeightUnit.DataSource = EnumToHashtable(typeof(CommerceBuilder.Shipping.WeightUnit)); WeightUnit.DataTextField = "Key"; WeightUnit.DataValueField = "Value"; WeightUnit.DataBind(); MeasurementUnit.DataSource = EnumToHashtable(typeof(CommerceBuilder.Shipping.MeasurementUnit)); MeasurementUnit.DataTextField = "Key"; MeasurementUnit.DataValueField = "Value"; MeasurementUnit.DataBind(); item = WeightUnit.Items.FindByValue(store.WeightUnitId.ToString()); if (item != null) { item.Selected = true; } item = MeasurementUnit.Items.FindByValue(store.MeasurementUnitId.ToString()); if (item != null) { item.Selected = true; } BindTimeZone(); PostalCodeCountries.Text = settings.PostalCodeCountries; // PRODUCTS PURCHASING ProductPurchasingDisabled.Checked = settings.ProductPurchasingDisabled; // WISHLISTS ENABLED WishlistsEnabled.Checked = settings.WishlistsEnabled; // SEARCH SETTINGS EnableWishlistSearch.Checked = settings.WishlistSearchEnabled; MinimumSearchLength.Text = settings.MinimumSearchLength.ToString(); PopularSearchThreshold.Text = settings.PopularSearchThreshold.ToString(); CategorySearchDisplayLimit.Text = settings.CategorySearchDisplayLimit.ToString(); item = SearchProvider.Items.FindByValue(ApplicationSettings.Instance.SearchProvider); if (item != null) { item.Selected = true; } // RESTRICT STORE ACCESS ListItem option = RestrictStoreAccessOptions.Items.FindByValue(settings.RestrictStoreAccess.ToString()); if (option != null) { option.Selected = true; } IList <Group> allGroups = GroupDataSource.LoadForStore(AbleContext.Current.StoreId, "Name ASC"); IList <Group> nonAdminGroups = allGroups.FindAll(grp => !grp.IsInRole(Role.AllAdminRoles)) as IList <Group>; IList <Group> authorizedGroups = allGroups.FindAll(grp => grp.IsInRole(Role.CustomerRoles)); AuthorizedGroups.DataSource = nonAdminGroups as IList <Group>; AuthorizedGroups.DataBind(); foreach (ListItem groupItem in AuthorizedGroups.Items) { int groupId = AlwaysConvert.ToInt(groupItem.Value); foreach (Group group in authorizedGroups) { if (groupId == group.Id) { groupItem.Selected = true; break; } } } PaymentStorage.Checked = settings.EnablePaymentProfilesStorage; EnableHtmlEditor.Checked = settings.EnableWysiwygEditor; } }
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(); } }
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(); } }
/// <summary> /// Gets instances of all classes available that implement the IPaymentProvider interface /// </summary> /// <returns>List of instances of classes implementing IPaymentProvider</returns> public static List <IPaymentProvider> GetProviders() { List <IPaymentProvider> providers = new List <IPaymentProvider>(); List <string> providerNames = new List <string>(); PaymentGatewayCollection configuredGateways = PaymentGatewayDataSource.LoadForStore(); //LOOP THROUGH ALL THE ASSEMBLIES IN THE CURRENT DOMAIN foreach (System.Reflection.Assembly assemblyInstance in AppDomain.CurrentDomain.GetAssemblies()) { try { //LOOP THROUGH ALL TYPES IN THE ASSEMBLY foreach (Type thisType in assemblyInstance.GetTypes()) { //ONLY CHECK CLASSES THAT ARE NOT ABSTRACT if ((thisType.IsClass && !thisType.IsAbstract)) { //LOOP THROUGH ALL INTERFACES THIS TYPE IMPLMEMENTS foreach (Type thisInterface in thisType.GetInterfaces()) { //ONLY PROCEED IF THE CLASS IMPLEMENTS PAYMENT PROVIDER INTERFACE string interfaceFullName = thisInterface.FullName; if (!string.IsNullOrEmpty(interfaceFullName) && (interfaceFullName == "CommerceBuilder.Payments.Providers.IPaymentProvider")) { //GET THE CLASS ID WITHOUT VERSION string classId = Utility.Misc.GetClassId(thisType); //MAKE SURE WE ONLY LIST THIS PROVIDER ONE TIME string loweredClassId = classId.ToLowerInvariant(); if (!providerNames.Contains(loweredClassId)) { //DO NOT INCLUDE GIFT CERTIFICATE PROVIDER if (classId != Utility.Misc.GetClassId(typeof(GiftCertificatePaymentProvider))) { //ONLY INCLUDE GATEWAYS NOT CONFIGURED ALREADY if (!IsConfigured(configuredGateways, classId)) { try { //ONLY INCLUDE GATEWAYS THAT WE CAN CREATE INSTANCES OF IPaymentProvider instance = Activator.CreateInstance(Type.GetType(classId)) as IPaymentProvider; if (instance != null) { providers.Add(instance); } } catch (Exception ex) { Logger.Warn("Could not create an instance of the payment provider: " + classId, ex); throw; } } } //DO NOT LIST THIS PROVIDER AGAIN providerNames.Add(loweredClassId); } } } } } } catch { //ignore error } } //SORT BY NAME providers.Sort(CompareProvidersByName); return(providers); }
/// <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); }