public JsonResult CancelRecurring(int? pid) { var ReturnCode = new TransactionReturnType() { StatusCode = (int)ErrorCodes.UnknownError, StatusMessage = String.Empty }; DateTime registDt = DateTime.Now; try { if (pid == null) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Request is not valid"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (!Request.IsAjaxRequest()) { ReturnCode.StatusCode = (int)ErrorCodes.IsInvalidRequest; ReturnCode.StatusMessage = "Request is not valid"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } if (User.Identity.IsAuthenticated) { var context = new IPTV2Entities(); var userId = new Guid(User.Identity.Name); var user = context.Users.FirstOrDefault(u => u.UserId == userId); if (user != null) { var product = context.Products.FirstOrDefault(p => p.ProductId == (int)pid); if (product != null) { if (product is SubscriptionProduct) { var subscription_product = (SubscriptionProduct)product; var packageIds = subscription_product.ProductGroup.GetPackageIds(true); var CurrencyCode = GlobalConfig.DefaultCurrency; try { CurrencyCode = user.Country.CurrencyCode; } catch (Exception) { } var rb = context.RecurringBillings.Where(r => r.UserId == user.UserId && r.StatusId == GlobalConfig.Visible && packageIds.Contains(r.PackageId)); if (rb != null) { if (rb.Count() > 0) { var gomsService = new GomsTfcTv(); foreach (var billing in rb) { string reference = String.Empty; bool serviceUpdateSuccess = false; string cancellation_remarks = String.Empty; if (billing is PaypalRecurringBilling) { try { var paypalrbilling = (PaypalRecurringBilling)billing; billing.StatusId = 0; billing.UpdatedOn = registDt; try { if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId)) { reference = String.Format("PayPal Payment Renewal id {0} cancelled", billing.RecurringBillingId); String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } } catch (Exception) { } } catch (Exception) { } } else { try { var result = gomsService.CancelRecurringPayment(user, billing.Product); if (result.IsSuccess) { billing.StatusId = 0; billing.UpdatedOn = registDt; reference = String.Format("Credit Card Payment Renewal {0} cancelled", billing.RecurringBillingId); cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } else { ReturnCode.StatusMessage = result.StatusMessage; throw new Exception(result.StatusMessage); } } catch (Exception) { } } //serviceUpdateSuccess = true; if (serviceUpdateSuccess) { var transaction = new CancellationTransaction() { Amount = 0, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, CancellationRemarks = cancellation_remarks, OriginalTransactionId = -1, GomsTransactionId = -1000, Date = registDt, Reference = reference, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } } if (context.SaveChanges() > 0) { ReturnCode.StatusCode = (int)ErrorCodes.Success; ReturnCode.StatusMessage = "We have disabled all your automatic payment renewal."; } } } } } } } else { ReturnCode.StatusCode = (int)ErrorCodes.NotAuthenticated; ReturnCode.StatusMessage = "User is not authenticated"; return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); } } catch (Exception e) { MyUtility.LogException(e); } return this.Json(ReturnCode, JsonRequestBehavior.AllowGet); }
private void UpdateRecurringBillingViaEditProfile2(IPTV2Entities context, User user, string list, bool? enable) { try { if (User.Identity.IsAuthenticated) { var rb_list = list.Replace("rs", ""); var billingIds = MyUtility.StringToIntList(rb_list); DateTime registDt = DateTime.Now; if (billingIds.Count() > 0) { var gomsService = new GomsTfcTv(); var recurring_billings = user.RecurringBillings.Where(r => billingIds.Contains(r.RecurringBillingId) && r.StatusId != 2); if (recurring_billings != null) { if (recurring_billings.Count() > 0) { bool RecurringStatus = false; if (enable != null) RecurringStatus = (bool)enable; var CurrencyCode = GlobalConfig.DefaultCurrency; try { CurrencyCode = user.Country.CurrencyCode; } catch (Exception) { } foreach (var billing in recurring_billings) { string cancellation_remarks = String.Empty; string reference = String.Empty; bool serviceUpdateSuccess = false; if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0) { //there is same package with recurring enabled. } else { if (billing is PaypalRecurringBilling) { try { var paypalrbilling = (PaypalRecurringBilling)billing; billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; if (registDt.Date > billing.NextRun && RecurringStatus) billing.NextRun = registDt.AddDays(1).Date; if (!RecurringStatus) { try { if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId)) { reference = String.Format("PayPal billing id {0} cancelled", billing.RecurringBillingId); cancellation_remarks = String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } } catch (Exception) { } } } catch (Exception) { } } else { billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; if (registDt.Date > billing.NextRun && RecurringStatus) billing.NextRun = registDt.AddDays(1).Date; if (!RecurringStatus) { try { var result = gomsService.CancelRecurringPayment(user, billing.Product); if (result.IsSuccess) { reference = String.Format("Credit Card billing id {0} cancelled", billing.RecurringBillingId); cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } else throw new Exception(result.StatusMessage); } catch (Exception e) { MyUtility.LogException(e); } } } if (!RecurringStatus && serviceUpdateSuccess) { var transaction = new CancellationTransaction() { Amount = 0, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, CancellationRemarks = cancellation_remarks, OriginalTransactionId = -1, GomsTransactionId = -1000, Date = registDt, Reference = reference, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } } } } } } } } catch (Exception e) { MyUtility.LogException(e); } }
private void UpdateRecurringBillingViaEditProfile(IPTV2Entities context, User user, string list, bool? enable) { try { DateTime registDt = DateTime.Now; var rb_list = list.Split(','); var gomsService = new GomsTfcTv(); if (rb_list.Count() > 0) { foreach (var item in rb_list) { if (!String.IsNullOrEmpty(item)) { var name = item; if (MyUtility.isUserLoggedIn()) { bool RecurringStatus = false; if (enable != null) RecurringStatus = (bool)enable; int RecurringBillingId = 0; try { RecurringBillingId = Convert.ToInt32(name.Substring(2)); } catch (Exception e) { MyUtility.LogException(e); } if (user != null) { var CurrencyCode = GlobalConfig.DefaultCurrency; try { CurrencyCode = user.Country.CurrencyCode; } catch (Exception) { } string cancellation_remarks = String.Empty; string reference = String.Empty; bool serviceUpdateSuccess = false; var billing = user.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == RecurringBillingId && r.StatusId != 2); if (billing != null) { //Check first if there is a same package with recurring turned on if (user.RecurringBillings.Count(r => r.PackageId == billing.PackageId && r.StatusId == GlobalConfig.Visible && r.RecurringBillingId != billing.RecurringBillingId) > 0) { //there is same package with recurring enabled. } else { if (billing is PaypalRecurringBilling) { try { var paypalrbilling = (PaypalRecurringBilling)billing; billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; if (registDt.Date > billing.NextRun && RecurringStatus) billing.NextRun = registDt.AddDays(1).Date; if (!RecurringStatus) { try { if (PaymentHelper.CancelPaypalRecurring(paypalrbilling.SubscriberId)) { reference = String.Format("PayPal Payment Renewal {0} cancelled", billing.RecurringBillingId); String.Format("{0} - PayPal Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } } catch (Exception) { } } } catch (Exception) { } } else { if (RecurringStatus) { billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; if (registDt.Date > billing.NextRun && RecurringStatus) billing.NextRun = registDt.AddDays(1).Date; } else //if (!RecurringStatus) { try { var result = gomsService.CancelRecurringPayment(user, billing.Product); if (result.IsSuccess) { billing.StatusId = RecurringStatus ? 1 : 0; billing.UpdatedOn = registDt; reference = String.Format("Credit Card Payment Renewal {0} cancelled", billing.RecurringBillingId); cancellation_remarks = String.Format("{0} - Credit Card Recurring Billing Id cancelled", billing.RecurringBillingId); serviceUpdateSuccess = true; } else throw new Exception(result.StatusMessage); } catch (Exception e) { MyUtility.LogException(e); } } } if (!RecurringStatus && serviceUpdateSuccess) { var transaction = new CancellationTransaction() { Amount = 0, Currency = CurrencyCode, OfferingId = GlobalConfig.offeringId, CancellationRemarks = cancellation_remarks, OriginalTransactionId = -1, GomsTransactionId = -1000, Date = registDt, Reference = reference, StatusId = GlobalConfig.Visible }; user.Transactions.Add(transaction); } } } } } } } } } catch (Exception e) { MyUtility.LogException(e); } }
private void Send() { //Trace.WriteLine(context.Database.Connection.ConnectionString); try { int successfullyProcessed = 0; int failedProcessed = 0; var failedEmails = new StringBuilder(); var emailBody = new StringBuilder(); List<Int32> listOfFailedRecurringBillingId = new List<Int32>(); emailBody.AppendLine(@"Recurring Billing Consolidated Report\r\n\r\n"); emailBody.AppendLine(String.Format(@"Current date: {0}\r\n\r\n\r\n", registDt)); Console.WriteLine("Fetching users for recurring billing..."); DateTime dtRecur = registDt.Date.AddDays(addDays); var recurringBillings = GetUsersEligibleForRenewal(dtRecur); Console.WriteLine(String.Format("Total users eligible for renewal: {0}", recurringBillings.Count())); if (recurringBillings != null) { if (recurringBillings.Count > 0) { using (var context = new IPTV2Entities()) { var gomsService = new GomsTfcTv(); try { gomsService.TestConnect(); Console.WriteLine("Test Connect success"); } catch (Exception) { Console.WriteLine("Test Connect failed."); } foreach (var i in recurringBillings) { using (var context3 = new IPTV2Entities()) { var user = context3.Users.FirstOrDefault(u => u.UserId == i.UserId); var recurringBilling = context3.RecurringBillings.Find(i.RecurringBillingId); var product = context3.Products.Find(i.ProductId); string productName = String.Empty; Console.WriteLine(String.Format("Processing user {0} with productId {1}, endDate {2}", user.EMail, product.Description, recurringBilling.EndDate)); try { ProductPrice priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == user.Country.CurrencyCode && p.ProductId == product.ProductId); if (priceOfProduct == null) priceOfProduct = context3.ProductPrices.FirstOrDefault(p => p.CurrencyCode == DefaultCurrencyCode && p.ProductId == product.ProductId); Purchase purchase = CreatePurchase(registDt, "Payment via Credit Card"); user.Purchases.Add(purchase); PurchaseItem item = CreatePurchaseItem(user.UserId, product, priceOfProduct); purchase.PurchaseItems.Add(item); var cardType = user.CreditCards.LastOrDefault(c => c.StatusId == 1).CardType; CreditCardPaymentTransaction transaction = new CreditCardPaymentTransaction() { Amount = priceOfProduct.Amount, Currency = priceOfProduct.CurrencyCode, Reference = cardType.ToUpper(), Date = registDt, Purchase = purchase, OfferingId = offeringId, StatusId = 1 }; var response = gomsService.CreateOrderViaRecurringPayment(context3, user.UserId, transaction); if (response.IsSuccess) { DateTime endDate = registDt; item.SubscriptionProduct = (SubscriptionProduct)product; if (item.SubscriptionProduct is PackageSubscriptionProduct) { PackageSubscriptionProduct subscription = (PackageSubscriptionProduct)product; foreach (var package in subscription.Packages) { string packageName = package.Package.Description; string ProductNameBought = packageName; productName = ProductNameBought; PackageEntitlement currentPackage = user.PackageEntitlements.FirstOrDefault(p => p.PackageId == package.PackageId); EntitlementRequest request = CreateEntitlementRequest(registDt, endDate, product, String.Format("{0}-{1}", "CC", cardType), response.TransactionId.ToString(), registDt); if (currentPackage != null) { request.StartDate = currentPackage.EndDate; currentPackage.EndDate = GetEntitlementEndDate(subscription.Duration, subscription.DurationType, ((currentPackage.EndDate > registDt) ? currentPackage.EndDate : registDt)); endDate = currentPackage.EndDate; currentPackage.LatestEntitlementRequest = request; request.EndDate = endDate; } else { PackageEntitlement entitlement = CreatePackageEntitlement(request, subscription, package, registDt); request.EndDate = entitlement.EndDate; user.PackageEntitlements.Add(entitlement); } user.EntitlementRequests.Add(request); item.EntitlementRequest = request; //UPDATED: November 22, 2012 } recurringBilling.EndDate = endDate; recurringBilling.NextRun = endDate.AddDays(-3).Date; recurringBilling.UpdatedOn = registDt; recurringBilling.GomsRemarks = null; recurringBilling.NumberOfAttempts = 0; } Console.WriteLine(user.EMail + ": renewal process complete!"); if (context3.SaveChanges() > 0) { successfullyProcessed += 1; Console.WriteLine("Saving changes..."); } //Send email to user; try { SendConfirmationEmails(user, user, transaction, productName, product, endDate, registDt, "Credit Card", (DateTime)endDate.AddDays(-4).Date); } catch (Exception e) { recurringBilling.GomsRemarks = e.Message; } } else { using (var context2 = new IPTV2Entities()) { var failedRecurring = context2.RecurringBillings.FirstOrDefault(r => r.RecurringBillingId == recurringBilling.RecurringBillingId); if (failedRecurring != null) { failedRecurring.GomsRemarks = response.StatusMessage; failedRecurring.NumberOfAttempts += 1; listOfFailedRecurringBillingId.Add(failedRecurring.RecurringBillingId); if (failedRecurring.NumberOfAttempts == 2) { //Send failure email try { SendConfirmationEmails(user, user, transaction, productName, product, registDt, registDt, "Credit Card", registDt, response.StatusMessage); } catch (Exception e) { failedRecurring.GomsRemarks = e.Message; } } string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nError: {3}\r\n\r\n", failedRecurring.RecurringBillingId, user.EMail, product.Description, response.StatusMessage); failedEmails.AppendLine(failedSpecificsCopy); failedEmails.AppendLine("--------------------------------------------------\r\n\r\n"); failedProcessed += 1; if (context2.SaveChanges() > 0) Console.WriteLine("Saving error..."); } } throw new Exception(user.EMail + ": " + response.StatusMessage); } } catch (Exception e) { Console.WriteLine("Inner Exception: " + e.Message); } } } //if (context.SaveChanges() > 0) //{ // Console.WriteLine("Saving changes..."); Console.WriteLine("Processing of eligible users for recurring billing has completed"); //} //Finish the copy of the email emailBody.AppendLine(String.Format(@"Total number of successful transactions: {0}\r\n\r\n", successfullyProcessed)); emailBody.AppendLine(String.Format(@"Total number of failed transactions (GOMS): {0}\r\n\r\n\r\n", failedProcessed)); if (failedEmails.Length > 0) { emailBody.AppendLine(@"Specifics can be found below\r\n\r\n\r\n"); emailBody.AppendLine(String.Format(@"{0}\r\n\r\n\r\n", failedEmails.ToString())); } emailBody.AppendLine("=================================================================\r\n\r\n\r\n"); //Get total numbers of recurring billing that have reached processing threshold //var reachedThreshold = context.RecurringBillings.Where(r => r.StatusId == 1 && r.NumberOfAttempts == 3); //if (reachedThreshold != null) //{ // emailBody.AppendLine(String.Format(@"Total number of failed transactions (MAX ATTEMPT): {0}\r\n\r\n", reachedThreshold.Count())); // foreach (var item in reachedThreshold) // { // string failedSpecificsCopy = String.Format("RBId: {0}\r\n\r\nEmail: {1}\r\n\r\nProduct: {2}\r\n\r\nLast error received: {3}\r\n\r\n", item.RecurringBillingId, item.User.EMail, item.Product.Description, item.GomsRemarks); // emailBody.AppendLine(failedSpecificsCopy); // emailBody.AppendLine("--------------------------------------------------\r\n\r\n"); // } //} failedEmails.AppendLine("=================================================================\r\n\r\n\r\n"); emailBody.AppendLine("Report ends here."); var newEmailBody = new StringBuilder(); newEmailBody.AppendLine("<!DOCTYPE html><html><body style=\"font-family: \"Trebuchet MS\", Arial, sans-serif;color:#000; font-size: 14px;\">"); newEmailBody.AppendLine("<h3>Report summary</h3>"); newEmailBody.AppendLine(String.Format("DateTime of processing (UTC): {0}", UtcDt)); newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of successful transactions: {0}</p>", successfullyProcessed)); newEmailBody.AppendLine(String.Format("<p style=\"font-size: 16px; font-weight: bold;\">Total number of failed transactions: {0}</p>", failedProcessed)); newEmailBody.AppendLine(CreateConsolidatedReport(1, "GOMS", listOfFailedRecurringBillingId)); newEmailBody.AppendLine("<hr />"); newEmailBody.AppendLine(CreateConsolidatedReport(3, "MAX ATTEMPT", null)); newEmailBody.AppendLine("<p style=\"font-size: 16px; font-weight: bold;\">Report ends here.</p>"); newEmailBody.AppendLine("</body></html>"); if (IsSendConsolidatedReportsEnabled) { var receivers = consolidatedReportReceivers.Split(','); try { //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", emailBody.ToString(), MailType.TextOnly, emailBody.ToString(), receivers); //SendEmailViaSendGrid(null, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers); SendEmailViaSendGrid(toRecipient, NoReplyEmail, "TFC.tv Recurring Billing: Consolidated Report", newEmailBody.ToString(), MailType.HtmlOnly, newEmailBody.ToString(), receivers); Console.WriteLine("Sending of consolidated report is successful!"); } catch (Exception) { Console.WriteLine("Sending of consolidated report failed!"); } } //CANCELL ALL RECURRING try { var cancellation_list = GetUsersEligibleForCancellation(dtRecur); foreach (var i in cancellation_list) { try { gomsService.CancelRecurringPayment(i.User, i.Product); } catch (Exception) { } } } catch (Exception) { } } } else Console.WriteLine("Nothing to process.."); } } catch (Exception e) { Console.WriteLine("Outer Exception: " + e.Message); } }