Advertisement
LaughingMan

Untitled

Apr 12th, 2018
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 36.85 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Configuration;
  4. using System.Data;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text.RegularExpressions;
  8. using System.Web.Mvc;
  9. using System.Web.Security;
  10. using SYD.Models.AuthNetService;
  11.  
  12. namespace SYD.Models
  13. {
  14.     public class AuthNetApi
  15.     {
  16.         #region Variable Declarations
  17.         private static readonly SYDEntities db = new SYDEntities();
  18.  
  19.         public static Service Service
  20.         {
  21.             get
  22.             {
  23.                 return new Service(Live);
  24.             }
  25.         }
  26.  
  27.         public static bool Live
  28.         {
  29.             get
  30.             {
  31.                 return bool.Parse(ConfigurationManager.AppSettings["AuthorizeNetLiveServers"]);
  32.             }
  33.             set
  34.             {
  35.                 ConfigurationManager.AppSettings["AuthorizeNetLiveServers"] = value.ToString();
  36.             }
  37.         }
  38.         #endregion
  39.  
  40.         #region Enumerators
  41.         public enum UserType
  42.         {
  43.             Administrator,
  44.             Investor,
  45.             Owner
  46.         }
  47.         #endregion
  48.  
  49.         #region Custom Methods
  50.         public static bool ParseDirectResponse(string response)
  51.         {
  52.             return false;
  53.         }
  54.  
  55.         public static MerchantAuthenticationType GetMerchantAuthentication(string nameToken, string transactionKey)
  56.         {
  57.             return new MerchantAuthenticationType
  58.                        {
  59.                            name = nameToken,
  60.                            transactionKey = transactionKey
  61.                        };
  62.         }
  63.  
  64.         public static MerchantAuthenticationType GetMerchantAuthentication(CustomerProfile customerProfile)
  65.         {
  66.             return GetMerchantAuthentication(customerProfile.AuthNetAccount.NameToken, customerProfile.AuthNetAccount.KeyToken);
  67.         }
  68.  
  69.         public static bool CheckAccountStatus(ModelStateDictionary modelState, UserProfile profile)
  70.         {
  71.             List<bool> successes = new List<bool>();
  72.  
  73.             if (profile == null)
  74.                 successes.Add(false);
  75.             else
  76.             {
  77.                 if (Roles.IsUserInRole(profile.UserName, "Developer") || Roles.IsUserInRole(profile.UserName, "Administrator"))
  78.                     successes.Add(CreateCustomerProfile(modelState, profile, UserType.Administrator));
  79.                 if (Roles.IsUserInRole(profile.UserName, "Investor"))
  80.                     successes.Add(CreateCustomerProfile(modelState, profile, UserType.Investor));
  81.                 if (Roles.IsUserInRole(profile.UserName, "Owner"))
  82.                     successes.Add(CreateCustomerProfile(modelState, profile, UserType.Owner));
  83.             }
  84.             return successes.All(s => true);
  85.         }
  86.  
  87.         public static bool ValidateProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
  88.         {
  89.             if (customerProfile == null)
  90.             {
  91.                 modelState.AddModelError("", "Unable to retrieve customer profile. There was no profile id specified.");
  92.                 return false;
  93.             }
  94.             if (!CheckAccountStatus(modelState, customerProfile.UserProfile))
  95.             {
  96.                 modelState.AddModelError("", "The application was unable to retrieve and/or establish a proper customer profile for the current user.");
  97.                 return false;
  98.             }
  99.             if (customerProfile.AuthNetAccount == null)
  100.             {
  101.                 modelState.AddModelError("", "Unable to retrieve customer profile. The associated Authorize.Net account was not found.");
  102.                 return false;
  103.             }
  104.             if (!(customerProfile.AuthNetProfileId > 0))
  105.             {
  106.                 modelState.AddModelError("", "Unable to retrieve customer profile. The profile id specified was invalid.");
  107.                 return false;
  108.             }
  109.             return true;
  110.         }
  111.  
  112.         public static bool ValidateAddress(ModelStateDictionary modelState, CustomerAddressType address)
  113.         {
  114.             if (address == null)
  115.             {
  116.                 modelState.AddModelError("", "Street, City, State & Zip are required!");
  117.                 return false;
  118.             }
  119.             if (string.IsNullOrWhiteSpace(address.address) || string.IsNullOrWhiteSpace(address.zip))
  120.             {
  121.                 if (string.IsNullOrWhiteSpace(address.address))
  122.                 {
  123.                     modelState.AddModelError("", "Street address is required!");
  124.                 }
  125.                 if (string.IsNullOrWhiteSpace(address.zip))
  126.                 {
  127.                     modelState.AddModelError("", "Zip Code is required!");
  128.                 }
  129.                 return false;
  130.             }
  131.             return true;
  132.         }
  133.  
  134.         public static List<CustomerProfileMaskedType> GetCustomerProfiles(ModelStateDictionary modelState, UserProfile userProfile)
  135.         {
  136.             if (!CheckAccountStatus(modelState, userProfile))
  137.             {
  138.                 modelState.AddModelError("", "The application was unable to retrieve and/or establish a proper customer profile for the current user.");
  139.                 return null;
  140.             }
  141.  
  142.             List<CustomerProfileMaskedType> profiles = new List<CustomerProfileMaskedType>();
  143.  
  144.             foreach (GetCustomerProfileResponseType response in from prof in userProfile.CustomerProfiles
  145.                                                                 let merchantAuthentication =
  146.                                                                     GetMerchantAuthentication(
  147.                                                                         prof.AuthNetAccount.NameToken, prof.AuthNetAccount.KeyToken)
  148.                                                                 select
  149.                                                                     Service.GetCustomerProfile(merchantAuthentication,
  150.                                                                                                prof.AuthNetProfileId))
  151.             {
  152.                 switch (response.resultCode)
  153.                 {
  154.                     case MessageTypeEnum.Error:
  155.                         foreach (MessagesTypeMessage message in response.messages)
  156.                             modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  157.                         break;
  158.                     default:
  159.                         profiles.Add(response.profile);
  160.                         break;
  161.                 }
  162.             }
  163.             return profiles;
  164.         }
  165.  
  166.         public static PaymentScheduleTypeInterval GetPaymentInterval(short length, ARBSubscriptionUnitEnum unit)
  167.         {
  168.             return new PaymentScheduleTypeInterval
  169.             {
  170.                 length = length,
  171.                 unit = unit
  172.             };
  173.         }
  174.  
  175.         public static PaymentScheduleType GetPaymentSchedule(PaymentScheduleTypeInterval interval, DateTime startDate)
  176.         {
  177.             return new PaymentScheduleType
  178.             {
  179.                 interval = interval,
  180.                 startDate = startDate,
  181.                 startDateSpecified = true,
  182.                 totalOccurrences = 9999,
  183.                 totalOccurrencesSpecified = true
  184.             };
  185.         }
  186.  
  187.         public static DateTime GetMountainTime()
  188.         {
  189.             TimeZoneInfo zoneInfo = TimeZoneInfo.Local;
  190.             TimeZoneInfo mountainZone =
  191.                 TimeZoneInfo.FindSystemTimeZoneById(zoneInfo.IsDaylightSavingTime(DateTime.Now)
  192.                                                         ? "Mountain Daylight Time"
  193.                                                         : "Mountain Standard Time");
  194.             return TimeZoneInfo.ConvertTimeFromUtc(DateTime.Now.ToUniversalTime(), mountainZone);
  195.         }
  196.  
  197.         public static DateTime ConvertMountainToPacificTime(DateTime mountainTime)
  198.         {
  199.             mountainTime = mountainTime.ToUniversalTime();
  200.             TimeZoneInfo zoneInfo = TimeZoneInfo.FindSystemTimeZoneById(mountainTime.IsDaylightSavingTime() ? "US Pacific Daylight Time" : "US Pacific Standard Time");
  201.             return TimeZoneInfo.ConvertTimeFromUtc(mountainTime, zoneInfo);
  202.         }
  203.         #endregion
  204.  
  205.         #region Get Methods
  206.         public static long[] GetCustomerProfileIds(ModelStateDictionary modelState, AuthNetAccount authNetAccount)
  207.         {
  208.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(authNetAccount.NameToken,
  209.                                                                                           authNetAccount.KeyToken);
  210.             GetCustomerProfileIdsResponseType result = Service.GetCustomerProfileIds(merchantAuthentication);
  211.  
  212.             switch (result.resultCode)
  213.             {
  214.                 case MessageTypeEnum.Ok:
  215.                     return result.ids;
  216.                 case MessageTypeEnum.Error:
  217.                     foreach (MessagesTypeMessage message in result.messages)
  218.                     {
  219.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  220.                     }
  221.                     return null;
  222.                 default:
  223.                     modelState.AddModelError("",
  224.                                              "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!");
  225.                     foreach (MessagesTypeMessage message in result.messages)
  226.                     {
  227.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  228.                     }
  229.                     return null;
  230.             }
  231.         }
  232.  
  233.         public static CustomerProfileMaskedType GetCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
  234.         {
  235.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  236.  
  237.             GetCustomerProfileResponseType result = Service.GetCustomerProfile(merchantAuthentication, customerProfile.AuthNetProfileId);
  238.  
  239.             switch (result.resultCode)
  240.             {
  241.                 case MessageTypeEnum.Ok:
  242.                     return result.profile;
  243.                 case MessageTypeEnum.Error:
  244.                     foreach (MessagesTypeMessage message in result.messages)
  245.                     {
  246.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  247.                     }
  248.                     return null;
  249.                 default:
  250.                     modelState.AddModelError("",
  251.                                              "Unable to retrieve customer profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
  252.                     foreach (MessagesTypeMessage message in result.messages)
  253.                     {
  254.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  255.                     }
  256.                     return null;
  257.             }
  258.         }
  259.  
  260.         public static CustomerPaymentProfileMaskedType GetCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId)
  261.         {
  262.             if (!ValidateProfile(modelState, customerProfile))
  263.                 return null;
  264.  
  265.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  266.  
  267.             GetCustomerPaymentProfileResponseType result = Service.GetCustomerPaymentProfile(merchantAuthentication,
  268.                                                                                              customerProfile.AuthNetProfileId,
  269.                                                                                              billingId);
  270.  
  271.             switch (result.resultCode)
  272.             {
  273.                 case MessageTypeEnum.Ok:
  274.                     return result.paymentProfile;
  275.                 case MessageTypeEnum.Error:
  276.                     foreach (MessagesTypeMessage message in result.messages)
  277.                     {
  278.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  279.                     }
  280.                     return null;
  281.                 default:
  282.                     modelState.AddModelError("",
  283.                                              "Unable to retrieve payment profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
  284.                     foreach (MessagesTypeMessage message in result.messages)
  285.                     {
  286.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  287.                     }
  288.                     return null;
  289.             }
  290.         }
  291.  
  292.         public static CustomerAddressExType GetCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, long shippingId)
  293.         {
  294.             if (!ValidateProfile(modelState, customerProfile))
  295.                 return null;
  296.  
  297.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  298.  
  299.             GetCustomerShippingAddressResponseType result = Service.GetCustomerShippingAddress(merchantAuthentication,
  300.                                                                                              customerProfile.AuthNetProfileId,
  301.                                                                                              shippingId);
  302.  
  303.             switch (result.resultCode)
  304.             {
  305.                 case MessageTypeEnum.Ok:
  306.                     return result.address;
  307.                 case MessageTypeEnum.Error:
  308.                     foreach (MessagesTypeMessage message in result.messages)
  309.                     {
  310.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  311.                     }
  312.                     return null;
  313.                 default:
  314.                     modelState.AddModelError("",
  315.                                              "Unable to retrieve payment profile. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
  316.                     foreach (MessagesTypeMessage message in result.messages)
  317.                     {
  318.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  319.                     }
  320.                     return null;
  321.             }
  322.         }
  323.  
  324.         public static string GetHostedProfilePageToken(ModelStateDictionary modelState, CustomerProfile customerProfile, string redirectUrl)
  325.         {
  326.             if (!ValidateProfile(modelState, customerProfile))
  327.                 return null;
  328.             if (string.IsNullOrWhiteSpace(redirectUrl))
  329.             {
  330.                 modelState.AddModelError("", "Unable to retrieve Hosted Profile Page. Redirect Url is required!");
  331.             }
  332.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  333.  
  334.             SettingType[] settings = new[]
  335.                                          {
  336.                                              new SettingType { settingName = "hostedProfileReturnUrl", settingValue = redirectUrl },
  337.                                              new SettingType { settingName = "hostedProfileReturnUrlText", settingValue = "Return to Structure Your Deal" },
  338.                                              new SettingType { settingName = "hostedProfilePageBorderVisible", settingValue = "true" },
  339.                                              new SettingType { settingName = "hostedProfileHeadingBgColor", settingValue = "#2c88c9" }
  340.                                          };
  341.             GetHostedProfilePageResponseType result = Service.GetHostedProfilePage(merchantAuthentication,
  342.                                                                                    customerProfile.AuthNetProfileId, settings);
  343.  
  344.             switch (result.resultCode)
  345.             {
  346.                 case MessageTypeEnum.Ok:
  347.                     return result.token;
  348.                 case MessageTypeEnum.Error:
  349.                     foreach (MessagesTypeMessage message in result.messages)
  350.                     {
  351.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  352.                     }
  353.                     return null;
  354.                 default:
  355.                     modelState.AddModelError("",
  356.                                              "Unable to retrieve hosted profile page token. An unknown error has occurred. If you continue to see this error, please contact an administrator!");
  357.                     foreach (MessagesTypeMessage message in result.messages)
  358.                     {
  359.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  360.                     }
  361.                     return null;
  362.             }
  363.         }
  364.         #endregion
  365.  
  366.         #region Create Methods
  367.         public static bool CreateCustomerProfile(ModelStateDictionary modelState, UserProfile userProfile, UserType userType)
  368.         {
  369.             AuthNetAccount authNetAccount = null;
  370.             switch (userType)
  371.             {
  372.                 case UserType.Administrator:
  373.                     return CreateCustomerProfile(modelState, userProfile, UserType.Investor) &&
  374.                         CreateCustomerProfile(modelState, userProfile, UserType.Owner);
  375.                 case UserType.Investor:
  376.                     authNetAccount = db.AuthNetAccounts.First(a => a.Description == "Investor");
  377.                     break;
  378.                 case UserType.Owner:
  379.                     authNetAccount = db.AuthNetAccounts.First(a => a.Description == "Owner");
  380.                     break;
  381.             }
  382.  
  383.             if (authNetAccount == null)
  384.             {
  385.                 modelState.AddModelError("",
  386.                                          new ArgumentNullException("",
  387.                                                                    string.Format(
  388.                                                                        "Authorize.Net account was found! Unable to create a new customer profile!")));
  389.                 return false;
  390.             }
  391.  
  392.             if (userProfile.CustomerProfiles.Any(c => c.AuthNetAccount.Description == authNetAccount.Description && c.AuthNetProfileId > 0))
  393.             {
  394.                 return true;
  395.             }
  396.  
  397.             CustomerProfile customerProfile = new CustomerProfile
  398.                                                   {
  399.                                                       AuthNetAccountId = authNetAccount.AuthNetAccountId,
  400.                                                       AuthNetAccount = authNetAccount,
  401.                                                       UserId = userProfile.UserId,
  402.                                                       Description =
  403.                                                           string.Format("{0} account for {1} ({2})", authNetAccount.Description, userProfile.UserName,
  404.                                                                         userProfile.UserId)
  405.                                                   };
  406.  
  407.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  408.  
  409.             CustomerProfileType customerProfileType = new CustomerProfileType
  410.                                                           {
  411.                                                               email = userProfile.EmailAddress,
  412.                                                               merchantCustomerId =
  413.                                                                   userProfile.UserId.ToString(CultureInfo.InvariantCulture),
  414.                                                               description = customerProfile.Description
  415.                                                           };
  416.  
  417.             CreateCustomerProfileResponseType result = Service.CreateCustomerProfile(merchantAuthentication, customerProfileType,
  418.                                                                                      ValidationModeEnum.none);
  419.  
  420.             switch (result.resultCode)
  421.             {
  422.                 case MessageTypeEnum.Error:
  423.                     foreach (MessagesTypeMessage message in result.messages)
  424.                     {
  425.                         switch (message.code)
  426.                         {
  427.                             case "E00039":
  428.                                 customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
  429.                                 if (!db.CustomerProfiles.Any(c => c.UserId == userProfile.UserId && c.AuthNetProfileId == customerProfile.AuthNetProfileId))
  430.                                 {
  431.                                     db.CustomerProfiles.Add(customerProfile);
  432.                                     db.SaveChanges();
  433.                                 }
  434.                                 return true;
  435.                             default:
  436.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  437.                                 break;
  438.                         }
  439.                     }
  440.                     return false;
  441.                 case MessageTypeEnum.Ok:
  442.                     customerProfile.AuthNetProfileId = result.customerProfileId;
  443.                     db.CustomerProfiles.Add(customerProfile);
  444.                     db.SaveChanges();
  445.                     return true;
  446.                 default:
  447.                     modelState.AddModelError("",
  448.                                              "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!");
  449.                     return false;
  450.             }
  451.         }
  452.  
  453.         public static bool CreateCustomerPaymentProfile
  454.             (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerPaymentProfileType paymentProfile)
  455.         {
  456.             if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, paymentProfile.billTo))
  457.                 return false;
  458.  
  459.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  460.  
  461.             CreateCustomerPaymentProfileResponseType result = Service.CreateCustomerPaymentProfile(merchantAuthentication,
  462.                                                                                                    customerProfile
  463.                                                                                                        .AuthNetProfileId,
  464.                                                                                                    paymentProfile,
  465.                                                                                                    ValidationModeEnum.liveMode);
  466.  
  467.             modelState.AddModelError("", string.Format("Validation Response: {0}", result.validationDirectResponse));
  468.  
  469.             switch (result.resultCode)
  470.             {
  471.                 case MessageTypeEnum.Error:
  472.                     foreach (MessagesTypeMessage message in result.messages)
  473.                     {
  474.                         switch (message.code)
  475.                         {
  476.                             case "E00039":
  477.                                 // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
  478.                                 //customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
  479.                                 //db.CustomerProfiles.Add(customerProfile);
  480.                                 //db.SaveChanges();
  481.                                 return true;
  482.                             default:
  483.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  484.                                 break;
  485.                         }
  486.                     }
  487.                     return false;
  488.                 case MessageTypeEnum.Ok:
  489.                     // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
  490.                     //customerProfile.AuthNetProfileId = result.customerProfileId;
  491.                     //db.CustomerProfiles.Add(customerProfile);
  492.                     //db.SaveChanges();
  493.                     return true;
  494.                 default:
  495.                     modelState.AddModelError("",
  496.                                              "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!");
  497.                     return false;
  498.             }
  499.         }
  500.  
  501.         public static bool CreateCustomerShippingAddress
  502.             (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerAddressType addressInfo)
  503.         {
  504.             if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, addressInfo))
  505.                 return false;
  506.  
  507.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  508.  
  509.             CreateCustomerShippingAddressResponseType result = Service.CreateCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, addressInfo);
  510.  
  511.             switch (result.resultCode)
  512.             {
  513.                 case MessageTypeEnum.Error:
  514.                     foreach (MessagesTypeMessage message in result.messages)
  515.                     {
  516.                         switch (message.code)
  517.                         {
  518.                             case "E00039":
  519.                                 // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
  520.                                 //customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
  521.                                 //db.CustomerProfiles.Add(customerProfile);
  522.                                 //db.SaveChanges();
  523.                                 return true;
  524.                             default:
  525.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  526.                                 break;
  527.                         }
  528.                     }
  529.                     return false;
  530.                 case MessageTypeEnum.Ok:
  531.                     // TODO: Add the Tables for the CustomerPaymentProfile, CustomerShippingAddress and CustomerProfileTransaction records, then adjust this code to add the ID and link it appropriately!
  532.                     //customerProfile.AuthNetProfileId = result.customerProfileId;
  533.                     //db.CustomerProfiles.Add(customerProfile);
  534.                     //db.SaveChanges();
  535.                     return true;
  536.                 default:
  537.                     modelState.AddModelError("",
  538.                                              "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!");
  539.                     return false;
  540.             }
  541.         }
  542.  
  543.         // TODO: CODE THE CUSTOMER PROFILE TRANSACTION SECTION AFTER CODING THE CART TABLES
  544.         public static CreateCustomerProfileTransactionResponseType CreateCustomerProfileTransaction()
  545.         {
  546.             throw new NotImplementedException("Creating customer profile transactions has not been implemented yet.");
  547.         }
  548.         #endregion
  549.  
  550.         #region Delete Methods
  551.         public static bool DeleteCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
  552.         {
  553.             if (!ValidateProfile(modelState, customerProfile))
  554.                 return false;
  555.  
  556.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  557.  
  558.             DeleteCustomerProfileResponseType result = Service.DeleteCustomerProfile(merchantAuthentication,
  559.                                                                                      customerProfile.AuthNetProfileId);
  560.  
  561.             switch (result.resultCode)
  562.             {
  563.                 case MessageTypeEnum.Error:
  564.                     foreach (MessagesTypeMessage message in result.messages)
  565.                     {
  566.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  567.                     }
  568.                     return false;
  569.                 case MessageTypeEnum.Ok:
  570.                     return true;
  571.                 default:
  572.                     modelState.AddModelError("",
  573.                                              "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!");
  574.                     return false;
  575.             }
  576.         }
  577.         public static bool DeleteCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId)
  578.         {
  579.             if (!ValidateProfile(modelState, customerProfile) || !(billingId > 0))
  580.                 return false;
  581.  
  582.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  583.  
  584.             DeleteCustomerPaymentProfileResponseType result = Service.DeleteCustomerPaymentProfile(merchantAuthentication,
  585.                                                                                      customerProfile.AuthNetProfileId, billingId);
  586.  
  587.             switch (result.resultCode)
  588.             {
  589.                 case MessageTypeEnum.Error:
  590.                     foreach (MessagesTypeMessage message in result.messages)
  591.                     {
  592.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  593.                     }
  594.                     return false;
  595.                 case MessageTypeEnum.Ok:
  596.                     return true;
  597.                 default:
  598.                     modelState.AddModelError("",
  599.                                              "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!");
  600.                     return false;
  601.             }
  602.         }
  603.         public static bool DeleteCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, long shippingId)
  604.         {
  605.             if (!ValidateProfile(modelState, customerProfile) || !(shippingId > 0))
  606.                 return false;
  607.  
  608.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  609.  
  610.             DeleteCustomerShippingAddressResponseType result = Service.DeleteCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, shippingId);
  611.  
  612.             switch (result.resultCode)
  613.             {
  614.                 case MessageTypeEnum.Error:
  615.                     foreach (MessagesTypeMessage message in result.messages)
  616.                     {
  617.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  618.                     }
  619.                     return false;
  620.                 case MessageTypeEnum.Ok:
  621.                     return true;
  622.                 default:
  623.                     modelState.AddModelError("",
  624.                                              "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!");
  625.                     return false;
  626.             }
  627.         }
  628.         #endregion
  629.  
  630.         #region Update Methods
  631.         public static bool UpdateCustomerProfile(ModelStateDictionary modelState, CustomerProfile customerProfile)
  632.         {
  633.  
  634.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  635.  
  636.             CustomerProfileExType customerProfileType = new CustomerProfileExType
  637.             {
  638.                 customerProfileId = customerProfile.AuthNetProfileId,
  639.                 email = customerProfile.UserProfile.EmailAddress,
  640.                 merchantCustomerId =
  641.                     customerProfile.UserId.ToString(CultureInfo.InvariantCulture),
  642.                 description = customerProfile.Description
  643.             };
  644.  
  645.             UpdateCustomerProfileResponseType result = Service.UpdateCustomerProfile(merchantAuthentication, customerProfileType);
  646.  
  647.             switch (result.resultCode)
  648.             {
  649.                 case MessageTypeEnum.Error:
  650.                     foreach (MessagesTypeMessage message in result.messages)
  651.                     {
  652.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  653.                     }
  654.                     return false;
  655.                 case MessageTypeEnum.Ok:
  656.                     db.Entry(customerProfile).State = EntityState.Modified;
  657.                     db.SaveChanges();
  658.                     return true;
  659.                 default:
  660.                     modelState.AddModelError("",
  661.                                              "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!");
  662.                     return false;
  663.             }
  664.         }
  665.  
  666.         public static bool UpdateCustomerPaymentProfile
  667.             (ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerPaymentProfileExType paymentProfile)
  668.         {
  669.             if (!ValidateProfile(modelState, customerProfile))
  670.                 return false;
  671.  
  672.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  673.  
  674.             CreateCustomerPaymentProfileResponseType result = Service.CreateCustomerPaymentProfile(merchantAuthentication,
  675.                                                                                                    customerProfile
  676.                                                                                                        .AuthNetProfileId,
  677.                                                                                                    paymentProfile,
  678.                                                                                                    ValidationModeEnum.liveMode);
  679.  
  680.             modelState.AddModelError("", string.Format("Validation Response: {0}", result.validationDirectResponse));
  681.  
  682.             switch (result.resultCode)
  683.             {
  684.                 case MessageTypeEnum.Error:
  685.                     foreach (MessagesTypeMessage message in result.messages)
  686.                     {
  687.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  688.                     }
  689.                     return false;
  690.                 case MessageTypeEnum.Ok:
  691.                     return true;
  692.                 default:
  693.                     modelState.AddModelError("",
  694.                                              "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!");
  695.                     return false;
  696.             }
  697.         }
  698.  
  699.         public static bool UpdateCustomerShippingAddress(ModelStateDictionary modelState, CustomerProfile customerProfile, CustomerAddressExType addressInfo)
  700.         {
  701.             if (!ValidateProfile(modelState, customerProfile) || !ValidateAddress(modelState, addressInfo))
  702.                 return false;
  703.  
  704.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  705.  
  706.             UpdateCustomerShippingAddressResponseType result = Service.UpdateCustomerShippingAddress(merchantAuthentication, customerProfile.AuthNetProfileId, addressInfo);
  707.  
  708.             switch (result.resultCode)
  709.             {
  710.                 case MessageTypeEnum.Error:
  711.                     foreach (MessagesTypeMessage message in result.messages)
  712.                     {
  713.                         switch (message.code)
  714.                         {
  715.                             case "E00039":
  716.                                 return true;
  717.                             default:
  718.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  719.                                 break;
  720.                         }
  721.                     }
  722.                     return false;
  723.                 case MessageTypeEnum.Ok:
  724.                     return true;
  725.                 default:
  726.                     modelState.AddModelError("",
  727.                                              "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!");
  728.                     return false;
  729.             }
  730.         }
  731.  
  732.         public static UpdateSplitTenderGroupResponseType UpdateSplitTenderGroup()
  733.         {
  734.             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.");
  735.         }
  736.         #endregion
  737.  
  738.         #region Subscription Methods
  739.         public static bool CreateSubscription(ModelStateDictionary modelState, long profileId, Subscription sub, ARBSubscriptionType subscription)
  740.         {
  741.             CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
  742.             if (customerProfile == null)
  743.             {
  744.                 modelState.AddModelError("", "Could not retrieve customer profile. Unable to create subscription!");
  745.                 return false;
  746.             }
  747.  
  748.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  749.  
  750.             ARBCreateSubscriptionResponseType result = Service.ARBCreateSubscription(merchantAuthentication, subscription);
  751.  
  752.             switch (result.resultCode)
  753.             {
  754.                 case MessageTypeEnum.Error:
  755.                     foreach (MessagesTypeMessage message in result.messages)
  756.                     {
  757.                         switch (message.code)
  758.                         {
  759.                             case "E00012":
  760.                                 if (!db.CustomerSubscriptions.Any(s => s.UserId == customerProfile.UserId && s.SubscriptionId == sub.SubscriptionId))
  761.                                 {
  762.                                     CustomerSubscription customerSubscription = new CustomerSubscription
  763.                                     {
  764.                                         UserId = customerProfile.UserId,
  765.                                         SubscriptionId = sub.SubscriptionId,
  766.                                         AuthNetSubscriptionId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\.\s").Groups["ID"].Value),
  767.                                         StartDate =
  768.                                             subscription.paymentSchedule.startDate
  769.                                     };
  770.                                     db.CustomerSubscriptions.Add(customerSubscription);
  771.                                 }
  772.                                 else
  773.                                 {
  774.                                     var oldSub =
  775.                                         db.CustomerSubscriptions.OrderByDescending(o => o.StartDate).First(
  776.                                             s =>
  777.                                             s.UserId == customerProfile.UserId && s.SubscriptionId == sub.SubscriptionId);
  778.                                     oldSub.AuthNetSubscriptionId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\.\s").Groups["ID"].Value);
  779.                                     db.Entry(oldSub).State = EntityState.Modified;
  780.                                 }
  781.                                 db.SaveChanges();
  782.                                 return true;
  783.                             default:
  784.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  785.                                 break;
  786.                         }
  787.                     }
  788.                     return false;
  789.                 case MessageTypeEnum.Ok:
  790.                     CustomerSubscription customerSub = new CustomerSubscription
  791.                                                                     {
  792.                                                                         UserId = customerProfile.UserId,
  793.                                                                         CustomerProfileId = customerProfile.CustomerProfileId,
  794.                                                                         SubscriptionId = sub.SubscriptionId,
  795.                                                                         AuthNetSubscriptionId = result.subscriptionId,
  796.                                                                         StartDate =
  797.                                                                             subscription.paymentSchedule.startDate
  798.                                                                     };
  799.                     db.CustomerSubscriptions.Add(customerSub);
  800.                     db.SaveChanges();
  801.                     return true;
  802.                 default:
  803.                     modelState.AddModelError("",
  804.                                              "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!");
  805.                     return false;
  806.             }
  807.         }
  808.  
  809.         public static bool UpdateSubscription(ModelStateDictionary modelState, long profileId, long subscriptionId, ARBSubscriptionType subscription)
  810.         {
  811.             CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
  812.             if (customerProfile == null)
  813.             {
  814.                 modelState.AddModelError("", "Could not retrieve customer profile. Unable to update subscription!");
  815.                 return false;
  816.             }
  817.  
  818.             if (!ValidateProfile(modelState, customerProfile) || !(profileId > 0) || !(subscriptionId > 0))
  819.                 return false;
  820.  
  821.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  822.  
  823.             ARBUpdateSubscriptionResponseType result = Service.ARBUpdateSubscription(merchantAuthentication, subscriptionId, subscription);
  824.  
  825.             switch (result.resultCode)
  826.             {
  827.                 case MessageTypeEnum.Error:
  828.                     foreach (MessagesTypeMessage message in result.messages)
  829.                     {
  830.                         switch (message.code)
  831.                         {
  832.                             //case "E00039":
  833.                             //  customerProfile.AuthNetProfileId = long.Parse(Regex.Match(message.text, @"\s(?<ID>\d*)\s").Groups["ID"].Value);
  834.                             //  if (!db.CustomerProfiles.Any(c => c.AuthNetProfileId == customerProfile.AuthNetProfileId))
  835.                             //  {
  836.                             //      db.CustomerProfiles.Add(customerProfile);
  837.                             //      db.SaveChanges();
  838.                             //  }
  839.                             //  return true;
  840.                             default:
  841.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  842.                                 break;
  843.                         }
  844.                     }
  845.                     return false;
  846.                 case MessageTypeEnum.Ok:
  847.                     return true;
  848.                 default:
  849.                     modelState.AddModelError("",
  850.                                              "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!");
  851.                     return false;
  852.             }
  853.         }
  854.        
  855.         public static bool CancelSubscription(ModelStateDictionary modelState, long profileId, long subscriptionId)
  856.         {
  857.             CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
  858.             if (customerProfile == null)
  859.             {
  860.                 modelState.AddModelError("", "Could not retrieve customer profile. Unable to delete subscription!");
  861.                 return false;
  862.             }
  863.  
  864.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  865.  
  866.             ARBCancelSubscriptionResponseType result = Service.ARBCancelSubscription(merchantAuthentication, subscriptionId);
  867.  
  868.             switch (result.resultCode)
  869.             {
  870.                 case MessageTypeEnum.Error:
  871.                     foreach (MessagesTypeMessage message in result.messages)
  872.                     {
  873.                         switch (message.code)
  874.                         {
  875.                             default:
  876.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  877.                                 break;
  878.                         }
  879.                     }
  880.                     return false;
  881.                 case MessageTypeEnum.Ok:
  882.                     return true;
  883.                 default:
  884.                     modelState.AddModelError("",
  885.                                              "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!");
  886.                     return false;
  887.             }
  888.         }
  889.        
  890.         public static bool GetSubscriptionStatus(ModelStateDictionary modelState, long profileId, long subscriptionId)
  891.         {
  892.             CustomerProfile customerProfile = db.CustomerProfiles.Find(profileId);
  893.             if (customerProfile == null)
  894.             {
  895.                 modelState.AddModelError("", "Could not retrieve customer profile. Unable to retrieve subscription status!");
  896.                 return false;
  897.             }
  898.  
  899.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  900.  
  901.             ARBGetSubscriptionStatusResponseType result = Service.ARBGetSubscriptionStatus(merchantAuthentication, subscriptionId);
  902.  
  903.             switch (result.resultCode)
  904.             {
  905.                 case MessageTypeEnum.Error:
  906.                     foreach (MessagesTypeMessage message in result.messages)
  907.                     {
  908.                         switch (message.code)
  909.                         {
  910.                             default:
  911.                                 modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  912.                                 break;
  913.                         }
  914.                     }
  915.                     return false;
  916.                 case MessageTypeEnum.Ok:
  917.                     switch (result.status)
  918.                     {
  919.                         case ARBSubscriptionStatusEnum.active:
  920.                             return true;
  921.                         case ARBSubscriptionStatusEnum.canceled:
  922.                             return false;
  923.                         case ARBSubscriptionStatusEnum.expired:
  924.                             return false;
  925.                         case ARBSubscriptionStatusEnum.suspended:
  926.                             return false;
  927.                         case ARBSubscriptionStatusEnum.terminated:
  928.                             return false;
  929.                         default:
  930.                             modelState.AddModelError("", string.Format("The Subscription Status of {0} was not handled properly by the application and is inactive.", result.status));
  931.                             return false;
  932.                     }
  933.                 default:
  934.                     modelState.AddModelError("",
  935.                                              "An unknown error has occurred. If you continue to see this error, please contact an administrator!");
  936.                     return false;
  937.             }
  938.         }
  939.         #endregion
  940.  
  941.         #region Validation Methods
  942.         public static bool ValidateCustomerPaymentProfile(ModelStateDictionary modelState, CustomerProfile customerProfile, long billingId, long shippingId, string cardCode = null)
  943.         {
  944.             if (!ValidateProfile(modelState, customerProfile) || !(billingId > 0))
  945.                 return false;
  946.  
  947.             MerchantAuthenticationType merchantAuthentication = GetMerchantAuthentication(customerProfile);
  948.  
  949.             ValidateCustomerPaymentProfileResponseType result = Service.ValidateCustomerPaymentProfile(merchantAuthentication, customerProfile.AuthNetProfileId, billingId, shippingId, cardCode, ValidationModeEnum.liveMode);
  950.  
  951.             modelState.AddModelError("", string.Format("Validation Response: {0}", result.directResponse));
  952.  
  953.             switch (result.resultCode)
  954.             {
  955.                 case MessageTypeEnum.Error:
  956.                     foreach (MessagesTypeMessage message in result.messages)
  957.                     {
  958.                         modelState.AddModelError("", string.Format("Code {0}: {1}", message.code, message.text));
  959.                     }
  960.                     return false;
  961.                 case MessageTypeEnum.Ok:
  962.                     return true;
  963.                 default:
  964.                     modelState.AddModelError("",
  965.                                              "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!");
  966.                     return false;
  967.             }
  968.         }
  969.         #endregion
  970.     }
  971. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement