Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Globalization;
- using System.Linq;
- using System.Text.RegularExpressions;
- using System.Web.Mvc;
- using System.Web.Security;
- using SYD.Models.AuthNetService;
- namespace SYD.Models
- {
- public class AuthNetApi
- {
- #region Variable Declarations
- private static readonly SYDEntities db = new SYDEntities();
- public static Service Service
- {
- get
- {
- return new Service(Live);
- }
- }
- public static bool Live
- {
- get
- {
- return bool.Parse(ConfigurationManager.AppSettings["AuthorizeNetLiveServers"]);
- }
- set
- {
- ConfigurationManager.AppSettings["AuthorizeNetLiveServers"] = value.ToString();
- }
- }
- #endregion
- #region Enumerators
- public enum UserType
- {
- Administrator,
- Investor,
- Owner
- }
- #endregion
- #region Custom Methods
- public static bool ParseDirectResponse(string response)
- {
- return false;
- }
- public static MerchantAuthenticationType GetMerchantAuthentication(string nameToken, string transactionKey)
- {
- return new MerchantAuthenticationType
- {
- name = nameToken,
- transactionKey = transactionKey
- };
- }
- public static MerchantAuthenticationType GetMerchantAuthentication(CustomerProfile customerProfile)
- {
- return GetMerchantAuthentication(customerProfile.AuthNetAccount.NameToken, customerProfile.AuthNetAccount.KeyToken);
- }
- public static bool CheckAccountStatus(ModelStateDictionary modelState, UserProfile profile)
- {
- List<bool> successes = new List<bool>();
- if (profile == null)
- successes.Add(false);
- else
- {
- if (Roles.IsUserInRole(profile.UserName, "Developer") || Roles.IsUserInRole(profile.UserName, "Administrator"))
- successes.Add(CreateCustomerProfile(modelState, profile, UserType.Administrator));
- if (Roles.IsUserInRole(profile.UserName, "Investor"))
- successes.Add(CreateCustomerProfile(modelState, profile, UserType.Investor));
- if (Roles.IsUserInRole(profile.UserName, "Owner"))
- successes.Add(CreateCustomerProfile(modelState, profile, UserType.Owner));
- }
- return successes.All(s => true);
- }
- public static bool ValidateProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
- {
- if (customerProfile == null)
- {
- modelState.AddModelError("", "Unable to retrieve customer profile. There was no profile id specified.");
- return false;
- }
- if (!CheckAccountStatus(modelState, customerProfile.UserProfile))
- {
- modelState.AddModelError("", "The application was unable to retrieve and/or establish a proper customer profile for the current user.");
- return false;
- }
- if (customerProfile.AuthNetAccount == null)
- {
- modelState.AddModelError("", "Unable to retrieve customer profile. The associated Authorize.Net account was not found.");
- return false;
- }
- if (!(customerProfile.AuthNetProfileId > 0))
- {
- modelState.AddModelError("", "Unable to retrieve customer profile. The profile id specified was invalid.");
- return false;
- }
- return true;
- }
- public static bool ValidateAddress(ModelStateDictionary modelState, CustomerAddressType address)
- {
- if (address == null)
- {
- modelState.AddModelError("", "Street, City, State & Zip are required!");
- return false;
- }
- if (string.IsNullOrWhiteSpace(address.address) || string.IsNullOrWhiteSpace(address.zip))
- {
- if (string.IsNullOrWhiteSpace(address.address))
- {
- modelState.AddModelError("", "Street address is required!");
- }
- if (string.IsNullOrWhiteSpace(address.zip))
- {
- modelState.AddModelError("", "Zip Code is required!");
- }
- return false;
- }
- return true;
- }
- public static List<CustomerProfileMaskedType> GetCustomerProfiles(ModelStateDictionary modelState, UserProfile userProfile)
- {
- if (!CheckAccountStatus(modelState, userProfile))
- {
- modelState.AddModelError("", "The application was unable to retrieve and/or establish a proper customer profile for the current user.");
- return null;
- }
- List<CustomerProfileMaskedType> profiles = new List<CustomerProfileMaskedType>();
- foreach (GetCustomerProfileResponseType response in from prof in userProfile.CustomerProfiles
- let merchantAuthentication =
- GetMerchantAuthentication(
- prof.AuthNetAccount.NameToken, prof.AuthNetAccount.KeyToken)
- select
- Service.GetCustomerProfile(merchantAuthentication,
- prof.AuthNetProfileId))
- {
- switch (response.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in response.messages)
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- default:
- profiles.Add(response.profile);
- break;
- }
- }
- return profiles;
- }
- public static PaymentScheduleTypeInterval GetPaymentInterval(short length, ARBSubscriptionUnitEnum unit)
- {
- return new PaymentScheduleTypeInterval
- {
- length = length,
- unit = unit
- };
- }
- public static PaymentScheduleType GetPaymentSchedule(PaymentScheduleTypeInterval interval, DateTime startDate)
- {
- return new PaymentScheduleType
- {
- interval = interval,
- startDate = startDate,
- startDateSpecified = true,
- totalOccurrences = 9999,
- totalOccurrencesSpecified = true
- };
- }
- public static DateTime GetMountainTime()
- {
- TimeZoneInfo zoneInfo = TimeZoneInfo.Local;
- TimeZoneInfo mountainZone =
- TimeZoneInfo.FindSystemTimeZoneById(zoneInfo.IsDaylightSavingTime(DateTime.Now)
- ? "Mountain Daylight Time"
- : "Mountain Standard Time");
- return TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), mountainZone);
- }
- public static DateTime ConvertMountainToPacificTime(DateTime mountainTime)
- {
- mountainTime = mountainTime.ToUniversalTime();
- TimeZoneInfo zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(mountainTime.IsDaylightSavingTime() ? "US Pacific Daylight Time" : "US Pacific Standard Time");
- return TimeZoneInfo.ConvertTimeFromUtc(mountainTime, zoneInfo);
- }
- #endregion
- #region Get Methods
- public static long[] GetCustomerProfileIds(ModelStateDictionary modelState, AuthNetAccount authNetAccount)
- {
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(authNetAccount.NameToken,
- authNetAccount.KeyToken);
- GetCustomerProfileIdsResponseType result = Service.GetCustomerProfileIds(merchantAuthentication);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Ok:
- return result.ids;
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not created properly. If you continue to see this error, please contact an administrator!");
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- }
- }
- public static CustomerProfileMaskedType GetCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
- {
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- GetCustomerProfileResponseType result = Service.GetCustomerProfile(merchantAuthentication, customerProfile.AuthNetProfileId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Ok:
- return result.profile;
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- default:
- modelState.AddModelError("",
- "Unable to retrieve customer profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- }
- }
- public static CustomerPaymentProfileMaskedType GetCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId)
- {
- if (!ValidateProfile(modelState, customerProfile))
- return null;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- GetCustomerPaymentProfileResponseType result = Service.GetCustomerPaymentProfile(merchantAuthentication,
- customerProfile.AuthNetProfileId,
- billingId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Ok:
- return result.paymentProfile;
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- default:
- modelState.AddModelError("",
- "Unable to retrieve payment profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- }
- }
- public static CustomerAddressExType GetCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, long shippingId)
- {
- if (!ValidateProfile(modelState, customerProfile))
- return null;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- GetCustomerShippingAddressResponseType result = Service.GetCustomerShippingAddress(merchantAuthentication,
- customerProfile.AuthNetProfileId,
- shippingId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Ok:
- return result.address;
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- default:
- modelState.AddModelError("",
- "Unable to retrieve payment profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- }
- }
- public static string GetHostedProfilePageToken(ModelStateDictionary modelState, CustomerProfile customerProfile, string redirectUrl)
- {
- if (!ValidateProfile(modelState, customerProfile))
- return null;
- if (string.IsNullOrWhiteSpace(redirectUrl))
- {
- modelState.AddModelError("", "Unable to retrieve Hosted Profile Page. Redirect Url is required!");
- }
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- SettingType[] settings = new[]
- {
- new SettingType { settingName = "hostedProfileReturnUrl", settingValue = redirectUrl },
- new SettingType { settingName = "hostedProfileReturnUrlText", settingValue = "Return to Structure Your Deal" },
- new SettingType { settingName = "hostedProfilePageBorderVisible", settingValue = "true" },
- new SettingType { settingName = "hostedProfileHeadingBgColor", settingValue = "#2c88c9" }
- };
- GetHostedProfilePageResponseType result = Service.GetHostedProfilePage(merchantAuthentication,
- customerProfile.AuthNetProfileId, settings);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Ok:
- return result.token;
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- default:
- modelState.AddModelError("",
- "Unable to retrieve hosted profile page token. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return null;
- }
- }
- #endregion
- #region Create Methods
- public static bool CreateCustomerProfile(ModelStateDictionary modelState, UserProfile userProfile, UserType userType)
- {
- AuthNetAccount authNetAccount = null;
- switch (userType)
- {
- case UserType.Administrator:
- return CreateCustomerProfile(modelState, userProfile, UserType.Investor) &&
- CreateCustomerProfile(modelState, userProfile, UserType.Owner);
- case UserType.Investor:
- authNetAccount = db.AuthNetAccounts.First(a => a.Description == "Investor");
- break;
- case UserType.Owner:
- authNetAccount = db.AuthNetAccounts.First(a => a.Description == "Owner");
- break;
- }
- if (authNetAccount == null)
- {
- modelState.AddModelError("",
- new ArgumentNullException("",
- string.Format(
- "Authorize.Net account was found! Unable to create a new customer profile!")));
- return false;
- }
- if (userProfile.CustomerProfiles.Any(c => c.AuthNetAccount.Description == authNetAccount.Description && c.AuthNetProfileId > 0))
- {
- return true;
- }
- CustomerProfile customerProfile = new CustomerProfile
- {
- AuthNetAccountId = authNetAccount.AuthNetAccountId,
- AuthNetAccount = authNetAccount,
- UserId = userProfile.UserId,
- Description =
- string.Format("{0} account for {1} ({2})", authNetAccount.Description, userProfile.UserName,
- userProfile.UserId)
- };
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- CustomerProfileType customerProfileType = new CustomerProfileType
- {
- email = userProfile.EmailAddress,
- merchantCustomerId =
- userProfile.UserId.ToString(CultureInfo.InvariantCulture),
- description = customerProfile.Description
- };
- CreateCustomerProfileResponseType result = Service.CreateCustomerProfile(merchantAuthentication, customerProfileType,
- ValidationModeEnum.none);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- case "E00039":
- customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
- if (!db.CustomerProfiles.Any(c => c.UserId == userProfile.UserId && c.AuthNetProfileId == customerProfile.AuthNetProfileId))
- {
- db.CustomerProfiles.Add(customerProfile);
- db.SaveChanges();
- }
- return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- customerProfile.AuthNetProfileId = result.customerProfileId;
- db.CustomerProfiles.Add(customerProfile);
- db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool CreateCustomerPaymentProfile
- (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerPaymentProfileType paymentProfile)
- {
- if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, paymentProfile.billTo))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- CreateCustomerPaymentProfileResponseType result = Service.CreateCustomerPaymentProfile(merchantAuthentication,
- customerProfile
- .AuthNetProfileId,
- paymentProfile,
- ValidationModeEnum.liveMode);
- modelState.AddModelError("", string.Format("Validation Response: {0}", result.validationDirectResponse));
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- case "E00039":
- // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
- //customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
- //db.CustomerProfiles.Add(customerProfile);
- //db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
- //customerProfile.AuthNetProfileId = result.customerProfileId;
- //db.CustomerProfiles.Add(customerProfile);
- //db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool CreateCustomerShippingAddress
- (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerAddressType addressInfo)
- {
- if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, addressInfo))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- CreateCustomerShippingAddressResponseType result = Service.CreateCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, addressInfo);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- case "E00039":
- // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
- //customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
- //db.CustomerProfiles.Add(customerProfile);
- //db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
- //customerProfile.AuthNetProfileId = result.customerProfileId;
- //db.CustomerProfiles.Add(customerProfile);
- //db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- // TODO: CODE THE CUSTOMER PROFILE TRANSACTION SECTION AFTER CODING THE CART TABLES
- public static CreateCustomerProfileTransactionResponseType CreateCustomerProfileTransaction()
- {
- throw new NotImplementedException("Creating customer profile transactions has not been implemented yet.");
- }
- #endregion
- #region Delete Methods
- public static bool DeleteCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
- {
- if (!ValidateProfile(modelState, customerProfile))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- DeleteCustomerProfileResponseType result = Service.DeleteCustomerProfile(merchantAuthentication,
- customerProfile.AuthNetProfileId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool DeleteCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId)
- {
- if (!ValidateProfile(modelState, customerProfile) || !(billingId > 0))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- DeleteCustomerPaymentProfileResponseType result = Service.DeleteCustomerPaymentProfile(merchantAuthentication,
- customerProfile.AuthNetProfileId, billingId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool DeleteCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, long shippingId)
- {
- if (!ValidateProfile(modelState, customerProfile) || !(shippingId > 0))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- DeleteCustomerShippingAddressResponseType result = Service.DeleteCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, shippingId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- #endregion
- #region Update Methods
- public static bool UpdateCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
- {
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- CustomerProfileExType customerProfileType = new CustomerProfileExType
- {
- customerProfileId = customerProfile.AuthNetProfileId,
- email = customerProfile.UserProfile.EmailAddress,
- merchantCustomerId =
- customerProfile.UserId.ToString(CultureInfo.InvariantCulture),
- description = customerProfile.Description
- };
- UpdateCustomerProfileResponseType result = Service.UpdateCustomerProfile(merchantAuthentication, customerProfileType);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- db.Entry(customerProfile).State = EntityState.Modified;
- db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool UpdateCustomerPaymentProfile
- (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerPaymentProfileExType paymentProfile)
- {
- if (!ValidateProfile(modelState, customerProfile))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- CreateCustomerPaymentProfileResponseType result = Service.CreateCustomerPaymentProfile(merchantAuthentication,
- customerProfile
- .AuthNetProfileId,
- paymentProfile,
- ValidationModeEnum.liveMode);
- modelState.AddModelError("", string.Format("Validation Response: {0}", result.validationDirectResponse));
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool UpdateCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerAddressExType addressInfo)
- {
- if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, addressInfo))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- UpdateCustomerShippingAddressResponseType result = Service.UpdateCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, addressInfo);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- case "E00039":
- return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static UpdateSplitTenderGroupResponseType UpdateSplitTenderGroup()
- {
- throw new NotImplementedException("SYD requires that all payments be made by a single payment source. There is no need to update orders that have multiple transactions as each order should only have one transaction.");
- }
- #endregion
- #region Subscription Methods
- public static bool CreateSubscription(ModelStateDictionary modelState, long profileId, Subscription sub, ARBSubscriptionType subscription)
- {
- CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
- if (customerProfile == null)
- {
- modelState.AddModelError("", "Could not retrieve customer profile. Unable to create subscription!");
- return false;
- }
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- ARBCreateSubscriptionResponseType result = Service.ARBCreateSubscription(merchantAuthentication, subscription);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- case "E00012":
- if (!db.CustomerSubscriptions.Any(s => s.UserId == customerProfile.UserId && s.SubscriptionId == sub.SubscriptionId))
- {
- CustomerSubscription customerSubscription = new CustomerSubscription
- {
- UserId = customerProfile.UserId,
- SubscriptionId = sub.SubscriptionId,
- AuthNetSubscriptionId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\.\s").Groups["ID"].Value),
- StartDate =
- subscription.paymentSchedule.startDate
- };
- db.CustomerSubscriptions.Add(customerSubscription);
- }
- else
- {
- var oldSub =
- db.CustomerSubscriptions.OrderByDescending(o => o.StartDate).First(
- s =>
- s.UserId == customerProfile.UserId && s.SubscriptionId == sub.SubscriptionId);
- oldSub.AuthNetSubscriptionId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\.\s").Groups["ID"].Value);
- db.Entry(oldSub).State = EntityState.Modified;
- }
- db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- CustomerSubscription customerSub = new CustomerSubscription
- {
- UserId = customerProfile.UserId,
- CustomerProfileId = customerProfile.CustomerProfileId,
- SubscriptionId = sub.SubscriptionId,
- AuthNetSubscriptionId = result.subscriptionId,
- StartDate =
- subscription.paymentSchedule.startDate
- };
- db.CustomerSubscriptions.Add(customerSub);
- db.SaveChanges();
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool UpdateSubscription(ModelStateDictionary modelState, long profileId, long subscriptionId, ARBSubscriptionType subscription)
- {
- CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
- if (customerProfile == null)
- {
- modelState.AddModelError("", "Could not retrieve customer profile. Unable to update subscription!");
- return false;
- }
- if (!ValidateProfile(modelState, customerProfile) || !(profileId > 0) || !(subscriptionId > 0))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- ARBUpdateSubscriptionResponseType result = Service.ARBUpdateSubscription(merchantAuthentication, subscriptionId, subscription);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- //case "E00039":
- // customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
- // if (!db.CustomerProfiles.Any(c => c.AuthNetProfileId == customerProfile.AuthNetProfileId))
- // {
- // db.CustomerProfiles.Add(customerProfile);
- // db.SaveChanges();
- // }
- // return true;
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not updated properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool CancelSubscription(ModelStateDictionary modelState, long profileId, long subscriptionId)
- {
- CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
- if (customerProfile == null)
- {
- modelState.AddModelError("", "Could not retrieve customer profile. Unable to delete subscription!");
- return false;
- }
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- ARBCancelSubscriptionResponseType result = Service.ARBCancelSubscription(merchantAuthentication, subscriptionId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the customer profile was not deleted properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- public static bool GetSubscriptionStatus(ModelStateDictionary modelState, long profileId, long subscriptionId)
- {
- CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
- if (customerProfile == null)
- {
- modelState.AddModelError("", "Could not retrieve customer profile. Unable to retrieve subscription status!");
- return false;
- }
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- ARBGetSubscriptionStatusResponseType result = Service.ARBGetSubscriptionStatus(merchantAuthentication, subscriptionId);
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- switch (message.code)
- {
- default:
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- break;
- }
- }
- return false;
- case MessageTypeEnum.Ok:
- switch (result.status)
- {
- case ARBSubscriptionStatusEnum.active:
- return true;
- case ARBSubscriptionStatusEnum.canceled:
- return false;
- case ARBSubscriptionStatusEnum.expired:
- return false;
- case ARBSubscriptionStatusEnum.suspended:
- return false;
- case ARBSubscriptionStatusEnum.terminated:
- return false;
- default:
- modelState.AddModelError("", string.Format("The Subscription Status of {0} was not handled properly by the application and is inactive.", result.status));
- return false;
- }
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- #endregion
- #region Validation Methods
- public static bool ValidateCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId, long shippingId, string cardCode = null)
- {
- if (!ValidateProfile(modelState, customerProfile) || !(billingId > 0))
- return false;
- MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
- ValidateCustomerPaymentProfileResponseType result = Service.ValidateCustomerPaymentProfile(merchantAuthentication, customerProfile.AuthNetProfileId, billingId, shippingId, cardCode, ValidationModeEnum.liveMode);
- modelState.AddModelError("", string.Format("Validation Response: {0}", result.directResponse));
- switch (result.resultCode)
- {
- case MessageTypeEnum.Error:
- foreach (MessagesTypeMessage message in result.messages)
- {
- modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
- }
- return false;
- case MessageTypeEnum.Ok:
- return true;
- default:
- modelState.AddModelError("",
- "An unknown error has occurred. It is likely that the payment profile was not created properly. If you continue to see this error, please contact an administrator!");
- return false;
- }
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement