/// <summary> /// Processes the successful transaction, will be called when DIBS server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionID">The transaction id.</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionID, string orderNumber, string acceptUrl, string cancelUrl) { if (cart == null) { return(cancelUrl); } string redirectionUrl; // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from DIBS to payment. payment.TransactionID = transactionID; var purchaseOrder = MakePurchaseOrder(cart, orderNumber); redirectionUrl = UpdateAcceptUrl(purchaseOrder, payment, acceptUrl); return(redirectionUrl); }
public string GetSectionGroupUrl(string groupName) { string url = UriUtil.AddQueryString(HttpContext.Current.Request.RawUrl, "t", HttpContext.Current.Server.UrlEncode(groupName)); url = UriUtil.AddQueryString(url, "p", "1"); return(url); }
public ActionResult Index() { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName + SiteDefinition.Current.StartPage.ID); if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Generic Error"); } var payooConfiguration = new PayooConfiguration(); var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(payooConfiguration.PaymentMethodId)); if (payment == null) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Payment Not Specified"); } var orderNumber = payment.Properties[Constant.PayooOrderNumberPropertyName] as string; if (string.IsNullOrEmpty(orderNumber)) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Payment Not Specified"); } // Redirect customer to receipt page var paymentResult = ExtractPaymentResultFromPayoo(); var cancelUrl = _cmsPaymentPropertyService.GetCancelledPaymentUrl(); // get link to Checkout page cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentmethod", "payoo"); var redirectUrl = cancelUrl; if (VerifyChecksumIsValid(payooConfiguration.ChecksumKey, orderNumber, paymentResult)) { var gateway = new PayooPaymentGateway(); if (paymentResult.IsSuccess) { var acceptUrl = _cmsPaymentPropertyService.GetAcceptedPaymentUrl(); redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, acceptUrl, cancelUrl); } else { var message = paymentResult.Status.Equals("0") ? "Payment failed" : "Payment cancelled"; TempData[Constant.ErrorMessages] = $"{message}. Payoo Message: {paymentResult.ErrorCode}-{paymentResult.ErrorMsg}"; redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, message); } } else { TempData[Constant.ErrorMessages] = "The Payoo checksum is invalid"; } return(Redirect(redirectUrl)); }
/// <summary> /// Processes the successful transaction, was called when Payoo Gateway redirect back. /// </summary> /// <param name="orderGroup">The order group that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The url redirection after process.</returns> public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl) { if (HttpContext.Current == null) { return(cancelUrl); } var cart = orderGroup as ICart; if (cart == null) { // return to the shopping cart page immediately and show error messages return(ProcessUnsuccessfulTransaction(cancelUrl, "Commit Tran Error Cart Null")); } // everything is fine var errorMessages = new List <string>(); var cartCompleted = _payooCartService.DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Place order var purchaseOrder = _payooCartService.MakePurchaseOrder(cart, payment); var redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl); _logger.Info($"Payoo transaction succeeds, redirect end user to {redirectionUrl}"); return(redirectionUrl); }
private SetExpressCheckoutRequestDetailsType SetupExpressCheckoutReqDetailsType(ICart cart, IPayment payment, string orderNumber) { var setExpressChkOutReqDetails = _payPalAPIHelper.CreateExpressCheckoutReqDetailsType(payment, _paymentMethodConfiguration); // This key is sent to PayPal using https so it is not likely it will come from other because // only PayPal knows this key to send back to us var acceptSecurityKey = Utilities.GetAcceptUrlHashValue(orderNumber); var cancelSecurityKey = Utilities.GetCancelUrlHashValue(orderNumber); _notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("PayPalPaymentPage")); var acceptUrl = UriUtil.AddQueryString(_notifyUrl, "accept", "true"); acceptUrl = UriUtil.AddQueryString(acceptUrl, "hash", acceptSecurityKey); var cancelUrl = UriUtil.AddQueryString(_notifyUrl, "accept", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "hash", cancelSecurityKey); setExpressChkOutReqDetails.CancelURL = cancelUrl; setExpressChkOutReqDetails.ReturnURL = acceptUrl; setExpressChkOutReqDetails.PaymentDetails = new List <PaymentDetailsType>() { _payPalAPIHelper.GetPaymentDetailsType(payment, cart, orderNumber, _notifyUrl) }; setExpressChkOutReqDetails.BillingAddress = AddressHandling.ToAddressType(payment.BillingAddress); return(setExpressChkOutReqDetails); }
private PaymentProcessingResult ProcessPaymentCheckout(IPayment payment, ICart cart) { var merchRef = DateTime.Now.Ticks.ToString(); payment.Properties[DataCashMerchantReferencePropertyName] = merchRef; // A unique reference number for each transaction (Min 6, max 30 alphanumeric character) var notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("DataCashPaymentPage")); notifyUrl = UriUtil.AddQueryString(notifyUrl, "accept", "true"); notifyUrl = UriUtil.AddQueryString(notifyUrl, "hash", Utilities.GetSHA256Key(merchRef + "accepted")); var requestDoc = _requestDocumentCreation.CreateDocumentForPaymentCheckout(cart, payment, notifyUrl); var responseDoc = DocumentHelpers.SendTransaction(requestDoc, _dataCashConfiguration.Config); string redirectUrl; if (DocumentHelpers.IsSuccessful(responseDoc)) { redirectUrl = $"{responseDoc.get("Response.HpsTxn.hps_url")}?HPS_SessionID={responseDoc.get("Response.HpsTxn.session_id")}"; payment.Properties[DataCashReferencePropertyName] = responseDoc.get("Response.datacash_reference"); } else { return(PaymentProcessingResult.CreateUnsuccessfulResult(DocumentHelpers.GetErrorMessage(responseDoc))); } _orderRepository.Save(cart); var message = $"---DataCash--. Redirect end user to {redirectUrl}"; _logger.Information(message); return(PaymentProcessingResult.CreateSuccessfulResult(message, redirectUrl)); }
/// <summary> /// Processes the successful transaction, will be called when Dintero server processes /// the payment successfully and redirect back. /// </summary> /// <param name="cart">The cart that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="transactionId">The transaction id.</param> /// <param name="orderNumber">The order number.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The redirection url after processing.</returns> public virtual string ProcessSuccessfulTransaction(ICart cart, IPayment payment, string transactionId, string orderNumber, string acceptUrl, string cancelUrl) { Logger.Debug("DinteroPaymentGateway.ProcessSuccessfulTransaction starting..."); if (cart == null) { return(cancelUrl); } // check whether transaction was authorized by Dintero (prevent order creation on manual hack) var transaction = _requestsHelper.GetTransactionDetails(payment.TransactionID); if (transaction == null) { Logger.Debug($"Unable to get Dintero transaction by id: [{payment.TransactionID}]!"); return(cancelUrl); } Logger.Debug($"Dintero transaction #'{payment.TransactionID}' status = [{transaction.Status}]!"); if (transaction.Status != "AUTHORIZED" && transaction.Status != "ON_HOLD") { return(cancelUrl); } string redirectionUrl; using (var scope = new TransactionScope()) { // Change status of payments to processed. // It must be done before execute workflow to ensure payments which should mark as processed. // To avoid get errors when executed workflow. PaymentStatusManager.ProcessPayment(payment); var isOnHold = transaction.Status == "ON_HOLD"; var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Save the transact from Dintero to payment. payment.TransactionID = transactionId; var purchaseOrder = MakePurchaseOrder(cart, orderNumber, isOnHold); redirectionUrl = UpdateAcceptUrl(purchaseOrder, acceptUrl, isOnHold); // Commit changes scope.Complete(); } return(redirectionUrl); }
public static string UpdateAcceptUrl(IPurchaseOrder purchaseOrder, string acceptUrl, bool isOnHold = false) { var redirectionUrl = UriUtil.AddQueryString(acceptUrl, "success", "true"); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "contactId", purchaseOrder.CustomerId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "orderNumber", purchaseOrder.OrderNumber); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "isOnHold", isOnHold.ToString()); return(redirectionUrl); }
private string CreateRedirectionUrl(IPurchaseOrder purchaseOrder, string acceptUrl) { var redirectionUrl = UriUtil.AddQueryString(acceptUrl, "success", "true"); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "contactId", purchaseOrder.CustomerId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString()); return(redirectionUrl); }
private string CreateRedirectUrl(string expChkoutURLSetting, string token) { var redirectUrl = expChkoutURLSetting; redirectUrl = UriUtil.AddQueryString(redirectUrl, "cmd", "_express-checkout"); redirectUrl = UriUtil.AddQueryString(redirectUrl, "token", token); redirectUrl = UriUtil.AddQueryString(redirectUrl, "useraction", "commit"); return(redirectUrl); }
private string UpdateAcceptUrl(IPurchaseOrder purchaseOrder, IPayment payment, string acceptUrl) { var redirectionUrl = UriUtil.AddQueryString(acceptUrl, "success", "true"); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "contactId", purchaseOrder.CustomerId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "notificationMessage", string.Format(_localizationService.GetString("/OrderConfirmationMail/ErrorMessages/SmtpFailure"), payment.BillingAddress.Email)); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "email", payment.BillingAddress.Email); return(redirectionUrl); }
/// <summary> /// Processes the unsuccessful transaction /// </summary> /// <param name="cancelUrl">The cancel url.</param> /// <param name="errorMessage">The error message.</param> /// <returns>The url redirection after process.</returns> public string ProcessUnsuccessfulTransaction(string cancelUrl, string errorMessage) { if (HttpContext.Current == null) { return(cancelUrl); } _logger.Error($"Payoo transaction failed [{errorMessage}]."); return(UriUtil.AddQueryString(cancelUrl, "message", HttpUtility.UrlEncode(errorMessage))); }
// <summary> // Processes the unsuccessful transaction. // </summary> // <param name = "cancelUrl" > The cancel url.</param> // <param name = "errorMessage" > The error message.</param> // <returns>The url redirection after process.</returns> public string ProcessUnsuccessfulTransaction(string cancelUrl, string errorMessage) { if (HttpContext.Current == null) { return(cancelUrl); } Logger.Error($"Dintero transaction failed [{errorMessage}]."); return(UriUtil.AddQueryString(cancelUrl, "message", errorMessage)); }
private string CreateRedirectionUrl(IPurchaseOrder purchaseOrder, string acceptUrl, string email) { var redirectionUrl = UriUtil.AddQueryString(acceptUrl, "success", "true"); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "contactId", purchaseOrder.CustomerId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString()); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "notificationMessage", string.Format(Utilities.GetLocalizationMessage("/OrderConfirmationMail/ErrorMessages/SmtpFailure"), email)); redirectionUrl = UriUtil.AddQueryString(redirectionUrl, "email", email); return(redirectionUrl); }
public ActionResult Index() { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName); if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("GenericError")); } var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(_dibsRequestHelper.DIBSConfiguration.PaymentMethodId)); if (payment == null) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified")); } InitializeReponse(); var transactionRequest = new TransactionRequest(Request.Form, _dibsRequestHelper.DIBSConfiguration); if (transactionRequest.IsProcessable()) { var cancelUrl = Utilities.GetUrlFromStartPageReferenceProperty("CheckoutPage"); // get link to Checkout page cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentmethod", "dibs"); var gateway = new DIBSPaymentGateway(); var redirectUrl = cancelUrl; if (transactionRequest.IsSuccessful()) { var acceptUrl = Utilities.GetUrlFromStartPageReferenceProperty("DIBSPaymentLandingPage"); redirectUrl = gateway.ProcessSuccessfulTransaction (currentCart, payment, transactionRequest.TransactionId, transactionRequest.OrderId, acceptUrl, cancelUrl); } else { TempData["Message"] = Utilities.Translate("CancelMessage"); redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CancelMessage")); } return(Redirect(redirectUrl)); } var notifyUrl = UriSupport.AbsoluteUrlBySettings(Utilities.GetUrlFromStartPageReferenceProperty("DIBSPaymentPage")); var requestPaymentData = _dibsRequestHelper.CreateRequestPaymentData(payment, currentCart, notifyUrl); return(new RedirectAndPostActionResult(PaymentWindowEntryPoint, requestPaymentData)); }
public ActionResult Index() { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName); if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("GenericError")); } // Get DataCash payment by PaymentMethodName, instead of get the first payment in the list. var dataCashPaymentMethod = DataCashConfiguration.GetDataCashPaymentMethod().PaymentMethod.Rows[0] as Mediachase.Commerce.Orders.Dto.PaymentMethodDto.PaymentMethodRow; var paymentMethodId = dataCashPaymentMethod != null ? dataCashPaymentMethod.PaymentMethodId : Guid.Empty; var payment = currentCart.GetFirstForm().Payments.FirstOrDefault(c => c.PaymentMethodId.Equals(paymentMethodId)); if (payment == null) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified")); } string merchantRef = payment.Properties[DataCashPaymentGateway.DataCashMerchantReferencePropertyName] as string; if (string.IsNullOrEmpty(merchantRef)) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("GenericError")); } // Redirect customer to receipt page var acceptUrl = Utilities.GetUrlFromStartPageReferenceProperty("DataCashPaymentLandingPage"); var cancelUrl = Utilities.GetUrlFromStartPageReferenceProperty("CheckoutPage"); // get link to Checkout page cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentmethod", "DataCash"); var gateway = new DataCashPaymentGateway(); string redirectUrl; if (string.Equals(Request.QueryString["accept"], "true") && Utilities.GetSHA256Key(merchantRef + "accepted") == Request.QueryString["hash"]) { redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, acceptUrl, cancelUrl); } else { redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("GenericError")); } return(Redirect(redirectUrl)); }
public ActionResult Index() { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } var currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName); if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("GenericError")); } var paymentConfiguration = new PayPalConfiguration(); var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(paymentConfiguration.PaymentMethodId)); if (payment == null) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified")); } var orderNumber = payment.Properties[PayPalPaymentGateway.PayPalOrderNumberPropertyName] as string; if (string.IsNullOrEmpty(orderNumber)) { throw new PaymentException(PaymentException.ErrorType.ProviderError, "", Utilities.Translate("PaymentNotSpecified")); } // Redirect customer to receipt page var cancelUrl = Utilities.GetUrlFromStartPageReferenceProperty("CheckoutPage"); // get link to Checkout page cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentmethod", "paypal"); var gateway = new PayPalPaymentGateway(); var redirectUrl = cancelUrl; if (string.Equals(Request.QueryString["accept"], "true") && Utilities.GetAcceptUrlHashValue(orderNumber) == Request.QueryString["hash"]) { var acceptUrl = Utilities.GetUrlFromStartPageReferenceProperty("PayPalPaymentLandingPage"); redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, acceptUrl, cancelUrl); } else if (string.Equals(Request.QueryString["accept"], "false") && Utilities.GetCancelUrlHashValue(orderNumber) == Request.QueryString["hash"]) { TempData["Message"] = Utilities.Translate("CancelMessage"); redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CancelMessage")); } return(Redirect(redirectUrl)); }
/// <summary> /// Processes the successful transaction, was called when redirect back from DataCash. /// </summary> /// <param name="orderGroup">The order group that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The url redirection after process.</returns> public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl) { if (!(orderGroup is ICart cart)) { // return to the shopping cart page immediately and show error messages return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CommitTranErrorCartNull"))); } var orderForm = orderGroup.Forms.FirstOrDefault(f => f.Payments.Contains(payment)); var result = PreAuthenticateRequest(orderGroup, orderForm, payment, out var authenticateCode); if (!result.IsSuccessful && string.IsNullOrEmpty(authenticateCode)) { _logger.Error(result.Message); return(ProcessUnsuccessfulTransaction(cancelUrl, result.Message)); } var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } payment.Properties[DataCashAuthenticateCodePropertyName] = authenticateCode; payment.TransactionID = payment.Properties[DataCashReferencePropertyName] as string; // Save changes var orderReference = _orderRepository.SaveAsPurchaseOrder(orderGroup); var purchaseOrder = _orderRepository.Load <IPurchaseOrder>(orderReference.OrderGroupId); purchaseOrder.OrderNumber = _orderNumberGenerator.GenerateOrderNumber(purchaseOrder); _orderRepository.Save(purchaseOrder); _orderRepository.Delete(orderGroup.OrderLink); var email = payment.BillingAddress.Email; acceptUrl = UriUtil.AddQueryString(acceptUrl, "success", "true"); acceptUrl = UriUtil.AddQueryString(acceptUrl, "contactId", purchaseOrder.CustomerId.ToString()); acceptUrl = UriUtil.AddQueryString(acceptUrl, "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString()); acceptUrl = UriUtil.AddQueryString(acceptUrl, "notificationMessage", string.Format(_localizationService.GetString("/OrderConfirmationMail/ErrorMessages/SmtpFailure"), email)); acceptUrl = UriUtil.AddQueryString(acceptUrl, "email", email); return(acceptUrl); }
public ActionResult Index() { if (Request.QueryString.Count == 0) { // cancel order var cancelUrl = GetUrlFromStartPageReferenceProperty("CheckoutPage"); // get link to Checkout page return(Redirect(cancelUrl)); } var cart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName); var payment = cart.GetFirstForm().Payments.First(); var purchaseOrder = MakePurchaseOrder(cart, Request.QueryString["order_code"]); // redirect to Order Confirmation page var confirmationUrl = GetUrlFromStartPageReferenceProperty("NganLuongConfirmationPage"); // get link to NganLuong confirmation page confirmationUrl = UriUtil.AddQueryString(confirmationUrl, "contactId", purchaseOrder.CustomerId.ToString()); confirmationUrl = UriUtil.AddQueryString(confirmationUrl, "orderNumber", purchaseOrder.OrderLink.OrderGroupId.ToString()); confirmationUrl = UriUtil.AddQueryString(confirmationUrl, "email", payment.BillingAddress.Email); return(Redirect(confirmationUrl)); }
/// <summary> /// Processes the unsuccessful transaction. /// </summary> /// <param name="cancelUrl">The cancel url.</param> /// <param name="errorMessage">The error message.</param> /// <returns>The url redirection after process.</returns> public string ProcessUnsuccessfulTransaction(string cancelUrl, string errorMessage) { return(UriUtil.AddQueryString(cancelUrl, "message", errorMessage)); }
/// <summary> /// Create URL for the previous paging section. /// </summary> /// <returns>Url for previous paging section</returns> public string GetPreviousPagingSectionUrl() { return(UriUtil.AddQueryString(HttpContext.Current.Request.RawUrl, "p", ((PagingSection - 1) * PagingSectionSize).ToString())); }
private string CreateRedirectUrl(IOrderGroup orderGroup) { var orderCode = _orderNumberGenerator.GenerateOrderNumber(orderGroup); var redirectUrl = ConfigurationManager.AppSettings["NganLuong:RedirectUrl"].ToString(); var securePass = ConfigurationManager.AppSettings["NganLuong:SecurePass"].ToString(); var merchantSiteCode = ConfigurationManager.AppSettings["NganLuong:SiteCode"].ToString(); var returnUrl = ConfigurationManager.AppSettings["NganLuong:ReturnUrl"].ToString(); var receiver = ConfigurationManager.AppSettings["NganLuong:Receiver"].ToString(); var transactionInfo = ConfigurationManager.AppSettings["NganLuong:TransactionInfor"].ToString() + orderCode; var payment = orderGroup.GetFirstForm().Payments.First(); var price = payment.Amount.ToString(); var currency = orderGroup.Currency.CurrencyCode; var quantity = "1"; var tax = "0"; var discount = "0"; var feeCal = "0"; var feeShipping = "0"; var orderDescription = ConfigurationManager.AppSettings["NganLuong:OrderDescription"] + orderCode; var billingAddress = payment.BillingAddress; var buyerInfo = $"{billingAddress.FirstName} {billingAddress.LastName}*|*{billingAddress.Email}*|*{billingAddress.DaytimePhoneNumber}*|*{billingAddress.Line1}"; var affiliateCode = ""; var lang = "vi"; var cancelUrl = ConfigurationManager.AppSettings["NganLuong:CancelUrl"].ToString(); var security_code = merchantSiteCode; security_code += " " + returnUrl; security_code += " " + receiver; security_code += " " + transactionInfo; security_code += " " + orderCode; security_code += " " + price; security_code += " " + currency; security_code += " " + quantity; security_code += " " + tax; security_code += " " + discount; security_code += " " + feeCal; security_code += " " + feeShipping; security_code += " " + orderDescription; security_code += " " + buyerInfo; security_code += " " + affiliateCode; security_code += " " + securePass; string secureCodeMd5 = CreateMD5Hash(security_code); redirectUrl = UriUtil.AddQueryString(redirectUrl, "merchant_site_code", merchantSiteCode); redirectUrl = UriUtil.AddQueryString(redirectUrl, "return_url", HttpUtility.UrlEncode(returnUrl).ToLower()); redirectUrl = UriUtil.AddQueryString(redirectUrl, "receiver", HttpUtility.UrlEncode(receiver)); redirectUrl = UriUtil.AddQueryString(redirectUrl, "transaction_info", HttpUtility.UrlEncode(transactionInfo)); redirectUrl = UriUtil.AddQueryString(redirectUrl, "order_code", orderCode); redirectUrl = UriUtil.AddQueryString(redirectUrl, "price", price); redirectUrl = UriUtil.AddQueryString(redirectUrl, "currency", currency); redirectUrl = UriUtil.AddQueryString(redirectUrl, "quantity", quantity); redirectUrl = UriUtil.AddQueryString(redirectUrl, "tax", tax); redirectUrl = UriUtil.AddQueryString(redirectUrl, "discount", discount); redirectUrl = UriUtil.AddQueryString(redirectUrl, "fee_cal", feeCal); redirectUrl = UriUtil.AddQueryString(redirectUrl, "fee_shipping", feeShipping); redirectUrl = UriUtil.AddQueryString(redirectUrl, "order_description", HttpUtility.UrlEncode(orderDescription)); redirectUrl = UriUtil.AddQueryString(redirectUrl, "buyer_info", HttpUtility.UrlEncode(buyerInfo)); redirectUrl = UriUtil.AddQueryString(redirectUrl, "affiliate_code", affiliateCode); redirectUrl = UriUtil.AddQueryString(redirectUrl, "lang", lang); redirectUrl = UriUtil.AddQueryString(redirectUrl, "secure_code", secureCodeMd5); redirectUrl = UriUtil.AddQueryString(redirectUrl, "cancel_url", HttpUtility.UrlEncode(cancelUrl)); return(redirectUrl); }
/// <summary> /// Create URL for a specified paging page. /// </summary> /// <param name="pageNumber">Number of page for which to get a url</param> /// <returns>Url for specified page</returns> public string GetPagingUrl(int pageNumber) { return(UriUtil.AddQueryString(HttpContext.Current.Request.RawUrl, "p", pageNumber.ToString())); }
public ActionResult Index(string error, string transaction_id, string session_id, string merchant_reference, string trackingNumber) { if (PageEditing.PageIsInEditMode) { return(new EmptyResult()); } string redirectUrl = null; Logger.Debug($"HttpContext.Request.RawUrl: {HttpContext.Request.RawUrl}."); Logger.Debug($"Dintero payment error: {error}; transaction_id: {transaction_id}; session_id: {session_id}; merchant_reference: {merchant_reference}; trackingNumber: {trackingNumber}"); var cancelUrl = UriUtil.GetUrlFromStartPageReferenceProperty("DinteroPaymentCancelPage"); var acceptUrl = UriUtil.GetUrlFromStartPageReferenceProperty("DinteroPaymentLandingPage"); cancelUrl = UriUtil.AddQueryString(cancelUrl, "success", "false"); var orderNumber = merchant_reference + trackingNumber; InitializeResponse(); Logger.Debug($"Lock {orderNumber}"); LockHelper.Lock(orderNumber); var gateway = ServiceLocator.Current.GetInstance <DinteroPaymentGateway>(); Logger.Debug($"Dintero payment {orderNumber} start processing"); try { ICart currentCart; if (string.IsNullOrWhiteSpace(session_id)) { // redirect_url is called currentCart = _orderRepository.LoadCart <ICart>(PrincipalInfo.CurrentPrincipal.GetContactId(), Cart.DefaultName); // in case it's redirect from Dintero, but for some reason cookies are not set OR it's redirect from checkout(trackingNumber not empty) if (currentCart == null && (!string.IsNullOrWhiteSpace(transaction_id) || !string.IsNullOrEmpty(trackingNumber))) { var predictableOrderId = string.IsNullOrEmpty(trackingNumber) ? merchant_reference : trackingNumber; Logger.Debug($"Trying to get cart by predictable order Id predictableOrderId: {predictableOrderId}"); currentCart = OrderHelper.GetCartByPredictableOrderId(predictableOrderId); if (currentCart != null) { Logger.Debug($"Cart has been loaded by predictableOrderId: {predictableOrderId}"); } } Logger.Debug($"CurrentPrincipal {PrincipalInfo.CurrentPrincipal.GetContactId()}"); if (currentCart == null) { // check if cart was processed by return_url / callback_url var order = OrderHelper.GetOrderByTrackingNumber(merchant_reference); if (order == null) { Logger.Debug( $"Dintero payment {orderNumber} Cart cannot be loaded!!! contactId: {PrincipalInfo.CurrentPrincipal.GetContactId()}."); throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Cart cannot be loaded!!!"); } Logger.Debug( $"Dintero payment {orderNumber} redirect to accept Url. Order status - {((IOrderGroup) order).OrderStatus}"); return(Redirect(DinteroPaymentGateway.UpdateAcceptUrl(order, acceptUrl, ((IOrderGroup)order).OrderStatus == OrderStatus.OnHold))); } else { Logger.Debug($"CurrentCart.OrderFormId= {currentCart.Forms.First().OrderFormId}"); Logger.Debug($"Principal From Cart {currentCart.CustomerId}"); } if (!currentCart.Forms.Any() || !currentCart.GetFirstForm().Payments.Any()) { Logger.Debug($"Dintero payment {orderNumber} Cart is invalid!"); throw new PaymentException(PaymentException.ErrorType.ProviderError, "", "Cart is invalid!"); } Logger.Debug($"Dintero payment {orderNumber} retrieved cart for current principal"); } else { // if session_id parameter is set it means that it is either Dintero callback was sent (in pair with redirect) // or on_hold transaction was processed // in the first case we need to check whether redirect was processed if yes then skip // in the second we need to release order (check transaction if it is authorised or failed) // check if cart has been already processed by redirect_url currentCart = OrderHelper.GetCartByDinteroSessionId(session_id); if (currentCart == null) { var order = OrderHelper.GetOrderByTrackingNumber(merchant_reference); if (order != null && ((IOrderGroup)order).OrderStatus == OrderStatus.OnHold) { Logger.Debug($"Processing OnHold Order."); var result = gateway.ProcessOnHoldOrder(order.Id, transaction_id); if (result == null) { Logger.Debug("Unable to release OnHold order."); } else { Logger.Debug($"Processing OnHold Order completed: {result.OrderStatus}."); } } else { Logger.Debug($"Dintero payment {orderNumber} cart is already processed"); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); } Logger.Debug($"CurrentPrincipal {currentCart.CustomerId}"); Logger.Debug($"CurrentCart.OrderFormId= {currentCart.Forms.First().OrderFormId}"); Logger.Debug($"Dintero payment {orderNumber} cart as retrieved by session Id"); } var formPayments = currentCart.Forms.SelectMany(f => f.Payments).Select(p => p.PaymentId); var payment = currentCart.Forms.SelectMany(f => f.Payments).FirstOrDefault(c => c.PaymentMethodId.Equals(_requestsHelper.Configuration.PaymentMethodId)); if (payment == null) { Logger.Debug($"Dintero payment {orderNumber} payment is null"); throw new PaymentException(PaymentException.ErrorType.ProviderError, "", $"Payment was not specified ({_requestsHelper.Configuration.PaymentMethodId}). Form payments: {string.Join(";", formPayments)}"); } if (string.IsNullOrWhiteSpace(transaction_id) && string.IsNullOrWhiteSpace(error)) { var sessionData = _requestsHelper.CreateTransaction(payment, currentCart, trackingNumber); if (sessionData != null) { var cart = _orderRepository.LoadCart <Cart>(currentCart.CustomerId, Cart.DefaultName); cart[DinteroConstants.DinteroSessionMetaField] = sessionData.SessionId; cart.OrderForms[0][DinteroConstants.DinteroSessionMetaField] = sessionData.SessionId; cart.AcceptChanges(); Logger.Debug($"Dintero payment {orderNumber} redirect to checkout"); return(Redirect(sessionData.CheckoutUrl)); } Logger.Debug($"Dintero payment {orderNumber} redirect to cancel"); return(Redirect(cancelUrl)); } cancelUrl = UriUtil.AddQueryString(cancelUrl, "paymentMethod", "dintero"); if (string.IsNullOrWhiteSpace(error) && !string.IsNullOrWhiteSpace(transaction_id) && !string.IsNullOrWhiteSpace(merchant_reference)) { payment.TransactionID = transaction_id; payment.TransactionType = TransactionType.Authorization.ToString(); redirectUrl = gateway.ProcessSuccessfulTransaction(currentCart, payment, transaction_id, merchant_reference, acceptUrl, cancelUrl); } else { TempData["Message"] = error; redirectUrl = gateway.ProcessUnsuccessfulTransaction(cancelUrl, error); } Logger.Debug($"Dintero payment {orderNumber} call post authorize"); DinteroPaymentGateway.PostProcessPayment.PostAuthorize(payment, error, transaction_id, merchant_reference); } catch (Exception e) { Logger.Error($"Dintero payment {orderNumber} failed {e}"); } finally { Logger.Debug("Release"); LockHelper.Release(orderNumber); } if (string.IsNullOrWhiteSpace(session_id)) { Logger.Debug($"Dintero payment {orderNumber} redirect to {redirectUrl}"); return(Redirect(redirectUrl)); } return(new HttpStatusCodeResult(HttpStatusCode.OK)); }
/// <summary> /// Constructs a url for a section group /// </summary> /// <param name="groupName">Name of group</param> /// <returns>Url</returns> public string GetSectionGroupUrl(string groupName) { return(UriUtil.AddQueryString(RemoveQueryStringByKey(HttpContext.Current.Request.Url.AbsoluteUri, "p"), "t", HttpContext.Current.Server.UrlEncode(groupName))); }
/// <summary> /// Processes the successful transaction, was called when PayPal.com redirect back. /// </summary> /// <param name="orderGroup">The order group that was processed.</param> /// <param name="payment">The order payment.</param> /// <param name="acceptUrl">The redirect url when finished.</param> /// <param name="cancelUrl">The redirect url when error happens.</param> /// <returns>The url redirection after process.</returns> public string ProcessSuccessfulTransaction(IOrderGroup orderGroup, IPayment payment, string acceptUrl, string cancelUrl) { if (HttpContext.Current == null) { return(cancelUrl); } var cart = orderGroup as ICart; if (cart == null) { // return to the shopping cart page immediately and show error messages return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("CommitTranErrorCartNull"))); } string redirectionUrl; var getDetailRequest = new GetExpressCheckoutDetailsRequestType { Token = payment.Properties[PayPalExpTokenPropertyName] as string // Add request-specific fields to the request. }; // Execute the API operation and obtain the response. var caller = PayPalAPIHelper.GetPayPalAPICallerServices(_paymentMethodConfiguration); var getDetailsResponse = caller.GetExpressCheckoutDetails(new GetExpressCheckoutDetailsReq { GetExpressCheckoutDetailsRequest = getDetailRequest }); var errorCheck = _payPalAPIHelper.CheckErrors(getDetailsResponse); if (!string.IsNullOrEmpty(errorCheck)) { // unsuccessful get detail call _logger.Error(errorCheck); return(ProcessUnsuccessfulTransaction(cancelUrl, PaymentTransactionFailedMessage)); } var expressCheckoutDetailsResponse = getDetailsResponse.GetExpressCheckoutDetailsResponseDetails; // get commerceOrderId from what we put to PayPal instead of getting from cookie payment.Properties[PayPalOrderNumberPropertyName] = expressCheckoutDetailsResponse.InvoiceID; //process details sent from paypal, changing addresses if required var emptyAddressMsg = string.Empty; //process billing address var payPalBillingAddress = expressCheckoutDetailsResponse.BillingAddress; if (payPalBillingAddress != null && AddressHandling.IsAddressChanged(payment.BillingAddress, payPalBillingAddress)) { emptyAddressMsg = _payPalAPIHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalBillingAddress, payment.BillingAddress, CustomerAddressTypeEnum.Billing, "CommitTranErrorPayPalBillingAddressEmpty"); if (!string.IsNullOrEmpty(emptyAddressMsg)) { return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg)); } } //process shipping address var payPalShippingAddress = expressCheckoutDetailsResponse.PaymentDetails[0].ShipToAddress; if (payPalShippingAddress != null && AddressHandling.IsAddressChanged(cart.GetFirstShipment().ShippingAddress, payPalShippingAddress)) { //when address was changed on PayPal site, it might cause changing tax value changed and changing order value also. var taxValueBefore = cart.GetTaxTotal(_orderGroupCalculator); var shippingAddress = orderGroup.CreateOrderAddress("address"); emptyAddressMsg = _payPalAPIHelper.ProcessOrderAddress(expressCheckoutDetailsResponse.PayerInfo, payPalShippingAddress, shippingAddress, CustomerAddressTypeEnum.Shipping, "CommitTranErrorPayPalShippingAddressEmpty"); if (!string.IsNullOrEmpty(emptyAddressMsg)) { return(ProcessUnsuccessfulTransaction(cancelUrl, emptyAddressMsg)); } cart.GetFirstShipment().ShippingAddress = shippingAddress; var taxValueAfter = cart.GetTaxTotal(_orderGroupCalculator); if (taxValueBefore != taxValueAfter) { _orderRepository.Save(cart); // Saving cart to submit order address changed. return(ProcessUnsuccessfulTransaction(cancelUrl, Utilities.Translate("ProcessPaymentTaxValueChangedWarning"))); } } // Add request-specific fields to the request. // Create the request details object. var doExpressChkOutPaymentReqDetails = CreateExpressCheckoutPaymentRequest(getDetailsResponse, orderGroup, payment); // Execute the API operation and obtain the response. var doCheckOutResponse = caller.DoExpressCheckoutPayment(new DoExpressCheckoutPaymentReq { DoExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressChkOutPaymentReqDetails) }); errorCheck = _payPalAPIHelper.CheckErrors(doCheckOutResponse); if (!string.IsNullOrEmpty(errorCheck)) { // unsuccessful doCheckout response _logger.Error(errorCheck); return(ProcessUnsuccessfulTransaction(cancelUrl, PaymentTransactionFailedMessage)); } // everything is fine, this is a flag to tell ProcessPayment know about this case: redirect back from PayPal with accepted payment var errorMessages = new List <string>(); var cartCompleted = DoCompletingCart(cart, errorMessages); if (!cartCompleted) { return(UriUtil.AddQueryString(cancelUrl, "message", string.Join(";", errorMessages.Distinct().ToArray()))); } // Place order var purchaseOrder = MakePurchaseOrder(doCheckOutResponse, cart, payment); redirectionUrl = CreateRedirectionUrl(purchaseOrder, acceptUrl, payment.BillingAddress.Email); _logger.Information($"PayPal transaction succeeds, redirect end user to {redirectionUrl}"); return(redirectionUrl); }