/// <summary> /// Handles successfull authorization of delayed payment. /// </summary> /// <remarks> /// When <see cref="PaymentResultInfo.PaymentApprovalUrl"/> is set redirect to this url is performed. /// </remarks> private void HandleDelayedPaymentResult(PaymentResultInfo result) { if (result == null) { return; } if (!result.PaymentIsFailed && !string.IsNullOrEmpty(result.PaymentApprovalUrl)) { URLHelper.Redirect(result.PaymentApprovalUrl); } if (result.PaymentIsAuthorized && !result.PaymentIsFailed && !string.IsNullOrEmpty(RedirectAfterPurchase)) { URLHelper.Redirect(UrlResolver.ResolveUrl(RedirectAfterPurchase)); } }
public void SetPaymentResult_PaymentSuccess() { var order = CreateOrderFromNewCart(); var result = new PaymentResultInfo { PaymentIsCompleted = true }; order.SetPaymentResult(result); CMSAssert.All( () => Assert.IsTrue(order.IsPaid, "Order payment is successful but order is not marked as paid."), () => Assert.AreEqual(order.StatusID, Factory.PaymentMethodDefault.PaymentOptionSucceededOrderStatusID, "Order payment is successful but order status is not correctly updated."), () => Assert.NotNull(order.PaymentResult, "Order payment result is null.") ); }
public void SetPaymentResult_PaymentCaptured() { var order = CreateOrderFromNewCart(); var originalStatusID = order.StatusID; var result = new PaymentResultInfo { PaymentIsCompleted = false, PaymentStatusName = "Money captured" }; order.SetPaymentResult(result); CMSAssert.All( () => Assert.IsFalse(order.IsPaid, "Order payment is captured but order is marked as paid."), () => Assert.AreEqual(order.StatusID, originalStatusID, "Order status should not be updated"), () => Assert.NotNull(order.PaymentResult, "Order payment result is null.") ); }
public void SetPaymentResultWithoutStatus_PaymentFailed() { var order = CreateOrderFromNewCart(); order.OriginalOrder.OrderPaymentOptionID = mPaymentOptionWithoutStatus.PaymentOptionID; var originalstatusId = order.StatusID; var result = new PaymentResultInfo { PaymentIsCompleted = false, }; order.SetPaymentResult(result, true); CMSAssert.All( () => Assert.IsFalse(order.IsPaid, "Order payment failed but order is marked as paid."), () => Assert.AreEqual(order.StatusID, originalstatusId, "Order payment was changed."), () => Assert.NotNull(order.PaymentResult, "Order payment result is null.") ); }
/// <summary> /// Sets the payment result to the <see cref="Order"/> object. /// </summary> /// <remarks> /// In case the <see cref="PaymentResultInfo.PaymentIsCompleted"/> property of <paramref name="paymentResult"/> is true, the order is marked as paid and the order status is set according to <see cref="PaymentOptionInfo.PaymentOptionSucceededOrderStatusID"/>. /// The <see cref="PaymentResultInfo.PaymentIsFailed"/> property value of <paramref name="paymentResult"/> indicates if the order is marked as unpaid and the order status is set according to <see cref="PaymentOptionInfo.PaymentOptionFailedOrderStatusID"/>. /// </remarks> /// <param name="paymentResult"><see cref="PaymentResultInfo"/> object representing an original Kentico payment result object from which the model is created.</param> public void SetPaymentResult(PaymentResultInfo paymentResult) { if (paymentResult == null) { throw new ArgumentNullException(nameof(paymentResult)); } if (paymentResult.PaymentIsCompleted && paymentResult.PaymentIsFailed) { throw new InvalidOperationException("Order payment failed but paymentResult.PaymentIsCompleted is true"); } OriginalOrder.OrderPaymentResult = paymentResult; if (!paymentResult.PaymentIsCompleted && !paymentResult.PaymentIsFailed) { Save(); return; } OriginalOrder.UpdateOrderStatus(paymentResult); Save(); }
/// <summary> /// Sets the payment result to the <see cref="Order"/> object. /// </summary> /// <remarks> /// In case the <see cref="PaymentResultInfo.PaymentIsCompleted"/> property of <paramref name="paymentResult"/> is true, the order is marked as paid and the order status is set according to <see cref="PaymentOptionInfo.PaymentOptionSucceededOrderStatusID"/>. /// The <paramref name="paymentFailed"/> parameter indicates if the order is marked as unpaid and the order status is set according to <see cref="PaymentOptionInfo.PaymentOptionFailedOrderStatusID"/>. /// </remarks> /// <param name="paymentResult"><see cref="PaymentResultInfo"/> object representing an original Kentico payment result object from which the model is created.</param> /// <param name="paymentFailed">Indicates if the payment failed.</param> public void SetPaymentResult(PaymentResultInfo paymentResult, bool paymentFailed = false) { if (paymentResult == null) { throw new ArgumentNullException(nameof(paymentResult)); } if (paymentResult.PaymentIsCompleted && paymentFailed) { throw new InvalidOperationException("Order payment failed but paymentResult.PaymentIsCompleted is true"); } OriginalOrder.OrderPaymentResult = paymentResult; var payment = PaymentOptionInfoProvider.GetPaymentOptionInfo(OriginalOrder.OrderPaymentOptionID); if (paymentResult.PaymentIsCompleted) { var successStatusId = payment?.PaymentOptionSucceededOrderStatusID ?? 0; if (successStatusId > 0) { OriginalOrder.OrderStatusID = successStatusId; } OriginalOrder.OrderIsPaid = true; } if (paymentFailed) { var failedStatusId = payment?.PaymentOptionFailedOrderStatusID ?? 0; if (failedStatusId > 0) { OriginalOrder.OrderStatusID = failedStatusId; } OriginalOrder.OrderIsPaid = false; } Save(); }
//EndDocSection:DifferentShippingAddress private object DummyEcommerceMethod() { IPricingService pricingService = null; ShoppingCart shoppingCart = null; SKUInfo productSku = null; Variant variant = null; IVariantRepository mVariantRepository = null; SKUTreeNode product = null; SKUInfo sku = null; DummyViewModel model = null; Order order = null; PaymentResultInfo result = null; //DocSection:CalculatePriceOptions ProductPrice productPrice = pricingService.CalculatePrice(productSku, shoppingCart); //EndDocSection:CalculatePriceOptions //DocSection:FormatPriceOptions decimal price = 5.50M; string formattedPrice = shoppingCart.Currency.FormatPrice(price); //EndDocSection:FormatPriceOptions //DocSection:VariantDisplayImg var response = new { // ... imagePath = Url.Content(variant.ImagePath) }; //EndDocSection:VariantDisplayImg //DocSection:DisplayAttributeSelection // Gets the cheapest variant from the product List <Variant> variants = mVariantRepository.GetByProductId(product.NodeSKUID).OrderBy(v => v.VariantPrice).ToList(); Variant cheapestVariant = variants.FirstOrDefault(); // Gets the product's option categories. IEnumerable <ProductOptionCategory> categories = mVariantRepository.GetVariantOptionCategories(sku.SKUID); // Gets the cheapest variant's selected attributes IEnumerable <ProductOptionCategoryViewModel> variantCategories = cheapestVariant?.ProductAttributes.Select( option => new ProductOptionCategoryViewModel(option.SKUID, categories.FirstOrDefault(c => c.ID == option.SKUOptionCategoryID))); //EndDocSection:DisplayAttributeSelection //DocSection:ShippingIsDifferent if (model.ShippingAddressIsDifferent) { // ... } //EndDocSection:ShippingIsDifferent //DocSection:DifferentPaymentMethods if (shoppingCart.PaymentMethod.PaymentOptionName.Equals("PaymentMethodCodeName")) { return(RedirectToAction("ActionForPayment", "MyPaymentGateway")); } //EndDocSection:DifferentPaymentMethods //DocSection:SetPaymentResult order.SetPaymentResult(result); //EndDocSection:SetPaymentResult //DocSection:RedirectForManualPayment return(RedirectToAction("ThankYou", new { orderID = order.OrderID })); //EndDocSection:RedirectForManualPayment }
//EndDocSection:DifferentShippingAddress private object DummyEcommerceMethod() { ShoppingCartInfo shoppingCart = null; SKUInfo productSku = null; ProductVariant variant = null; SKUTreeNode product = null; SKUInfo sku = null; DummyViewModel model = null; OrderInfo order = null; PaymentResultInfo result = null; //DocSection:CalculatePriceOptions ProductCatalogPrices productPrice = Service.Resolve <ICatalogPriceCalculatorFactory>() .GetCalculator(shoppingCart.ShoppingCartSiteID) .GetPrices(productSku, Enumerable.Empty <SKUInfo>(), shoppingCart); //EndDocSection:CalculatePriceOptions //DocSection:FormatPriceOptions decimal price = 5.50M; string formattedPrice = String.Format(shoppingCart.Currency.CurrencyFormatString, price); //EndDocSection:FormatPriceOptions //DocSection:VariantDisplayImg var response = new { // ... imagePath = Url.Content(variant.Variant.SKUImagePath) }; //EndDocSection:VariantDisplayImg //DocSection:DisplayAttributeSelection // Gets the cheapest variant of the product List <ProductVariant> variants = VariantHelper.GetVariants(product.NodeSKUID).OnSite(SiteContext.CurrentSiteID).ToList() .Select(s => new ProductVariant(s.SKUID)) .OrderBy(v => v.Variant.SKUPrice).ToList(); ProductVariant cheapestVariant = variants.FirstOrDefault(); // Gets the product's option categories IEnumerable <OptionCategoryInfo> categories = VariantHelper.GetProductVariantsCategories(sku.SKUID).ToList(); // Gets the cheapest variant's selected attributes IEnumerable <ProductOptionCategoryViewModel> variantCategories = cheapestVariant?.ProductAttributes.Select( option => new ProductOptionCategoryViewModel(sku.SKUID, option.SKUID, categories.FirstOrDefault(c => c.CategoryID == option.SKUOptionCategoryID))); //EndDocSection:DisplayAttributeSelection //DocSection:ShippingIsDifferent if (model.IsShippingAddressDifferent) { // ... } //EndDocSection:ShippingIsDifferent //DocSection:DifferentPaymentMethods if (shoppingCart.PaymentOption.PaymentOptionName.Equals("PaymentMethodCodeName")) { return(RedirectToAction("ActionForPayment", "MyPaymentGateway")); } //EndDocSection:DifferentPaymentMethods //DocSection:SetPaymentResult order.UpdateOrderStatus(result); //EndDocSection:SetPaymentResult //DocSection:RedirectForManualPayment return(RedirectToAction("ThankYou", new { orderID = order.OrderID })); //EndDocSection:RedirectForManualPayment }
public void processResults() { int orderKey = 0; string orderKeyReturn = QueryHelper.GetString("orderKey", ""); string orderStatus = QueryHelper.GetString("paymentStatus", ""); if (orderKeyReturn != "" && orderStatus != "") { orderKeyReturn = orderKeyReturn.Replace(WebConfigurationManager.AppSettings["MerchantCode"], ""); orderKeyReturn = orderKeyReturn.Replace("", "");//ID orderKeyReturn = orderKeyReturn.Replace("^", ""); orderKey = int.Parse(orderKeyReturn); //Can be uncommented for debugging purposes //Response.Write("oderkey: " + orderKey + "<br><br>"); //Response.Write("status: " + orderStatus + "<br><br>"); //Response.Write("orderID: " + orderKey + "<br><br>"); PaymentResultInfo PRI; //Transaction Successful - Add your code to process a successful transaction here (before the break httpa.Response.Redirect). OrderInfo order = OrderInfoProvider.GetOrderInfo(orderKey); if (order != null) { OrderStatusInfo OSI; switch (orderStatus.ToUpper()) { case "AUTHORISED": CMS.SettingsProvider.InfoDataSet<OrderItemInfo> oii = OrderItemInfoProvider.GetOrderItems(orderKey); OSI = OrderStatusInfoProvider.GetOrderStatusInfo("Complete", CMSContext.CurrentSiteName); PRI = new PaymentResultInfo(); PRI.PaymentDate = DateTime.Now; PRI.PaymentIsCompleted = true; PRI.PaymentStatusValue = "Order & Payment Complete."; PRI.PaymentTransactionID = orderKey.ToString(); order.OrderStatusID = OSI.StatusID; order.OrderPaymentResult = PRI; order.OrderIsPaid = true; order.Update(); pnlResult.Visible = true; ltlDonationResultTitle.Text = oii.Items[0].OrderItemSKUName; double giftAidTotal; giftAidTotal = (order.OrderTotalPrice / 100) * 25; if (ValidationHelper.GetBoolean(order.GetValue("IsGiftAid"), false)) { giftAidTotal = Math.Truncate(giftAidTotal * 100) / 100; } else { giftAidTotal = 0; } double orderPriceTotal = Math.Truncate(order.OrderTotalPrice * 100) / 100; double total = 0; litDonationAmmountRestult.Text = order.OrderTotalPrice.ToString("0.00"); if (ValidationHelper.GetBoolean(order.GetValue("IsGiftAid"), false) == true && order.OrderTotalPrice != 0) { litGiftAidResult.Text = giftAidTotal.ToString("0.00"); } else { litGiftAidResult.Text = "0.00"; } //Show total price total = giftAidTotal + orderPriceTotal; litTotalResult.Text = total.ToString("0.00"); //Send finance email MacroResolver mcr = MacroResolver.GetInstance(); mcr.AddDynamicParameter("OrderCode", order.OrderID.ToString()); mcr.AddDynamicParameter("DonationAmount", total.ToString("0.00")); mcr.AddDynamicParameter("ImageChecked", order.GetStringValue("ImagePath", "") != "" ? true : false); mcr.AddDynamicParameter("CommentChecked", order.GetBooleanValue("AllowUseOfComment", false)); SendEmail(mcr, "Donation-Finance", "*****@*****.**"); break; case "CANCELLED": OSI = OrderStatusInfoProvider.GetOrderStatusInfo("Failed", CMSContext.CurrentSiteName); if (OSI != null) { PRI = new PaymentResultInfo(); PRI.PaymentDate = DateTime.Now; PRI.PaymentIsCompleted = false; PRI.PaymentStatusValue = "Cancelled"; PRI.PaymentTransactionID = orderKey.ToString(); order.OrderStatusID = OSI.StatusID; order.OrderPaymentResult = PRI; order.OrderIsPaid = false; order.Update(); pnlResultCancelled.Visible = true; litErrorCancelled.Text = "Your order was Cancelled."; } break; //case "PENDING": // pnlResultError.Visible = true; // litReturnError.Text = "Your order is pending."; // break; default: OSI = OrderStatusInfoProvider.GetOrderStatusInfo("Failed", CMSContext.CurrentSiteName); if (OSI != null) { PRI = new PaymentResultInfo(); PRI.PaymentDate = DateTime.Now; PRI.PaymentIsCompleted = false; PRI.PaymentStatusValue = "failed"; PRI.PaymentTransactionID = orderKey.ToString(); order.OrderStatusID = OSI.StatusID; order.OrderPaymentResult = PRI; order.OrderIsPaid = false; order.Update(); pnlResultError.Visible = true; litReturnError.Text = "Error detected."; } break; } } else { pnlResultError.Visible = true; litReturnError.Text = "Your order was not found. Please contact a member of support."; } } }
private void DoTraitement() { var ordeID = Request.QueryString["ORDERID"]; var order = OrderInfoProvider.GetOrderInfo(Int32.Parse(ordeID)); if (order == null) { return; } var transactionID = Request.QueryString["PAYID"]; string transactionDate = Request.QueryString["TRXDATE"]; var modePaiement = Request.QueryString["PM"]; var statutCode = Request.QueryString["STATUS"]; var ncerror = Request.QueryString["NCERROR"]; var sha = Request.QueryString["SHASIGN"]; var tab = transactionDate.Split('/'); var month = Int32.Parse(tab[0]); var day = Int32.Parse(tab[1]); var year = Int32.Parse(tab[2]); var date = new DateTime(year, month, day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second); var payementResult = new PaymentResultInfo() { PaymentDate = GetOgoneTransactionDate(transactionDate), PaymentTransactionID = transactionID, PaymentIsCompleted = true, PaymentStatusName = GetOgoneStatutLibelle(statutCode), PaymentMethodName = "Ogone" }; var paymentItem = new PaymentResultItemInfo() { Header = "Payment by", Name = "PaymentSytem", Text = modePaiement, Value = modePaiement }; payementResult.SetPaymentResultItemInfo(paymentItem); order.OrderPaymentResult = payementResult; if (statutCode != "1" && statutCode != "0") { order.OrderStatusID = OrderStatusInfoProvider.GetOrderStatusInfo("PaymentReceived", SiteContext.CurrentSiteName).StatusID; order.SetValue("OrderStatus", "1"); } else { order.OrderStatusID = OrderStatusInfoProvider.GetOrderStatusInfo("Canceled", SiteContext.CurrentSiteName).StatusID; order.SetValue("OrderStatus", "2"); } OrderHelper.CreateCustomInvoiceHelper(Int32.Parse(ordeID)); OrderInfoProvider.SetOrderInfo(order); }
public async Task <IActionResult> Payment([FromBody] AcceptJSDataModel model) { ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment = AuthorizeNet.Environment.SANDBOX; // define the merchant information (authentication / transaction id) ApiOperationBase <ANetApiRequest, ANetApiResponse> .MerchantAuthentication = new merchantAuthenticationType() { name = AcceptJSOptions.AcceptJSApiLoginID(), ItemElementName = ItemChoiceType.transactionKey, Item = AcceptJSOptions.AcceptJSApiTransactionKey() }; var opaqueData = new opaqueDataType() { dataDescriptor = model.DataDescriptor, dataValue = model.DataValue }; var paymentType = new paymentType() { Item = opaqueData }; var order = (await OrderInfoProvider.Get().WhereEquals(nameof(OrderInfo.OrderGUID), model.OrderGUID).TopN(1).GetEnumerableTypedResultAsync()).FirstOrDefault(); var orderItems = await OrderItemInfoProvider.Get().WhereEquals(nameof(OrderItemInfo.OrderItemOrderID), order.OrderID).GetEnumerableTypedResultAsync(); var customer = await CustomerInfoProvider.GetAsync(order.OrderCustomerID); var lineItems = new List <lineItemType>(); foreach (var item in orderItems) { lineItems.Add(new lineItemType() { itemId = item.OrderItemID.ToString(), name = item.OrderItemSKUName, unitPrice = item.OrderItemUnitPrice, quantity = item.OrderItemUnitCount }); } var state = await StateInfoProvider.GetAsync(order.OrderBillingAddress.AddressStateID); var billingAddress = new customerAddressType { firstName = customer.CustomerFirstName, lastName = customer.CustomerLastName, address = order.OrderBillingAddress.AddressLine1, city = order.OrderBillingAddress.AddressCity, zip = order.OrderBillingAddress.AddressZip, state = state.StateCode }; state = await StateInfoProvider.GetAsync(order.OrderShippingAddress.AddressStateID); var shippingAddress = new customerAddressType { firstName = customer.CustomerFirstName, lastName = customer.CustomerLastName, address = order.OrderShippingAddress.AddressLine1, city = order.OrderShippingAddress.AddressCity, zip = order.OrderShippingAddress.AddressZip, state = state.StateCode }; var mainCurrency = Service.Resolve <ISiteMainCurrencySource>().GetSiteMainCurrency(order.OrderSiteID); var orderCurrency = await CurrencyInfoProvider.GetAsync(order.OrderCurrencyID); var currencyConverter = Service.Resolve <ICurrencyConverterService>(); var rateToMainCurrency = currencyConverter.GetExchangeRate(orderCurrency.CurrencyCode, mainCurrency.CurrencyCode, order.OrderSiteID); var roundingService = Service.Resolve <IRoundingServiceFactory>().GetRoundingService(order.OrderSiteID); var shipping = roundingService.Round(currencyConverter.ApplyExchangeRate(order.OrderTotalShipping, rateToMainCurrency), mainCurrency); var tax = roundingService.Round(currencyConverter.ApplyExchangeRate(order.OrderTotalTax, rateToMainCurrency), mainCurrency); var transactionRequest = new transactionRequestType { transactionType = transactionTypeEnum.authCaptureTransaction.ToString(), amount = order.OrderGrandTotalInMainCurrency, shipping = new extendedAmountType() { amount = shipping, name = "Shipping", description = "Total Order Shipping" }, tax = new extendedAmountType() { amount = tax, name = "Tax", description = "Total Order Tax" }, payment = paymentType, billTo = billingAddress, shipTo = shippingAddress, lineItems = lineItems.ToArray(), poNumber = order.OrderID.ToString() }; var request = new createTransactionRequest { transactionRequest = transactionRequest }; // instantiate the controller that will call the service var controller = new createTransactionController(request); controller.Execute(); // get the response from the service (errors contained if any) var response = controller.GetApiResponse(); // validate response if (response != null) { if (response.messages.resultCode == messageTypeEnum.Ok) { if (response.transactionResponse.messages != null) { if (order != null && response.transactionResponse.responseCode == "1") { // Creates a payment result object that will be viewable in Xperience PaymentResultInfo result = new PaymentResultInfo { PaymentDate = DateTime.Now, PaymentDescription = "Successfully created transaction with Transaction ID: " + response.transactionResponse.transId, PaymentIsCompleted = response.transactionResponse.responseCode == "1", PaymentTransactionID = response.transactionResponse.transId, PaymentStatusValue = $"Response Code: {response.transactionResponse.responseCode}, Message Code: {response.transactionResponse.messages[0].code}, Description: { response.transactionResponse.messages[0].description}", PaymentMethodName = "AcceptJS" }; // Saves the payment result to the database order.UpdateOrderStatus(result); return(new JsonResult(new { PaymentSuccessful = true })); } else { return(new JsonResult(new { Message = $"Message Code: { response.transactionResponse.messages[0].code}, Description: {response.transactionResponse.messages[0].description}" })); } } else { if (response.transactionResponse.errors != null) { return(new JsonResult(new { Message = $"Failed Transaction. {response.transactionResponse.errors[0].errorCode}: {response.transactionResponse.errors[0].errorText}" })); } return(new JsonResult(new { Message = "Failed Transaction." })); } } else { if (response.transactionResponse != null && response.transactionResponse.errors != null) { return(new JsonResult(new { Message = $"Failed Transaction. {response.transactionResponse.errors[0].errorCode}: {response.transactionResponse.errors[0].errorText}" })); } else { return(new JsonResult(new { Message = $"Failed Transaction. {response.messages.message[0].code}: {response.messages.message[0].text}" })); } } } else { return(new JsonResult(new { Message = ResHelper.GetString("AcceptJS.ResponseNull") })); } }