/// <summary> /// Charges the specified order. /// </summary> /// <param name="order">The order.</param> /// <param name="userName">Name of the user.</param> /// <returns></returns> public static Transaction Charge(Order order, string userName) { //update the order with IP order.IPAddress = HttpContext.Current.Request.UserHostAddress == "::1" || HttpContext.Current.Request.UserHostAddress == "127.0.0.1" ? "127.0.0.1" : HttpContext.Current.Request.UserHostAddress; PaymentService paymentService = new PaymentService(); Transaction transaction = paymentService.Charge(order); order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder; order.OrderTypeId = (int)OrderType.Purchase; order.Save(userName); Guid userGuid = new Guid(Membership.GetUser(userName).ProviderUserKey.ToString()); try { //Add an OrderNote OrderNote orderNote = new OrderNote(); orderNote.OrderId = order.OrderId; orderNote.Note = Strings.ResourceManager.GetString(ORDER_CHARGED); orderNote.Save(userName); Sku sku; DownloadCollection downloadCollection; DownloadAccessControlCollection downloadAccessControlCollection; DownloadAccessControl downloadAccessControl; foreach (OrderItem orderItem in order.OrderItemCollection) { //Adjust the Inventory sku = new Sku(SKU, orderItem.Sku); sku.Inventory = sku.Inventory - orderItem.Quantity; sku.Save(SYSTEM); ProductCache.RemoveSKUFromCache(orderItem.Sku); //Add access control for orderitems downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId); if (downloadCollection.Count > 0) { foreach (Download download in downloadCollection) { Query query = new Query(DownloadAccessControl.Schema). AddWhere(DownloadAccessControl.Columns.UserId, Comparison.Equals, userGuid). AddWhere(DownloadAccessControl.Columns.DownloadId, Comparison.Equals, download.DownloadId); downloadAccessControlCollection = new DownloadAccessControlController().FetchByQuery(query); if (downloadAccessControlCollection.Count == 0) { downloadAccessControl = new DownloadAccessControl(); downloadAccessControl.DownloadId = download.DownloadId; downloadAccessControl.UserId = userGuid; downloadAccessControl.Save(SYSTEM); } } } } //Send out the messages //Send these last in case something happens with the email MessageService messageService = new MessageService(); messageService.SendOrderReceivedNotificationToCustomer(order); messageService.SendOrderReceivedNotificationToMerchant(order); } catch (Exception ex) { //swallow the exception here because the transaction is saved //and, while this is an inconvenience, it's not critical Logger.Error(typeof(OrderController).Name + ".Charge", ex); } return transaction; }
/// <summary> /// Handles the Click event of the btnManualTransaction control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected void btnManualTransaction_Click(object sender, EventArgs e) { try { Order order = new Order(orderId); paymentService = new PaymentService(); if (order.PaymentMethod == "PayPal" && paymentService.PaymentServiceSettings.ProviderSettingsCollection.Find(provider => provider.GetType().Name.Contains("PayPalStandardPaymentProvider")) != null) { OrderController.CommitStandardTransaction(order, txtTransactionId.Text.Trim(), order.Total); } SetOrderStatus(order.OrderStatusDescriptorId.ToString()); base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblManualTransactionSucceeded")); } catch (Exception ex) { Logger.Error(typeof(actions).Name + ".btnManualTransaction_Click", ex); base.MasterPage.MessageCenter.DisplayCriticalMessage(LocalizationUtility.GetCriticalMessageText(ex.Message)); } }
/// <summary> /// Handles the Click event of the btnSave control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void btnSave_Click(object sender, EventArgs e) { if(!string.IsNullOrEmpty(txtShippingTrackingNumber.Text)) { try { Order order = new Order(orderId); order.ShippingTrackingNumber = txtShippingTrackingNumber.Text; order.Save(WebUtility.GetUserName()); MessageService messageService = new MessageService(); messageService.SendShippingNotificationToCustomer(order); base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblShippingSaved")); } catch(Exception ex) { Logger.Error(typeof(shipping).Name + ".btnSave_Click", ex); base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message); } } }
/// <summary> /// Handles the Click event of the btnOrderStatus control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void btnOrderStatus_Click(object sender, EventArgs e) { try { Order order = new Order(orderId); int orderStatusDescriptorId = order.OrderStatusDescriptorId; bool isParsed = int.TryParse(ddlOrderStatus.SelectedValue, out orderStatusDescriptorId); if(!isParsed) { orderStatusDescriptorId = order.OrderStatusDescriptorId; } order.OrderStatusDescriptorId = orderStatusDescriptorId; order.Save(WebUtility.GetUserName()); base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblOrderStatusChanged")); } catch(Exception ex) { Logger.Error(typeof(actions).Name + ".btnOrderStatus_Click", ex); base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message); } }
public Order(Order order, string userName) { this.OrderId = 0; this.OrderGuid = Guid.NewGuid(); this.OrderNumber = order.OrderNumber; this.OrderTypeId = (int)OrderType.Refund; this.OrderParentId = order.OrderId; this.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded; this.UserName = order.UserName; this.ShippingAmount = 0; this.ShippingMethod = string.Empty; this.HandlingAmount = 0; this.BillToAddress = order.BillToAddress; this.ShipToAddress = order.ShipToAddress; this.IPAddress = HttpContext.Current.Request.UserHostAddress; this.PaymentMethod = order.PaymentMethod; this.ShippingTrackingNumber = string.Empty; this.AdditionalProperties = order.AdditionalProperties; this.CreatedBy = userName; this.CreatedOn = DateTime.UtcNow; this.ModifiedBy = userName; this.ModifiedOn = DateTime.UtcNow; }
/// <summary> /// Appends the line items. /// </summary> /// <param name="order">The order.</param> /// <param name="sb">The sb.</param> private static void AppendLineItems(Order order, StringBuilder sb, Currency currency) { string sku = string.Empty; string name = string.Empty; string description = string.Empty; foreach (OrderItem orderItem in order.OrderItemCollection) { //Sku, Name, Description, Quantity, Unit Price, Taxable if (!string.IsNullOrEmpty(orderItem.Sku)) { sku = orderItem.Sku.Length < 31 ? orderItem.Sku : orderItem.Sku.Substring(0, 30); } if (!string.IsNullOrEmpty(orderItem.Name)) { name = orderItem.Name.Length < 31 ? orderItem.Name : orderItem.Name.Substring(0, 30); } if (!string.IsNullOrEmpty(orderItem.Attributes)) { description = orderItem.Attributes.Length < 255 ? orderItem.Attributes : orderItem.Attributes.Substring(0, 254); } sb.AppendFormat("&x_line_item={0}<|>{1}<|>{2}<|>{3}<|>{4}<|>{5}", HttpUtility.UrlEncode(sku), HttpUtility.UrlEncode(name), HttpUtility.UrlEncode(description), HttpUtility.UrlEncode(orderItem.Quantity.ToString()), HttpUtility.UrlEncode(GetFormattedAmount(currency, orderItem.PricePaid).ToString()), HttpUtility.UrlEncode("TRUE")); } }
/// <summary> /// Refunds the specified order. /// </summary> /// <param name="order">The order.</param> /// <returns></returns> internal Transaction Refund(Transaction transaction, Order order) { StringBuilder sb = new StringBuilder(); string postData = string.Empty; Currency currency = new Currency(); #region Best Practice Fields GetBestPracticeFields(sb, AuthorizeNetTransactionType.CREDIT); #endregion #region Refund Fields sb.AppendFormat("&x_trans_id={0}", HttpUtility.UrlEncode(transaction.GatewayTransactionId)); //We need to get the parent order because it has the ExtendedProperty we need. //TODO: CMC - If we keep the full info, it needs to be encrypted. Order parentOrder = new Order(transaction.OrderId); sb.AppendFormat("&x_card_num={0}", HttpUtility.UrlEncode(parentOrder.ExtendedProperties["Validator"].ToString())); //.Substring((parentOrder.ExtendedProperties["AuthorizeNetRefundValidator"].ToString().Length - 4)))); sb.AppendFormat("&x_exp_date={0}", HttpUtility.UrlEncode(parentOrder.ExtendedProperties["ExpDate"].ToString())); //sb.AppendFormat("&x_card_code={0}", HttpUtility.UrlEncode(parentOrder.ExtendedProperties["SecNum"].ToString())); sb.AppendFormat("&x_amount={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.Total).ToString())); #endregion #region Line Items AppendLineItems(order, sb, currency); //foreach (OrderItem orderItem in order.OrderItemCollection) { // //Sku, Name, Description, Quantity, Unit Price, Taxable // sb.AppendFormat("&x_line_item={0}<|>{1}<|>{2}<|>{3}<|>{4}<|>{5}", HttpUtility.UrlEncode(orderItem.Sku), HttpUtility.UrlEncode(orderItem.Name), HttpUtility.UrlEncode(orderItem.Attributes), HttpUtility.UrlEncode(orderItem.Quantity.ToString()), HttpUtility.UrlEncode(GetFormattedAmount(currency, orderItem.PricePaid).ToString()), HttpUtility.UrlEncode("TRUE")); //} #endregion #region Refund it postData = sb.ToString(); string response = CoreUtility.SendRequestByPost(AuthorizeServiceUtility.GetAuthorizeServiceEndpoint(this.IsLive), postData); #endregion #region Check it and Build up the Transaction string[] output = response.Split('|'); int counter = 1;//Start @ 1 to keep in sync with docs System.Collections.Hashtable vars = new System.Collections.Hashtable(); foreach (string var in output) { vars.Add(counter, var); counter += 1; } Transaction refundTransaction = null; string responseCode = vars[1].ToString(); if ((responseCode == "2") || (responseCode == "3")) { throw new AuthorizeNetServiceException(vars[4].ToString());// + " :: " + postData); } else { refundTransaction = new Transaction(); refundTransaction.OrderId = transaction.OrderId; refundTransaction.TransactionTypeDescriptorId = (int)TransactionType.Refund; refundTransaction.PaymentMethod = transaction.PaymentMethod; refundTransaction.GatewayName = AUTHORIZENET; refundTransaction.GatewayResponse = vars[1].ToString(); refundTransaction.GatewayTransactionId = vars[7].ToString(); refundTransaction.AVSCode = vars[6].ToString(); refundTransaction.CVV2Code = vars[39].ToString(); decimal grossAmount = 0.00M; bool isParsed = decimal.TryParse(vars[10].ToString(), out grossAmount); refundTransaction.GrossAmount = grossAmount; refundTransaction.TransactionDate = DateTime.Now; } #endregion return refundTransaction; }
/// <summary> /// Commits the standard transaction. /// </summary> /// <param name="order">The order.</param> /// <param name="transactionId">The transaction id.</param> /// <param name="grossAmount">The gross amount.</param> /// <returns></returns> public static Transaction CommitStandardTransaction(Order order, string transactionId, decimal grossAmount) { order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder; order.Save(SYSTEM); Transaction transaction = new Transaction(); transaction.OrderId = order.OrderId; transaction.TransactionTypeDescriptorId = (int)TransactionType.Charge; transaction.PaymentMethod = PAYPAL; transaction.GatewayName = PAYPAL_STANDARD; transaction.GatewayResponse = SUCCESS; transaction.GatewayTransactionId = transactionId; transaction.GrossAmount = grossAmount; transaction.TransactionDate = DateTime.UtcNow; transaction.Save(SYSTEM); try { //Adjust the Inventory Sku sku; foreach (OrderItem orderItem in order.OrderItemCollection) { sku = new Sku("Sku", orderItem.Sku); sku.Inventory = sku.Inventory - orderItem.Quantity; sku.Save("System"); ProductCache.RemoveSKUFromCache(orderItem.Sku); } //Send out the messages MessageService messageService = new MessageService(); messageService.SendOrderReceivedNotificationToCustomer(order); messageService.SendOrderReceivedNotificationToMerchant(order); } catch (Exception ex) { //swallow the exception here because the transaction is saved //and, while this is an inconvenience, it's not critical Logger.Error(typeof(OrderController).Name + ".CommitStandardTransaction", ex); } return transaction; }
public Transaction Charge(Order order) { Transaction transaction = _authorizeService.Charge(order); return transaction; }
/// <summary> /// Handles the Click event of the btnRefundTransaction control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void btnRefundTransaction_Click(object sender, EventArgs e) { try { if (Page.IsValid) { TextBox txtRefundQuantity = null; Order order = new Order(orderId); OrderItem orderItem = null; OrderItem refundedOrderItem = null; Order refundOrder = new Order(order, WebUtility.GetUserName()); foreach (DataGridItem item in dgOrderItems.Items) { txtRefundQuantity = item.Cells[0].FindControl("txtRefundQuantity") as TextBox; if (txtRefundQuantity != null) { int quantity = 0; bool isParsed = int.TryParse(txtRefundQuantity.Text, out quantity); if (isParsed) { orderItem = new OrderItem(item.Cells[0].Text); refundedOrderItem = new OrderItem(); //refundedOrderItem.OrderId = orderItem.OrderId; refundedOrderItem.ProductId = orderItem.ProductId; refundedOrderItem.Name = orderItem.Name; refundedOrderItem.Sku = orderItem.Sku; refundedOrderItem.Quantity = quantity; refundedOrderItem.PricePaid = orderItem.PricePaid; refundedOrderItem.Attributes = orderItem.Attributes; refundedOrderItem.Weight = orderItem.Weight; refundedOrderItem.ItemTax = orderItem.ItemTax; refundedOrderItem.DiscountAmount = orderItem.DiscountAmount; refundOrder.OrderItemCollection.Add(refundedOrderItem); } } } decimal additionalRefundAmount = 0; decimal.TryParse(txtAdditionalRefundAmount.Text, out additionalRefundAmount); refundOrder.ShippingAmount = additionalRefundAmount; Transaction transaction = new TransactionController().FetchByOrderIdAndTransactionTypeId(orderId, (int)TransactionType.Charge); if (transaction.GatewayName == "PayPal Standard") { OrderController.RefundStandard(transaction, refundOrder, WebUtility.GetUserName()); } else { OrderController.Refund(transaction, refundOrder, WebUtility.GetUserName()); } base.MasterPage.MessageCenter.DisplaySuccessMessage(LocalizationUtility.GetText("lblOrderRefunded")); } } catch (PaymentServiceException pse) { Logger.Error(typeof(actions).Name + ".btnRefundTransaction_Click", pse); base.MasterPage.MessageCenter.DisplayFailureMessage(LocalizationUtility.GetPaymentProviderErrorText(pse.Message)); } catch (Exception ex) { Logger.Error(typeof(actions).Name + ".btnRefundTransaction_Click", ex); base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message); } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnInit(EventArgs e) { Label lblBillingInformation = acCheckout.Panes[0].FindControl("lblBillingInformation") as Label; Label lblShippingInformation = acCheckout.Panes[1].FindControl("lblShippingInformation") as Label; Label lblShippingMethod = acCheckout.Panes[2].FindControl("lblShippingMethod") as Label; Label lblCouponInformation = acCheckout.Panes[3].FindControl("lblCouponInformation") as Label; Label lblOrderReview = acCheckout.Panes[4].FindControl("lblOrderReview") as Label; //See if there are any coupons in the system //If not, then don't display the coupon stuff couponCollection = new CouponController().FetchAll(); if (couponCollection.Count == 0) { hasCoupons = false; acpCoupon.Visible = false; pnlCouponInformationDisplayTitle.Visible = false; pnlCouponInformationDisplay.Visible = false; } shippingService = new ShippingService(); if (!shippingService.ShippingServiceSettings.UseShipping) { acCheckout.Panes[1].Visible = false; acCheckout.Panes[2].Visible = false; pnlShippingAddressDisplayTitle.Visible = false; pnlShippingAddressDisplay.Visible = false; pnlShippingMethodDisplayTitle.Visible = false; pnlShippingMethodDisplay.Visible = false; } order = new OrderController().FetchOrder(WebUtility.GetUserName()); if (!Page.IsPostBack) { SetBillingAddressDisplay(); SetShippingAddressDisplay(); SetShippingMethodDisplay(); SetCouponDisplay(); } base.OnInit(e); }
/// <summary> /// Refunds the specified transaction. /// </summary> /// <param name="transaction">The transaction.</param> /// <param name="refundedOrder">The refunded order.</param> /// <param name="userName">Name of the user.</param> public static void RefundStandard(Transaction transaction, Order refundedOrder, string userName) { Order order = new Order(transaction.OrderId); Transaction refundTransaction = new Transaction(); //refundTransaction.OrderId = transaction.OrderId; refundTransaction.TransactionTypeDescriptorId = (int)TransactionType.Refund; refundTransaction.PaymentMethod = PAYPAL; refundTransaction.GatewayName = PAYPAL_STANDARD; refundTransaction.GatewayResponse = SUCCESS; refundTransaction.GatewayTransactionId = CoreUtility.GenerateRandomString(16); refundTransaction.GrossAmount = refundedOrder.Total; refundTransaction.NetAmount = 0.00M; refundTransaction.FeeAmount = 0.00M; refundTransaction.TransactionDate = DateTime.Now; //refundTransaction.Save(userName); refundedOrder.Save(userName); //set the orderid for the refund foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) { orderItem.OrderId = refundedOrder.OrderId; } refundedOrder.OrderItemCollection.SaveAll(userName); //set the orderId to the refunded orderId refundTransaction.OrderId = refundedOrder.OrderId; refundTransaction.Save(userName); Guid userGuid = new Guid(Membership.GetUser(order.UserName).ProviderUserKey.ToString()); DownloadCollection downloadCollection; foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) { //put the stock back Sku sku = new Sku(Sku.Columns.SkuX, orderItem.Sku); sku.Inventory = sku.Inventory + orderItem.Quantity; sku.Save(userName); ProductCache.RemoveSKUFromCache(orderItem.Sku); //remove the access control downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId); if (downloadCollection.Count > 0) { foreach (Download download in downloadCollection) { new DownloadAccessControlController().Delete(userGuid, download.DownloadId); } } } if(refundedOrder.Total == order.Total) { order.OrderStatusDescriptorId = (int)OrderStatus.OrderFullyRefunded; } else { order.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded; } order.Save(userName); //Add an OrderNote OrderNote orderNote = new OrderNote(); orderNote.OrderId = order.OrderId; orderNote.Note = Strings.ResourceManager.GetString(ORDER_REFUNDED); orderNote.Save(userName); //send off the notifications MessageService messageService = new MessageService(); messageService.SendOrderRefundToCustomer(refundedOrder); }
/// <summary> /// Sets the express checkout. /// </summary> /// <param name="order">The order.</param> /// <param name="returnUrl">The return URL.</param> /// <param name="cancelUrl">The cancel URL.</param> /// <param name="authorizeOnly">if set to <c>true</c> [authorize only].</param> /// <returns></returns> public static string SetExpressCheckout(Order order, string returnUrl, string cancelUrl, bool authorizeOnly) { PaymentService paymentService = new PaymentService(); string token = paymentService.SetExpressCheckout(order, returnUrl, cancelUrl, authorizeOnly); return token; }
/// <summary> /// Normalizes the cart quantities. /// </summary> /// <param name="order">The order.</param> /// <returns></returns> public static bool NormalizeCartQuantities(Order order) { bool changesMade = false; if (order.OrderId > 0) { List<OrderItem> itemsToRemove = new List<OrderItem>(); foreach (OrderItem item in order.OrderItemCollection) { Product product = Product.FetchByID(item.ProductId); if (!product.AllowNegativeInventories) { SkuCollection skuCollection = new SkuCollection().Where(Sku.Columns.SkuX, SubSonic.Comparison.Equals, item.Sku).Load(); if (skuCollection != null) { if (skuCollection.Count == 0 || skuCollection[0].Inventory == 0 || product.ProductStatusDescriptorId == (int)ProductStatus.Inactive) { itemsToRemove.Add(item); changesMade = true; } else if (item.Quantity > skuCollection[0].Inventory) { item.Quantity = skuCollection[0].Inventory; new OrderController().AdjustQuantity(order.OrderId, item.OrderItemId, item.Quantity, order.UserName); changesMade = true; } } } } foreach (OrderItem item in itemsToRemove) { new OrderController().RemoveItem(order.OrderId, item.OrderItemId, order.UserName); order.OrderItemCollection.Remove(item); } if (order.OrderItemCollection.Count == 0) { Order.Delete(order.OrderId); } } return changesMade; }
/// <summary> /// Refunds the specified transaction. /// </summary> /// <param name="transaction">The transaction.</param> /// <param name="refundedOrder">The order the refund should be applied to.</param> /// <param name="userName">Name of the user.</param> public static void Refund(Transaction transaction, Order refundedOrder, string userName) { Order order = new Order(transaction.OrderId); PaymentService paymentService = new PaymentService(); Transaction refundTransaction = paymentService.Refund(transaction, refundedOrder); refundedOrder.Save(userName); //set the orderid for the refund foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) { orderItem.OrderId = refundedOrder.OrderId; } refundedOrder.OrderItemCollection.SaveAll(userName); //set the orderId to the refunded orderId refundTransaction.OrderId = refundedOrder.OrderId; refundTransaction.Save(userName); Guid userGuid = new Guid(Membership.GetUser(order.UserName).ProviderUserKey.ToString()); foreach(OrderItem orderItem in refundedOrder.OrderItemCollection) { new Product(orderItem.ProductId); //put the stock back Sku sku = new Sku(Sku.Columns.SkuX, orderItem.Sku); sku.Inventory = sku.Inventory + orderItem.Quantity; sku.Save(userName); ProductCache.RemoveSKUFromCache(orderItem.Sku); //remove the access control DownloadCollection downloadCollection = new ProductController().FetchAssociatedDownloadsByProductIdAndForPurchase(orderItem.ProductId); if (downloadCollection.Count > 0) { foreach (Download download in downloadCollection) { new DownloadAccessControlController().Delete(userGuid, download.DownloadId); } } } if(refundedOrder.Total == order.Total) { order.OrderStatusDescriptorId = (int)OrderStatus.OrderFullyRefunded; } else { order.OrderStatusDescriptorId = (int)OrderStatus.OrderPartiallyRefunded; } order.Save(userName); //Add an OrderNote OrderNote orderNote = new OrderNote(); orderNote.OrderId = order.OrderId; orderNote.Note = Strings.ResourceManager.GetString(ORDER_REFUNDED); orderNote.Save(userName); //send off the notifications MessageService messageService = new MessageService(); messageService.SendOrderRefundToCustomer(refundedOrder); }
/// <summary> /// Fetches the shipping options. /// </summary> /// <param name="order">The Order</param> /// <returns></returns> public static ShippingOptionCollection FetchShippingOptions(Order order) { ShippingService shippingService = new ShippingService(); ShippingOptionCollection shippingOptionCollection = shippingService.GetShippingOptions(order); return shippingOptionCollection; }
/// <summary> /// Does the express checkout. /// </summary> /// <param name="order">The order.</param> /// <param name="authorizeOnly">if set to <c>true</c> [authorize only].</param> /// <param name="userName">Name of the user.</param> /// <returns></returns> public static Transaction DoExpressCheckout(Order order, bool authorizeOnly, string userName) { PaymentService paymentService = new PaymentService(); Transaction transaction = paymentService.DoExpressCheckout(order, authorizeOnly); order.OrderStatusDescriptorId = (int)OrderStatus.ReceivedPaymentProcessingOrder; order.Save(userName); try { //Adjust the Inventory Sku sku; foreach (OrderItem orderItem in order.OrderItemCollection) { sku = new Sku(SKU, orderItem.Sku); sku.Inventory = sku.Inventory - orderItem.Quantity; sku.Save(SYSTEM); ProductCache.RemoveSKUFromCache(orderItem.Sku); } //Send out the messages MessageService messageService = new MessageService(); messageService.SendOrderReceivedNotificationToCustomer(order); messageService.SendOrderReceivedNotificationToMerchant(order); } catch (Exception ex) { //swallow the exception here because the transaction is saved //and, while this is an inconvenience, it's not critical Logger.Error(typeof(OrderController).Name + ".DoExpressCheckout", ex); } return transaction; }
/// <summary> /// Creates the cart URL. /// </summary> /// <param name="order">The order.</param> /// <param name="returnUrl">The return URL.</param> /// <param name="cancelUrl">The cancel URL.</param> /// <returns></returns> public static string CreateCartUrl(Order order, string returnUrl, string cancelUrl, string notifyUrl) { PaymentService paymentService = new PaymentService(); string url = paymentService.CreateCartUrl(order, returnUrl, cancelUrl, notifyUrl); return url; }
public void Insert(Guid OrderGuid,string OrderNumber,int OrderTypeId,int OrderParentId,int OrderStatusDescriptorId,string UserName,decimal ShippingAmount,string ShippingMethod,decimal HandlingAmount,string BillToAddress,string ShipToAddress,string IPAddress,string PaymentMethod,string ShippingTrackingNumber,string AdditionalProperties,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn) { Order item = new Order(); item.OrderGuid = OrderGuid; item.OrderNumber = OrderNumber; item.OrderTypeId = OrderTypeId; item.OrderParentId = OrderParentId; item.OrderStatusDescriptorId = OrderStatusDescriptorId; item.UserName = UserName; item.ShippingAmount = ShippingAmount; item.ShippingMethod = ShippingMethod; item.HandlingAmount = HandlingAmount; item.BillToAddress = BillToAddress; item.ShipToAddress = ShipToAddress; item.IPAddress = IPAddress; item.PaymentMethod = PaymentMethod; item.ShippingTrackingNumber = ShippingTrackingNumber; item.AdditionalProperties = AdditionalProperties; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Save(UserName); }
/// <summary> /// Fetches the order. /// </summary> /// <param name="guid">The GUID.</param> /// <returns></returns> public Order FetchOrder(Guid guid) { Order order = new Order(); Query query = new Query(Order.Schema).AddWhere(Order.Columns.OrderGuid, guid.ToString()); OrderCollection orderCollection = this.FetchByQuery(query); if(orderCollection.Count > 1) { throw new InvalidOperationException(EXCEPTION_TOO_MANY_CARTS); } if(orderCollection.Count == 1) { order = orderCollection[0]; } return order; }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init"></see> event to initialize the page. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs"></see> that contains the event data.</param> protected override void OnInit(EventArgs e) { if (Master.SiteSettings.LoginRequirement == LoginRequirement.Checkout) { if (!User.Identity.IsAuthenticated) { Response.Redirect("login.aspx?ReturnUrl=/checkout.aspx", true); } } PaymentService paymentService = new PaymentService(); if (paymentService.PaymentServiceSettings.DefaultProvider == "PayPalStandardPaymentProvider") { Response.Redirect("~/paypalcheckout.aspx", true); } //Keep these here - the Accordion ViewState is funky and requires things to be set early Label lblBillingInformation = acCheckout.Panes[0].FindControl("lblBillingInformation") as Label; Label lblShippingInformation = acCheckout.Panes[1].FindControl("lblShippingInformation") as Label; Label lblShippingMethod = acCheckout.Panes[2].FindControl("lblShippingMethod") as Label; Label lblCouponInformation = acCheckout.Panes[3].FindControl("lblCouponInformation") as Label; Label lblPaymentInformation = acCheckout.Panes[4].FindControl("lblPaymentInformation") as Label; Label lblOrderReview = acCheckout.Panes[5].FindControl("lblOrderReview") as Label; //See if there are any coupons in the system //If not, then don't display the coupon stuff couponCollection = new CouponController().FetchAll(); if (couponCollection.Count == 0) { hasCoupons = false; acpCoupon.Visible = false; pnlCouponInformationDisplayTitle.Visible = false; pnlCouponInformationDisplay.Visible = false; } shippingService = new ShippingService(); if (!shippingService.ShippingServiceSettings.UseShipping) { acCheckout.Panes[1].Visible = false; acCheckout.Panes[2].Visible = false; pnlShippingAddressDisplayTitle.Visible = false; pnlShippingAddressDisplay.Visible = false; pnlShippingMethodDisplayTitle.Visible = false; pnlShippingMethodDisplay.Visible = false; } //Keep these here - the Accordion ViewState is funky and requires things to be set early order = new OrderController().FetchOrder(WebUtility.GetUserName()); #region PayPal Express Checkout Logic if (!string.IsNullOrEmpty(order.PaymentMethod)) { if (order.PaymentMethod == "PayPal") { string token = Utility.GetParameter("token"); if (!string.IsNullOrEmpty(token)) { pnlCreditCardInformation.Visible = false; pnlCreditCardInfo.Visible = false; lblCreditCardType.Text = order.PaymentMethod; ddlCreditCardType.SelectedValue = "4"; ddlCreditCardType.Enabled = false; PayPalPayer payPalPayer = OrderController.GetExpressCheckout(token); if (order.BillingAddress == null) {//Then they are coming in from the cart.aspx ExpressCheckout button //copy the PayPalPayer ShippingAddress and then flag it as a BillingAddress Address billingAddress = new Address(payPalPayer.ShippingAddress); billingAddress.AddressType = AddressType.BillingAddress; Address duplicateBillingAddress = WebProfile.Current.AddressCollection.Find( addressToFind => addressToFind.ToString() == billingAddress.ToString() && addressToFind.AddressType == AddressType.BillingAddress); if (duplicateBillingAddress == null) { WebProfile.Current.AddressCollection.Add(billingAddress); WebProfile.Current.Save(); } order.BillToAddress = payPalPayer.ShippingAddress.ToXml(); } if (!payPalPayer.ShippingAddress.Equals(order.ShippingAddress)) { Address shippingAddress = new Address(payPalPayer.ShippingAddress); shippingAddress.AddressType = AddressType.ShippingAddress; Address duplicateShippingAddress = WebProfile.Current.AddressCollection.Find( addressToFind => addressToFind.ToString() == shippingAddress.ToString() && addressToFind.AddressType == AddressType.ShippingAddress); if (duplicateShippingAddress == null) { WebProfile.Current.AddressCollection.Add(shippingAddress); WebProfile.Current.Save(); } order.ShipToAddress = payPalPayer.ShippingAddress.ToXml(); } if (order.ExtendedProperties.ContainsKey(PAYPAL_PAYER_ID)) { order.ExtendedProperties.Remove(PAYPAL_PAYER_ID); } if (order.ExtendedProperties.ContainsKey(PAYPAL_TOKEN)) { order.ExtendedProperties.Remove(PAYPAL_TOKEN); } order.ExtendedProperties.Add(PAYPAL_PAYER_ID, payPalPayer.PayPalPayerId); order.ExtendedProperties.Add(PAYPAL_TOKEN, payPalPayer.PayPalToken); order.AdditionalProperties = order.ExtendedProperties.ToXml(); order.Save(WebUtility.GetUserName()); OrderController.CalculateTax(WebUtility.GetUserName()); order = new OrderController().FetchOrder(WebUtility.GetUserName()); } } } #endregion if (!Page.IsPostBack) { SetBillingAddressDisplay(); SetShippingAddressDisplay(); SetShippingMethodDisplay(); SetCouponDisplay(); SetPaymentMethodDisplay(-1, order.CreditCardNumber, DateTime.MinValue); } base.OnInit(e); }
/// <summary> /// Fetches the order. /// </summary> /// <param name="orderId">The order id.</param> /// <param name="userName">Name of the user.</param> /// <returns></returns> public Order FetchOrder(int orderId, string userName) { Order order = new Order(); Query query = new Query(Order.Schema). AddWhere(Order.Columns.OrderId, orderId). AddWhere(Order.Columns.UserName, userName). AddWhere(Order.Columns.OrderStatusDescriptorId, Comparison.NotEquals, (int)OrderStatus.NotProcessed); OrderCollection orderCollection = this.FetchByQuery(query); if(orderCollection.Count > 1) { throw new InvalidOperationException(EXCEPTION_TOO_MANY_CARTS); } if(orderCollection.Count == 1) { order = orderCollection[0]; } return order; }
/// <summary> /// Reloads the order. /// </summary> private void ReloadOrder() { order = new OrderController().FetchOrder(WebUtility.GetUserName()); orderSummary.Order = order; orderSummary.LoadOrder(); }
public Transaction Authorize(Order order) { throw new Exception("The method or operation is not implemented."); }
/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { try { Page.Title = string.Format(WebUtility.MainTitleTemplate, Master.SiteSettings.SiteName, LocalizationUtility.GetText("titleCart")); order = new OrderController().FetchOrder(WebUtility.GetUserName()); PaymentServiceSettings providers = PaymentService.FetchConfiguredPaymentProviders(); if (providers != null) { if (providers.DefaultProvider == "PayPalProPaymentProvider" || !(string.IsNullOrEmpty(providers.ProviderSettingsCollection["PayPalProPaymentProvider"].Parameters[PayPalProPaymentProvider.BUSINESS_EMAIL]))) { pnlExpressCheckout.Visible = true; } } if (!Page.IsPostBack) { bool changesMade = OrderController.NormalizeCartQuantities(order); if (changesMade) { messageCenter.Visible = true; messageCenter.DisplayInformationMessage(LocalizationUtility.GetText("lblCartChanged")); } if (order.OrderId > 0 && order.OrderItemCollection.Count > 0) { pnlNoCart.Visible = false; orderSummary.Order = order; lblSubTotalAmountTop.Text = StoreUtility.GetFormattedAmount(order.SubTotal, true); lbUpdate.Text = LocalizationUtility.GetText("lblUpdate"); } else { pnlCart.Visible = false; ProductCollection productCollection; if (this.Master.SiteSettings.CollectBrowsingProduct) { productCollection = Store.Caching.ProductCache.GetMostPopularProducts(); } else { productCollection = new ProductController().FetchRandomProducts();//Should we cache this? } catalogList.ProductCollection = productCollection; } } } catch (Exception ex) { Logger.Error(typeof(cart).Name + ".Page_Load", ex); throw; } }
/// <summary> /// Provisions the order. /// </summary> /// <param name="userName">Name of the user.</param> /// <returns></returns> private int ProvisionOrder(string userName) { int orderId = GetOrderId(userName); if(orderId == 0) { Order order = new Order(); order.OrderGuid = Guid.NewGuid(); //order.OrderNumber = CoreUtility.GenerateRandomString(ORDER_NUMBER_LENGTH); order.OrderNumber = CoreUtility.Generate4By4MaskedString(); order.OrderStatusDescriptorId = (int)OrderStatus.NotProcessed; order.UserName = userName; order.IPAddress = HttpContext.Current.Request.UserHostAddress; order.Save(userName); orderId = order.OrderId; } return orderId; }
/// <summary> /// Handles the Load event of the Page control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="T:System.EventArgs"/> instance containing the event data.</param> protected void Page_Load(object sender, EventArgs e) { try { orderId = Utility.GetIntParameter("orderId"); view = Utility.GetParameter("view"); if(orderId > 0 && view == "a") { SetActionsProperties(); if(!Page.IsPostBack) { Order order = new Order(orderId); ds = new OrderController().FetchRefundedOrderItems(orderId); Transaction transaction = new TransactionController().FetchByOrderIdAndTransactionTypeId(orderId, (int)TransactionType.Charge); if(transaction.GatewayName == "PayPal Standard") { lblActionMessage.Text = LocalizationUtility.GetText("lblPayPalStandardRefundInstructions"); } if(order.OrderStatusDescriptorId == (int)OrderStatus.OrderFullyRefunded) { btnRefundTransaction.Visible = false; lblAdditionalRefundAmount.Visible = false; txtAdditionalRefundAmount.Visible = false; dgOrderItems.Visible = false; } else { dgOrderItems.DataSource = order.OrderItemCollection; dgOrderItems.ItemDataBound += new DataGridItemEventHandler(dgOrderItems_ItemDataBound); dgOrderItems.Columns[1].HeaderText = LocalizationUtility.GetText("hdrRefund"); dgOrderItems.Columns[2].HeaderText = LocalizationUtility.GetText("hdrSku"); dgOrderItems.Columns[3].HeaderText = LocalizationUtility.GetText("hdrQuantityRemaining"); dgOrderItems.Columns[4].HeaderText = LocalizationUtility.GetText("hdrName"); dgOrderItems.Columns[5].HeaderText = LocalizationUtility.GetText("hdrPricePaid"); dgOrderItems.Columns[6].HeaderText = LocalizationUtility.GetText("hdrItemTax"); dgOrderItems.Columns[7].HeaderText = LocalizationUtility.GetText("hdrDiscountAmount"); dgOrderItems.DataBind(); } OrderStatusDescriptorCollection orderStatusDescriptorCollection = new OrderStatusDescriptorController().FetchAll(); ddlOrderStatus.DataSource = orderStatusDescriptorCollection; ddlOrderStatus.DataValueField = "OrderStatusDescriptorId"; ddlOrderStatus.DataTextField = "Name"; ddlOrderStatus.DataBind(); ddlOrderStatus.SelectedValue = order.OrderStatusDescriptorId.ToString(); } } } catch(Exception ex) { Logger.Error(typeof(actions).Name + ".Page_Load", ex); base.MasterPage.MessageCenter.DisplayCriticalMessage(ex.Message); } }
/// <summary> /// Charges the specified order. /// </summary> /// <param name="order">The order.</param> /// <returns></returns> internal Transaction Charge(Order order) { /* * Minimum Requirements * x_version * x_login * x_tran_key * x_type * x_amount * x_card_num * x_exp_date * x_trans_id** * x_auth_code** */ StringBuilder sb = new StringBuilder(); string postData = string.Empty; Currency currency = new Currency(); #region Order Info #region Best Practice Fields GetBestPracticeFields(sb, AuthorizeNetTransactionType.AUTH_CAPTURE); #endregion sb.AppendFormat("&x_customer_ip={0}", HttpUtility.UrlEncode(order.IPAddress)); sb.AppendFormat("&x_invoice_num={0}", HttpUtility.UrlEncode(order.OrderNumber)); sb.AppendFormat("&x_amount={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.Total).ToString())); sb.AppendFormat("&x_freight={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.ShippingAmount).ToString())); sb.AppendFormat("&x_tax={0}", HttpUtility.UrlEncode(GetFormattedAmount(currency, order.TaxTotal).ToString())); #endregion #region Billing Info if (order.BillingAddress != null) { sb.AppendFormat("&x_email={0}", HttpUtility.UrlEncode(order.BillingAddress.Email)); sb.AppendFormat("&x_phone={0}", HttpUtility.UrlEncode(order.BillingAddress.Phone)); sb.AppendFormat("&x_first_name={0}", HttpUtility.UrlEncode(order.BillingAddress.FirstName)); sb.AppendFormat("&x_last_name={0}", HttpUtility.UrlEncode(order.BillingAddress.LastName)); sb.AppendFormat("&x_address={0}", HttpUtility.UrlEncode(order.BillingAddress.Address1)); sb.AppendFormat("&x_city={0}", HttpUtility.UrlEncode(order.BillingAddress.City)); sb.AppendFormat("&x_state={0}", HttpUtility.UrlEncode(order.BillingAddress.StateOrRegion)); sb.AppendFormat("&x_zip={0}", HttpUtility.UrlEncode(order.BillingAddress.PostalCode)); sb.AppendFormat("&x_country={0}", HttpUtility.UrlEncode(order.BillingAddress.Country)); } #endregion #region Shipping Info if (order.ShippingAddress != null) { sb.AppendFormat("&x_ship_to_first_name={0}", HttpUtility.UrlEncode(order.ShippingAddress.FirstName)); sb.AppendFormat("&x_ship_to_last_name={0}", HttpUtility.UrlEncode(order.ShippingAddress.LastName)); sb.AppendFormat("&x_ship_to_address={0}", HttpUtility.UrlEncode(order.ShippingAddress.Address1)); sb.AppendFormat("&x_ship_to_city={0}", HttpUtility.UrlEncode(order.ShippingAddress.City)); sb.AppendFormat("&x_ship_to_state={0}", HttpUtility.UrlEncode(order.ShippingAddress.StateOrRegion)); sb.AppendFormat("&x_ship_to_zip={0}", HttpUtility.UrlEncode(order.ShippingAddress.PostalCode)); sb.AppendFormat("&x_ship_to_country={0}", HttpUtility.UrlEncode(order.ShippingAddress.Country)); } #endregion #region Line Items AppendLineItems(order, sb, currency); #endregion #region Credit Card Info //x_exp_date //x_card_num //x_card_code string expDate = string.Empty; if (order.CreditCardExpirationMonth < 10) { expDate = "0" + order.CreditCardExpirationMonth.ToString(); } else { expDate = order.CreditCardExpirationMonth.ToString(); } if (order.CreditCardExpirationYear > 99) { expDate += order.CreditCardExpirationYear.ToString().Substring(2, 2); } else { expDate += order.CreditCardExpirationYear.ToString(); } sb.AppendFormat("&x_exp_date={0}", HttpUtility.UrlEncode(expDate)); sb.AppendFormat("&x_card_num={0}", HttpUtility.UrlEncode(order.CreditCardNumber)); sb.AppendFormat("&x_card_code={0}", HttpUtility.UrlEncode(order.CreditCardSecurityNumber)); //If the charge fails the first time thru, then we will have some data populated, so we need to try to remove it first if (order.ExtendedProperties.Contains("Validator")) { order.ExtendedProperties.Remove("Validator"); } if (order.ExtendedProperties.Contains("ExpDate")) { order.ExtendedProperties.Remove("ExpDate"); } //now, add them back in order.ExtendedProperties.Add("Validator", order.CreditCardNumber.ToString().Substring((order.CreditCardNumber.Length-4))); order.ExtendedProperties.Add("ExpDate", expDate); order.AdditionalProperties = order.ExtendedProperties.ToXml(); order.Save("System"); #endregion #region Charge It //postData = HttpUtility.UrlEncode(sb.ToString()); postData = sb.ToString(); string response = CoreUtility.SendRequestByPost(AuthorizeServiceUtility.GetAuthorizeServiceEndpoint(this.IsLive), postData); #endregion #region Check it and Build up the Transaction string[] output = response.Split('|'); int counter = 1;//Start @ 1 to keep in sync with docs System.Collections.Hashtable vars = new System.Collections.Hashtable(); foreach (string var in output) { vars.Add(counter, var); counter += 1; } Transaction transaction = null; string responseCode = vars[1].ToString(); if ((responseCode == "2") || (responseCode == "3")) { throw new AuthorizeNetServiceException(vars[4].ToString()); } else { transaction = new Transaction(); transaction.OrderId = order.OrderId; transaction.TransactionTypeDescriptorId = (int)TransactionType.Charge; transaction.PaymentMethod = order.CreditCardType.ToString(); transaction.GatewayName = AUTHORIZENET; transaction.GatewayResponse = vars[1].ToString(); transaction.GatewayTransactionId = vars[7].ToString(); transaction.AVSCode = vars[6].ToString(); transaction.CVV2Code = vars[39].ToString(); decimal grossAmount = 0.00M; bool isParsed = decimal.TryParse(vars[10].ToString(), out grossAmount); transaction.GrossAmount = grossAmount; transaction.TransactionDate = DateTime.Now; transaction.Save("System"); } #endregion return transaction; }
/// <summary> /// Resets the shipping and tax and discount. /// </summary> /// <param name="orderId">The order id.</param> /// <param name="userName">Name of the user.</param> private static void ResetShippingAndTaxAndDiscount(int orderId, string userName) { //Clear Shipping and Tax and Discount if in there Order order = new Order(orderId); if(order.OrderId > 0) { order.ShippingAmount = 0; order.ShippingMethod = string.Empty; foreach(OrderItem orderItem in order.OrderItemCollection) { orderItem.ItemTax = 0; orderItem.DiscountAmount = 0; orderItem.Save(userName); } order.Save(userName); } }
public Transaction Refund(Transaction transaction, Order order) { Transaction refundTransaction = _authorizeService.Refund(transaction, order); return refundTransaction; }