private static void SetSubscriptionCreditCardInformation(ISubscriptionRequest subscriptionRequest, CreditCard creditCard) { subscriptionRequest.CardCode = creditCard.CVV; subscriptionRequest.CardExpirationMonth = creditCard.ExpirationMonth; subscriptionRequest.CardExpirationYear = creditCard.ExpirationYear; subscriptionRequest.CardNumber = creditCard.Number; }
public void UpdateSubscriptionTest() { //check login / password string sError = CheckLoginPassword(); Assert.IsTrue(sError == "", sError); string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBUpdateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages></ARBUpdateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; SubscriptionGateway target = new SubscriptionGateway(ApiLogin, TransactionKey); ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Update Subscription Test", (decimal)1.32, 12); subscription.SubscriptionID = "2010573"; bool actual = false; // if choose "USELOCAL", the test should pass with no exception // Otherwise, the test might fail for error, i.e. duplicated request. try { actual = target.UpdateSubscription(subscription); } catch (Exception e) { string s = e.Message; } Assert.IsTrue(actual); }
public void AuthorizeNet_ARBCallTest() { var target = new SubscriptionGateway("77pmw32Vh7LS", "73629XQgg28GW2tp", ServiceMode.Test); ISubscriptionRequest subscription = SubscriptionRequest .CreateMonthly("*****@*****.**", "ARB Test" + Guid.NewGuid(), (decimal)5.60, 12); subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 1; subscription.CardExpirationYear = 20; var billToAddress = new Address(); billToAddress.First = "John"; billToAddress.Last = "Doe"; subscription.BillingAddress = billToAddress; ISubscriptionRequest actual = null; try { actual = target.CreateSubscription(subscription); } catch (Exception e) { var s = e.Message; Console.WriteLine("Failed to create SUB: " + e); } }
private static void SetSubscriptionBasics(ISubscriptionRequest subscriptionRequest, SubscriptionType subscriptionType) { subscriptionRequest.StartsOn = DateTime.UtcNow; subscriptionRequest.Amount = subscriptionType.Price; subscriptionRequest.SubscriptionName = subscriptionType.SubscriptionFrequency.Name + " Membership"; // Subscription interval if (subscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Monthly) { subscriptionRequest.BillingInterval = 1; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Months; } else if (subscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Quarterly) { subscriptionRequest.BillingInterval = 365 / 4; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Days; } else if (subscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Yearly) { subscriptionRequest.BillingInterval = 365; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Days; } else { // TODO: Log Error! We should never hit this case. } }
public void CreateSubscriptionTest_zeroTrial() { var random = new AnetRandom(); var counter = random.Next(1, (int)(Math.Pow(2, 24))); var amount = ComputeRandomAmount(); var email = string.Format("user.{0}@authorize.net", counter); const string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBCreateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><subscriptionId>2074569</subscriptionId></ARBCreateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; var target = new SubscriptionGateway(ApiLogin, TransactionKey); var billToAddress = new Address { First = "SomeOneCool", Last = "MoreCoolPerson" }; ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly(email, "ARB Subscription Test", amount, 10); subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 3; subscription.CardExpirationYear = 16; subscription.BillingAddress = billToAddress; //setting Trial amount/ Trial Ocurances to 0 subscription.SetTrialPeriod(3, 0M); ISubscriptionRequest actual = null; actual = target.CreateSubscription(subscription); Assert.NotNull(actual); }
/// <summary> /// Updates the subscription. /// </summary> /// <param name="subscription">The subscription to update. Can't change billing intervals however.</param> /// <returns></returns> public bool UpdateSubscription(ISubscriptionRequest subscription) { var sub = subscription.ToUpdateableAPI(); var req = new ARBUpdateSubscriptionRequest(); req.subscription = sub; req.subscriptionId = subscription.SubscriptionID; var response = (ARBUpdateSubscriptionResponse)_gateway.Send(req); return true; }
/// <summary> /// Creates a new subscription /// </summary> /// <param name="subscription">The subscription to create - requires that you add a credit card and billing first and last.</param> public ISubscriptionRequest CreateSubscription(ISubscriptionRequest subscription) { var sub = subscription.ToAPI(); var req = new ARBCreateSubscriptionRequest(); req.subscription = sub; var response = (ARBCreateSubscriptionResponse)_gateway.Send(req); subscription.SubscriptionID = response.subscriptionId; return subscription; }
public ActionResult Subscribe(SubscriptionRegistration registrationInformation) { registrationInformation.AvailableSubscriptionTypes = _database.SubscriptionTypes.Include(st => st.SubscriptionFrequency).Where(st => st.IsAvailableToUsers && !st.IsAddOn); registrationInformation.Countries = _database.Countries.AsEnumerable(); if (registrationInformation.SelectedSubscriptionTypeId == 0) { ModelState.AddModelError(string.Empty, "Please choose a subscription to continue."); } // If all credit card information has been supplied, then try to validate the request with Authorize.NET if (ModelState.IsValid) { ISubscriptionGateway gateway = GetSubscriptionGateway(); ISubscriptionRequest subscriptionRequest = MembersController.CreateAuthorizeDotNetSubscriptionRequest(registrationInformation); ISubscriptionRequest subscriptionResponse = null; try { subscriptionResponse = gateway.CreateSubscription(subscriptionRequest); } catch (InvalidOperationException exception) { ModelState.AddModelError(string.Empty, exception.Message); return(View(registrationInformation)); } // If we reach this part of the code, we have successfully scheduled a subscription, make a note of it in our system WebSite.Models.User currentUser = Authentication.GetCurrentUser(); DatabaseContext db = _database; // Encrypt the credit card information of the user registrationInformation.CreditCard.Encrypt(); // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = registrationInformation.SelectedSubscriptionTypeId, CreditCard = registrationInformation.CreditCard }; // Associate the subscription with the user currentUser.AddSubscription(userSubscription); db.SaveChanges(); return(this.RedirectToAction("Index")); } return(View(registrationInformation)); }
public ActionResult AddAutoTrading(AddonRegistration registrationInformation) { if (ModelState.IsValid) { SubscriptionType autoTradingAddOn = _database.SubscriptionTypes.Include(st => st.SubscriptionFrequency).Where(st => st.IsAvailableToUsers && st.IsAddOn).FirstOrDefault(); if (autoTradingAddOn != null) { ISubscriptionGateway gateway = GetSubscriptionGateway(); ISubscriptionRequest subscriptionRequest = MembersController.CreateAuthorizeDotNetSubscriptionRequest(registrationInformation.CreditCard, autoTradingAddOn); ISubscriptionRequest subscriptionResponse = null; try { subscriptionResponse = gateway.CreateSubscription(subscriptionRequest); } catch (InvalidOperationException exception) { ModelState.AddModelError(string.Empty, exception.Message); return(View(registrationInformation)); } // If the code reaches here then the payment went through WebSite.Models.User currentUser = Authentication.GetCurrentUser(); // Encrypt the credit card information of the user registrationInformation.CreditCard.Encrypt(); // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = autoTradingAddOn.SubscriptionTypeId, CreditCard = registrationInformation.CreditCard }; // Associate the subscription with the user currentUser.AddAddOnSubscription(userSubscription); _database.SaveChanges(); return(this.RedirectToAction("Index")); } else { this.ModelState.AddModelError(string.Empty, "Can't locate auto-trading add-on in server"); } } return(View(registrationInformation)); }
public ActionResult Subscribe(SubscriptionRegistration registrationInformation, int userId, int day, int month, int year) { ViewBag.UserId = userId; registrationInformation.AvailableSubscriptionTypes = _db.SubscriptionTypes.Include(o => o.SubscriptionFrequency); registrationInformation.Countries = _db.Countries.AsEnumerable(); if (registrationInformation.SelectedSubscriptionTypeId == 0) { ModelState.AddModelError(string.Empty, "Please choose a subscription to continue."); } // If all credit card information has been supplied, then try to validate the request with Authorize.NET if (ModelState.IsValid) { WebSite.Models.User user = _db.Users.Find(userId); ISubscriptionGateway gateway = this.GetSubscriptionGateway(); ISubscriptionRequest subscriptionRequest = this.CreateAuthorizeDotNetSubscriptionRequest(registrationInformation, user, new DateTime(year, month, day)); ISubscriptionRequest subscriptionResponse = null; try { subscriptionResponse = gateway.CreateSubscription(subscriptionRequest); } catch (InvalidOperationException exception) { ModelState.AddModelError(string.Empty, exception.Message); return(View(registrationInformation)); } // Encrypt the credit card information of the user registrationInformation.CreditCard.Encrypt(); // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = registrationInformation.SelectedSubscriptionTypeId, CreditCard = registrationInformation.CreditCard }; // Associate the subscription with the user user.AddSubscription(userSubscription); _db.SaveChanges(); return(this.RedirectToAction("Index")); } return(View(registrationInformation)); }
public ActionResult UpdateSubscription(CreditCard newCreditCard) { if (ModelState.IsValid) { User currentUser = Authentication.GetCurrentUserEagerlyLoaded(); // Create a new subscription with the old settings ISubscriptionRequest subscriptionRequest = CreateAuthorizeDotNetSubscriptionRequest(newCreditCard, currentUser.Subscription.SubscriptionType); ISubscriptionRequest subscriptionResponse = null; ISubscriptionGateway subscriptionGateway = GetSubscriptionGateway(); try { // Add the new subscription now subscriptionResponse = subscriptionGateway.CreateSubscription(subscriptionRequest); // Cancel the current subscription subscriptionGateway.CancelSubscription(currentUser.Subscription.AuthorizeNETSubscriptionId); // Subscription was updated successfully // Encrypt the card's number newCreditCard.Encrypt(); DatabaseContext db = _database; // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = currentUser.Subscription.SubscriptionTypeId, CreditCard = newCreditCard }; // Associate the subscription with the user currentUser.AddSubscription(userSubscription); db.SaveChanges(); return(this.RedirectToAction("Index")); } catch (Exception exception) { ModelState.AddModelError(string.Empty, exception.Message); } } ViewBag.Countries = _database.Countries; return(this.View()); }
public void CreateSubscriptionTest_eCheck() { //check login / password string sError = CheckLoginPassword(); Assert.IsTrue(sError == "", sError); string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBCreateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><subscriptionId>2074569</subscriptionId></ARBCreateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; SubscriptionGateway target = new SubscriptionGateway(ApiLogin, TransactionKey); ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Subscription Test eCheck", (decimal)1.31, 12); subscription.eCheckBankAccount = new BankAccount() { accountTypeSpecified = true, accountType = BankAccountType.Checking, routingNumber = "125000024", accountNumber = "123456", nameOnAccount = "Sue Zhu", echeckTypeSpecified = true, echeckType = EcheckType.WEB }; Address billToAddress = new Address(); billToAddress.First = "Sue"; billToAddress.Last = "Zhu"; subscription.BillingAddress = billToAddress; ISubscriptionRequest actual = null; // if choose "USELOCAL", the test should pass with no exception // Otherwise, the test might fail for error, i.e. duplicated request. try { actual = target.CreateSubscription(subscription); } catch (Exception e) { string s = e.Message; } Assert.AreEqual(subscription.Amount, actual.Amount); Assert.AreEqual(subscription.eCheckBankAccount.accountNumber, actual.eCheckBankAccount.accountNumber); Assert.AreEqual(subscription.SubscriptionName, actual.SubscriptionName); Assert.IsTrue(actual.SubscriptionID.Trim().Length > 0); Assert.IsTrue(long.Parse(actual.SubscriptionID) == 2074569); }
/// <summary> /// Updates the subscription. /// </summary> /// <param name="subscription">The subscription to update. Can't change billing intervals however.</param> /// <returns></returns> public bool UpdateSubscription(ISubscriptionRequest subscription) { var sub = subscription.ToUpdateableAPI(); var req = new ARBUpdateSubscriptionRequest(); req.subscription = sub; req.subscriptionId = subscription.SubscriptionID; var response = (ARBUpdateSubscriptionResponse)_gateway.Send(req); return(true); }
/// <summary> /// Creates a new subscription /// </summary> /// <param name="subscription">The subscription to create - requires that you add a credit card and billing first and last.</param> public ISubscriptionRequest CreateSubscription(ISubscriptionRequest subscription) { var sub = subscription.ToAPI(); var req = new ARBCreateSubscriptionRequest(); req.subscription = sub; var response = (ARBCreateSubscriptionResponse)_gateway.Send(req); subscription.SubscriptionID = response.subscriptionId; return(subscription); }
public void UpdateSubscriptionTest() { ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Update Subscription Test", _mAmount, 12); subscription.SubscriptionID = _sMonthlySubscriptionId; bool actual = _mTarget.UpdateSubscription(subscription); Assert.IsTrue(actual); }
public void UpdateSubscriptionTest_Description_Invoice() { ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Update Subscription Test Descriptn and Invoice", _mAmount, 12); subscription.SubscriptionID = _sMonthlySubscriptionId; subscription.Invoice = "INV12345"; subscription.Description = "update Description and Invoice"; bool actual = _mTarget.UpdateSubscription(subscription); Assert.IsTrue(actual); }
public void CreateSubscriptionTest() { var random = new Random(); var counter = random.Next(1, (int)(Math.Pow(2, 24))); const int maxSubscriptionAmount = 1000; //214747; var amount = new decimal(counter > maxSubscriptionAmount ? (counter % maxSubscriptionAmount) : counter); var email = string.Format("user.{0}@authorize.net", counter); //check login / password var sError = CheckLoginPassword(); Assert.IsTrue(sError == "", sError); string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBCreateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><subscriptionId>2010573</subscriptionId></ARBCreateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; var target = new SubscriptionGateway(ApiLogin, TransactionKey); var billToAddress = new Address { First = "SomeOneCool", Last = "MoreCoolPerson" }; ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly(email, "ARB Subscription Test", amount, 1); subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 3; subscription.CardExpirationYear = 16; subscription.BillingAddress = billToAddress; ISubscriptionRequest actual = null; try { actual = target.CreateSubscription(subscription); } catch (Exception e) { string s = e.Message; Assert.Fail("Exception in processing"); } Assert.NotNull(actual); Assert.AreEqual(subscription.Amount, actual.Amount); Assert.AreEqual(subscription.CardNumber, actual.CardNumber); Assert.AreEqual(subscription.SubscriptionName, actual.SubscriptionName); Assert.IsTrue(0 < actual.SubscriptionID.Trim().Length); Assert.IsTrue(0 < Int64.Parse(actual.SubscriptionID)); }
public void UpdateSubscriptionTest_SingleDigitMonth() { ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Update Subscription Test", _mAmount, 12); subscription.SubscriptionID = _sMonthlySubscriptionId; subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 4; subscription.CardExpirationYear = 16; bool actual = _mTarget.UpdateSubscription(subscription); Assert.IsTrue(actual); }
public void UpdateSubscriptionTest_SingleDigitMonth() { ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Update Subscription Test", _mAmount, 12); subscription.SubscriptionID = _sMonthlySubscriptionId; subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 4; subscription.CardExpirationYear = Convert.ToInt32(DateTime.Now.AddYears(3).ToString("yyyy")); bool actual = _mTarget.UpdateSubscription(subscription); Assert.IsTrue(actual); }
private static void SetSubscriptionBillingAddress(ISubscriptionRequest subscriptionRequest, CreditCard creditCard, string countryName) { subscriptionRequest.BillingAddress = new AuthorizeNet.Address() { City = creditCard.BillingAddress.City, Country = countryName, First = creditCard.CardholderFirstName, Last = creditCard.CardholderLastName, Phone = creditCard.BillingAddress.PhoneNumber, State = creditCard.BillingAddress.ProvinceOrState, Street = creditCard.BillingAddress.AddressLine1 + (!string.IsNullOrEmpty(creditCard.BillingAddress.AddressLine2) ? (Environment.NewLine + creditCard.BillingAddress.AddressLine2) : string.Empty) , Zip = creditCard.BillingAddress.PostalCode }; }
public static ISubscriptionRequest CreateAuthorizeDotNetSubscriptionRequest(CreditCard creditCard, SubscriptionType subscriptionType, WebSite.Models.User user) { ISubscriptionRequest request = SubscriptionRequest.CreateNew(); // Billing address information DatabaseContext db = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(DatabaseContext)) as DatabaseContext; string countryName = db.Countries.Find(creditCard.BillingAddress.CountryId).Name; SetSubscriptionBillingAddress(request, creditCard, countryName); // Subscription information SetSubscriptionBasics(request, subscriptionType); // Credit card information SetSubscriptionCreditCardInformation(request, creditCard); // Customer information request.CustomerEmail = user.EmailAddress; request.CustomerID = user.UserId.ToString(); return(request); }
public void CreateSubscription() { var random = new AnetRandom(); var counter = random.Next(1, (int)(Math.Pow(2, 24))); var amount = ComputeRandomAmount(); var email = string.Format("user.{0}@authorize.net", counter); //check ApiLoginid / TransactionKey var sError = CheckApiLoginTransactionKey(); Assert.IsTrue(sError == "", sError); const string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBCreateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><subscriptionId>2010573</subscriptionId></ARBCreateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; var target = new SubscriptionGateway(ApiLogin, TransactionKey); var billToAddress = new Address { First = "SomeOneCool", Last = "MoreCoolPerson" }; ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly(email, "ARB Subscription Test", amount, 1); subscription.CardNumber = "4111111111111111"; subscription.CardExpirationMonth = 3; subscription.CardExpirationYear = 16; subscription.BillingAddress = billToAddress; ISubscriptionRequest actual = target.CreateSubscription(subscription); Assert.NotNull(actual); Assert.AreEqual(subscription.Amount, actual.Amount); Assert.AreEqual(subscription.CardNumber, actual.CardNumber); Assert.AreEqual(subscription.SubscriptionName, actual.SubscriptionName); _sMonthlySubscriptionId = actual.SubscriptionID; Assert.IsTrue(0 < _sMonthlySubscriptionId.Trim().Length); Assert.IsTrue(0 < long.Parse(_sMonthlySubscriptionId)); }
public void CreateSubscriptionTest_eCheck() { const string responseString = "<?xml version=\"1.0\" encoding=\"utf-8\"?><ARBCreateSubscriptionResponse xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\"><messages><resultCode>Ok</resultCode><message><code>I00001</code><text>Successful.</text></message></messages><subscriptionId>2074569</subscriptionId></ARBCreateSubscriptionResponse>"; LocalRequestObject.ResponseString = responseString; var target = new SubscriptionGateway(ApiLogin, TransactionKey); ISubscriptionRequest subscription = SubscriptionRequest.CreateMonthly("*****@*****.**", "ARB Subscription Test eCheck", _mAmount, 12); subscription.eCheckBankAccount = new BankAccount { accountTypeSpecified = true, accountType = BankAccountType.Checking, routingNumber = "125000024", accountNumber = "123456", nameOnAccount = "Sue Zhu", echeckTypeSpecified = true, echeckType = EcheckType.WEB }; var billToAddress = new Address { First = "Sue", Last = "Zhu" }; subscription.BillingAddress = billToAddress; ISubscriptionRequest actual = target.CreateSubscription(subscription); Assert.AreEqual(subscription.Amount, actual.Amount); Assert.AreEqual(subscription.eCheckBankAccount.accountNumber, actual.eCheckBankAccount.accountNumber); Assert.AreEqual(subscription.SubscriptionName, actual.SubscriptionName); Assert.IsTrue(actual.SubscriptionID.Trim().Length > 0); Assert.IsTrue(0 < long.Parse(actual.SubscriptionID)); }
public void Subscribe(ISubscriptionRequest subscriptionRequest, OnSuccess successCallback, OnFailure failureCallback) { Handler handler = (Handler) new DefaultHandler(); this.SendRequest((IRequest)subscriptionRequest, handler, (Session.OnSucessfulRequest)(() => successCallback()), failureCallback); }
/// <summary> /// Tries to enable the auto-trading add-on using an existing credit card from the user /// </summary> /// <returns></returns> private ActionResult TryAddingAutoTradingFromExistingCreditCard() { User currentUser = Authentication.GetCurrentUser(); CreditCard successfulCreditCard = null; foreach (CreditCard card in currentUser.CreditCards) { try { card.Decrypt(); } catch { continue; } successfulCreditCard = card; break; } // If we could not find any credit cards then bail if (successfulCreditCard == null) { return(null); } SubscriptionType autoTradingAddOn = _database.SubscriptionTypes.Include(st => st.SubscriptionFrequency).Where(st => st.IsAvailableToUsers && st.IsAddOn).FirstOrDefault(); if (autoTradingAddOn == null) { return(null); } ISubscriptionGateway gateway = GetSubscriptionGateway(); ISubscriptionRequest subscriptionRequest = MembersController.CreateAuthorizeDotNetSubscriptionRequest(successfulCreditCard, autoTradingAddOn); ISubscriptionRequest subscriptionResponse = null; try { subscriptionResponse = gateway.CreateSubscription(subscriptionRequest); } catch (InvalidOperationException) { return(null); } // Encrypt the credit card information of the user successfulCreditCard.Encrypt(); // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = autoTradingAddOn.SubscriptionTypeId, CreditCard = successfulCreditCard }; // Associate the subscription with the user currentUser.AddAddOnSubscription(userSubscription); _database.SaveChanges(); return(this.RedirectToAction("Index")); }
private ISubscriptionRequest CreateAuthorizeDotNetSubscriptionRequest(SubscriptionRegistration registrationInformation, WebSite.Models.User user, DateTime startsOn) { ISubscriptionRequest subscriptionRequest = SubscriptionRequest.CreateNew(); // Billing address information string countryName = _db.Countries.Find(registrationInformation.CreditCard.BillingAddress.CountryId).Name; subscriptionRequest.BillingAddress = new AuthorizeNet.Address() { City = registrationInformation.CreditCard.BillingAddress.City, Country = countryName, First = registrationInformation.CreditCard.CardholderFirstName, Last = registrationInformation.CreditCard.CardholderLastName, Phone = registrationInformation.CreditCard.BillingAddress.PhoneNumber, State = registrationInformation.CreditCard.BillingAddress.ProvinceOrState, Street = registrationInformation.CreditCard.BillingAddress.AddressLine1 + (!string.IsNullOrEmpty(registrationInformation.CreditCard.BillingAddress.AddressLine2) ? (Environment.NewLine + registrationInformation.CreditCard.BillingAddress.AddressLine2) : string.Empty) , Zip = registrationInformation.CreditCard.BillingAddress.PostalCode }; // Subscription information SubscriptionType selectedSubscriptionType = registrationInformation.AvailableSubscriptionTypes.First(st => st.SubscriptionTypeId == registrationInformation.SelectedSubscriptionTypeId); subscriptionRequest.StartsOn = startsOn; subscriptionRequest.Amount = selectedSubscriptionType.Price; subscriptionRequest.SubscriptionName = selectedSubscriptionType.SubscriptionFrequency.Name + " Membership"; // Subscription interval if (selectedSubscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Monthly) { subscriptionRequest.BillingInterval = 1; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Months; } else if (selectedSubscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Quarterly) { subscriptionRequest.BillingInterval = 365 / 4; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Days; } else if (selectedSubscriptionType.SubscriptionFrequency.Name == PredefinedSubscriptionFrequencies.Yearly) { subscriptionRequest.BillingInterval = 365; subscriptionRequest.BillingIntervalUnits = BillingIntervalUnits.Days; } else { // TODO: Log Error! We should never hit this case. } // Credit card information subscriptionRequest.CardCode = registrationInformation.CreditCard.CVV; subscriptionRequest.CardExpirationMonth = registrationInformation.CreditCard.ExpirationMonth; subscriptionRequest.CardExpirationYear = registrationInformation.CreditCard.ExpirationYear; subscriptionRequest.CardNumber = registrationInformation.CreditCard.Number; // Customer information subscriptionRequest.CustomerEmail = user.EmailAddress; subscriptionRequest.CustomerID = user.UserId.ToString(); return(subscriptionRequest); }
public void Subscribe(ISubscriptionRequest subscriptionRequest, OnSuccess successCallback, OnFailure failureCallback) { DefaultHandler handler = new DefaultHandler(); SendRequest(subscriptionRequest, handler, delegate() { successCallback(); }, failureCallback); }
public void PostBack() { // If the post back is about a recurring payment, it'll have a subscription ID field in the request if (string.IsNullOrEmpty(Request.Form["x_subscription_id"])) { return; } // We can't handle a request if there is no response code sent to us if (string.IsNullOrEmpty(Request.Form["x_response_code"])) { return; } // If the payment was successful, we don't really care to do anything if (string.CompareOrdinal(Request.Form["x_response_code"], "1") == 0) { return; } // For any other response code the payment has failed, we need to set the subscription of the user to suspended and send them an email // letting them know something is wrong string subscriptionId = Request.Form["x_subscription_id"]; DatabaseContext db = _database; // Load the subscription and figure out which user it belongs to Subscription subscription = db.Subscriptions.Include(s => s.CreditCard).FirstOrDefault(s => s.AuthorizeNETSubscriptionId == subscriptionId); // Could we successfully load the subscription Authorize.NET is talking about? if (subscription == null) { // TODO: Log Error return; } User affectedUser = (from user in db.Users.Include(u => u.Subscription) where user.SubscriptionId.HasValue && user.Subscription.SubscriptionId == subscription.SubscriptionId select user).FirstOrDefault(); // Could we locate a user with an active subscription? if (affectedUser == null) { // TODO: Log Error return; } bool successfulRenewal = false; // Mark the subscription as suspended subscription.IsSuspended = true; // Check to see whether the card is expired, if so, try to renew the subscription with a new year if (subscription.CreditCard.IsExpired()) { // Decrypt to get the card information again bool successfulDecryption = true; try { subscription.CreditCard.Decrypt(); } catch (Exception) { successfulDecryption = false; } if (successfulDecryption) { // Bump up the expiry by 2 years CreditCard newCard = new CreditCard() { AddressId = subscription.CreditCard.AddressId, BillingAddress = subscription.CreditCard.BillingAddress, CardholderFirstName = subscription.CreditCard.CardholderFirstName, CardholderLastName = subscription.CreditCard.CardholderLastName, CVV = subscription.CreditCard.CVV, ExpirationMonth = subscription.CreditCard.ExpirationMonth, ExpirationYear = (short)(subscription.CreditCard.ExpirationYear + 2), Number = subscription.CreditCard.Number }; ISubscriptionGateway gateway = MembersController.GetSubscriptionGateway(); ISubscriptionRequest subscriptionRequest = MembersController.CreateAuthorizeDotNetSubscriptionRequest(newCard, subscription.SubscriptionType, affectedUser); ISubscriptionRequest subscriptionResponse = null; bool successfulTry = true; try { subscriptionResponse = gateway.CreateSubscription(subscriptionRequest); } catch (InvalidOperationException) { // Payment failed again successfulTry = false; } successfulRenewal = successfulTry; if (successfulTry) { // Encrypt the credit card information of the user newCard.Encrypt(); // Construct a subscription for the user Subscription userSubscription = new Subscription() { ActivationDate = DateTime.UtcNow, AuthorizeNETSubscriptionId = subscriptionResponse.SubscriptionID, CancellationDate = null, SubscriptionTypeId = subscription.SubscriptionTypeId, CreditCard = newCard }; // Associate the new subscription with the user affectedUser.AddSubscription(userSubscription); } } } db.SaveChanges(); if (!successfulRenewal) { // If we could not automatically renew the payment, then notify the user EmailResult email = new WebSite.Mailers.Account().PaymentSuspendedEmail(affectedUser); WebSite.Helpers.Email.SendEmail(email, new List <Models.User>() { affectedUser }); } return; }