private void UpdateOrderPaymentStatus(BaseTransactionResult result, Order order)
        {
            switch (result.TransactionStatus.Value)
            {
            case Enumerations.TransactionStatusCode.Sale:
            case Enumerations.TransactionStatusCode.Capture:     // Capture should not happen here
                order.CaptureTransactionId = result.TransactionNumber;
                _orderService.UpdateOrder(order);
                // Mark order as paid
                if (result.TransactionStatus == Enumerations.TransactionStatusCode.Sale &&
                    _orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                }
                break;

            case Enumerations.TransactionStatusCode.Authorize:
                order.AuthorizationTransactionId = result.TransactionNumber;
                _orderService.UpdateOrder(order);
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
                break;
            }
        }
예제 #2
0
        public ActionResult Return(FormCollection form)
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.Assist") as AssistPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) ||
                !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Assist module cannot be loaded");
            }

            var order = _orderService.GetOrderById(_webHelper.QueryString <int>("ordernumber"));

            if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
            {
                return(new HttpUnauthorizedResult());
            }

            if (_assistPaymentSettings.AuthorizeOnly)
            {
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
            }
            else
            {
                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                }
            }

            return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
        }
예제 #3
0
        public ActionResult IPNHandler(FormCollection form)
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.CyberSource") as CyberSourcePaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("CyberSource module cannot be loaded");
            }

            var reasonCode = form["reasonCode"];
            int orderId;

            if (HostedPaymentHelper.ValidateResponseSign(form, _cyberSourcePaymentSettings.PublicKey) &&
                !string.IsNullOrEmpty(reasonCode) && reasonCode.Equals("100") &&
                int.TryParse(form["orderNumber"], out orderId))
            {
                var order = _orderService.GetOrderById(orderId);
                if (order != null && _orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
            }

            return(Content(""));
        }
예제 #4
0
        private ActionResult UpdateOrderStatus(Order order, string status)
        {
            status = status.ToUpper();
            var textToResponse = "Your order has been paid";

            switch (status)
            {
            case "CANCELED":
            {
                //mark order as canceled
                if ((order.PaymentStatus == PaymentStatus.Paid || order.PaymentStatus == PaymentStatus.Authorized) &&
                    _orderProcessingService.CanCancelOrder(order))
                {
                    _orderProcessingService.CancelOrder(order, true);
                }

                textToResponse = "Your order has been canceled";
            }
            break;

            case "AUTHORIZED":
            {
                //mark order as authorized
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
                textToResponse = "Your order has been authorized";
            }
            break;

            case "PAID":
            {
                //mark order as paid
                if (_orderProcessingService.CanMarkOrderAsPaid(order) && status.ToUpper() == "PAID")
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                }
            }
            break;

            default:
            {
                return(GetResponse("Unsupported status"));
            }
            }

            return(GetResponse(textToResponse, true));
        }
        private void ProcessOrderStateChangeNotification(string xmlData)
        {
            try
            {
                var changeOrder = (OrderStateChangeNotification)EncodeHelper.Deserialize(xmlData, typeof(OrderStateChangeNotification));

                FinancialOrderState orderState = changeOrder.newfinancialorderstate;
                Order order = GetMerchantOrderByGoogleOrderId(changeOrder.googleordernumber);
                if (order != null)
                {
                    string message = string.Format("Order status {0} from Google: Order Number {1}", orderState, changeOrder.googleordernumber);
                    LogMessage(message);

                    //add a note
                    order.OrderNotes.Add(new OrderNote()
                    {
                        Note         = message,
                        CreatedOnUtc = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);

                    if (orderState == FinancialOrderState.CHARGING ||
                        orderState == FinancialOrderState.REVIEWING)
                    {
                    }

                    if (orderState == FinancialOrderState.CHARGEABLE)
                    {
                        _orderProcessingService.MarkAsAuthorized(order);
                    }
                    if (orderState == FinancialOrderState.CHARGED)
                    {
                        _orderProcessingService.MarkOrderAsPaid(order);
                    }
                    if (orderState == FinancialOrderState.CANCELLED || orderState == FinancialOrderState.CANCELLED_BY_GOOGLE)
                    {
                        _orderProcessingService.CancelOrder(order, true);
                    }
                }
            }
            catch (Exception exc)
            {
                LogMessage("processOrderStateChangeNotification Exception: " + exc.Message + ": " + exc.StackTrace);
            }
        }
        /// <summary>
        /// Authorize
        /// </summary>
        /// <param name="order">Order</param>
        /// <param name="authorization">Authorization</param>
        private void MarkOrderAsAuthorized(Core.Domain.Orders.Order order, Authorization authorization)
        {
            //compare amounts
            var orderTotal = Math.Round(order.OrderTotal, 2);

            if (!decimal.TryParse(authorization.Amount?.Value, out var authorizedAmount) || authorizedAmount != orderTotal)
            {
                return;
            }

            //all is ok, so authorize order
            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
            {
                order.AuthorizationTransactionId     = authorization.Id;
                order.AuthorizationTransactionResult = authorization.Status;
                _orderService.UpdateOrder(order);
                _orderProcessingService.MarkAsAuthorized(order);
            }
        }
예제 #7
0
        public void ProcessPostBackModel(PostBackModel model)
        {
            if (model == null)
            {
                return;
            }

            var orderId = GetOrderId(model.ORDERID);

            var requestFields      = new SortedDictionary <string, string>();
            var keyValueCollection = (Request.RequestType == "POST") ? Request.Form : Request.QueryString;

            var sb = new StringBuilder("Ogone Postback Fields:\r\n");

            foreach (string key in keyValueCollection)
            {
                if (!key.ToUpper().Equals("SHASIGN"))
                {
                    requestFields.Add(key, keyValueCollection[key]);
                }

                sb.AppendFormat("{0}={1};\r\n", key, keyValueCollection[key]);
            }

            var order = _orderService.GetOrderById(orderId);

            if (order == null)
            {
                _logger.InsertLog(LogLevel.Error, "Invalid order id", string.Format("Ogone Postback Error. Order id {0} not found.", orderId));
                return;
            }

            AddOrderNote(order, sb.ToString(), false);

            var processor =
                _paymentService.LoadPaymentMethodBySystemName("Payments.Ogone") as OgonePaymentProcessor;

            if (processor == null || !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Ogone Payment module cannot be loaded");
            }

            if (processor.VerifyHashDigest(requestFields, model.SHASIGN) == false)
            {
                AddOrderNote(order, "Ogone Postback Error. SHA-digest verification failed", false);
                return;
            }

            var paymentStatus = OgoneHelper.GetPaymentStatus(model.STATUS.ToString(), model.NCERROR);

            switch (paymentStatus)
            {
            case PaymentStatus.Authorized:
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
                break;

            case PaymentStatus.Paid:
                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                }
                break;

            case PaymentStatus.Pending:
                break;

            case PaymentStatus.Voided:
                if (_orderProcessingService.CanCancelOrder(order))
                {
                    _orderProcessingService.CancelOrder(order, notifyCustomer: true);
                }
                break;
            }
        }
예제 #8
0
        public bool ProcessCallBackRequest(string payment, string signature)
        {
            LogMessage(string.Format("payment={0}", payment));
            LogMessage(string.Format("signature={0}", signature));
            string password = payment + _privat24PaymentSettings.MerchantSignature;
            string text     = Sh1(Md5(password));

            LogMessage(string.Format("signaturemy={0}", text));
            if (!string.Equals(text, signature))
            {
                LogMessage("signature!=signaturemy");
                return(false);
            }
            var stringBuilder = new StringBuilder();

            stringBuilder.AppendLine("Privat24 IPN:");
            string order     = null;
            string state     = null;
            string amount    = null;
            string reference = null;
            string currency  = null;

            string[] array = payment.Split(new[]
            {
                '&'
            });
            foreach (string value in array)
            {
                string param = value.Trim();
                stringBuilder.AppendLine(param);
                if (param.StartsWith("order="))
                {
                    order = param.Substring(6).Trim();
                }
                if (param.StartsWith("state="))
                {
                    state = param.Substring(6).Trim();
                }
                if (param.StartsWith("amt="))
                {
                    amount = param.Substring(4).Trim();
                }
                if (param.StartsWith("ref="))
                {
                    reference = param.Substring(4).Trim();
                }
                if (param.StartsWith("ccy="))
                {
                    currency = param.Substring(4).Trim();
                }
            }
            if (state == null)
            {
                state = string.Empty;
            }
            if (reference == null)
            {
                reference = string.Empty;
            }
            if (currency == null)
            {
                currency = string.Empty;
            }
            int orderId = 0;

            int.TryParse(order, out orderId);
            Order orderById = _orderService.GetOrderById(orderId);

            if (orderById == null)
            {
                LogMessage(string.Format("bad order == null, nopOrderId={0}, nopOrderIdStr={1}", orderId, order));
                return(false);
            }
            if (orderById.PaymentStatus == PaymentStatus.Paid)
            {
                LogMessage(string.Format("Order is paid, nopOrderId={0}, order.PaymentStatus={1}", orderId, orderById.PaymentStatus));
                return(true);
            }

            decimal orderTotal = 0m;

            decimal.TryParse(amount, out orderTotal);
            if (_privat24PaymentSettings.IsTestMode)
            {
                orderTotal = orderById.OrderTotal;
            }
            if (orderById.OrderTotal != orderTotal)
            {
                LogMessage(string.Format("Bad OrderTotal orderid={0}, order.OrderTotal={1}, Privat24.amt={2}", orderId, orderById.OrderTotal, orderTotal));
                return(false);
            }
            string currencyCode = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;

            if (string.IsNullOrEmpty(currencyCode))
            {
                currencyCode = "UAH";
            }

            var currencies = _privat24PaymentSettings.Currencies.Split(new[] { ",", " " }, StringSplitOptions.RemoveEmptyEntries);;

            if (!currencies.Contains(currencyCode))
            {
                currencyCode = "UAH";
            }

            if (!string.Equals(currencyCode, currency))
            {
                LogMessage(string.Format("Bad OrderTotal currency orderid={0}, currency={1}, payment_ccy={2}", orderId, currencyCode, currency));
                return(false);
            }

            ICollection <OrderNote> orderNotes = orderById.OrderNotes;
            var orderNote = new OrderNote
            {
                Note = stringBuilder.ToString(),
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            };

            orderNotes.Add(orderNote);
            _orderService.UpdateOrder(orderById);
            PaymentStatus paymentStatus  = GetPaymentStatus(state);
            PaymentStatus paymentStatus2 = paymentStatus;

            if (paymentStatus2 <= PaymentStatus.Authorized)
            {
                if (paymentStatus2 != PaymentStatus.Pending)
                {
                    if (paymentStatus2 == PaymentStatus.Authorized)
                    {
                        if (_orderProcessingService.CanMarkOrderAsAuthorized(orderById))
                        {
                            _orderProcessingService.MarkAsAuthorized(orderById);
                        }
                    }
                }
            }
            else
            {
                if (paymentStatus2 != PaymentStatus.Paid)
                {
                    if (paymentStatus2 != PaymentStatus.Refunded)
                    {
                        if (paymentStatus2 == PaymentStatus.Voided)
                        {
                            if (_orderProcessingService.CanVoidOffline(orderById))
                            {
                                _orderProcessingService.VoidOffline(orderById);
                            }
                        }
                    }
                    else
                    {
                        if (_orderProcessingService.CanRefundOffline(orderById))
                        {
                            _orderProcessingService.RefundOffline(orderById);
                        }
                    }
                }
                else
                {
                    if (_orderProcessingService.CanMarkOrderAsPaid(orderById) &&
                        orderById.PaymentStatus != PaymentStatus.Paid)
                    {
                        _orderProcessingService.MarkOrderAsPaid(orderById);
                    }
                }
            }
            return(true);
        }
예제 #9
0
        /// <remarks>return 503 (HttpStatusCode.ServiceUnavailable) to ask paypal to resend it at later time again</remarks>
        public HttpStatusCode ProcessWebhook(
            PayPalApiSettingsBase settings,
            NameValueCollection headers,
            string rawJson,
            string providerSystemName)
        {
            if (rawJson.IsEmpty())
            {
                return(HttpStatusCode.OK);
            }

            dynamic json      = JObject.Parse(rawJson);
            var     eventType = (string)json.event_type;

            //foreach (var key in headers.AllKeys)"{0}: {1}".FormatInvariant(key, headers[key]).Dump();
            //string data = JsonConvert.SerializeObject(json, Formatting.Indented);data.Dump();


            // validating against PayPal SDK failing using sandbox, so better we do not use it:
            //var apiContext = new global::PayPal.Api.APIContext
            //{
            //	AccessToken = "I do not have one here",
            //	Config = new Dictionary<string, string>
            //		{
            //			{ "mode", settings.UseSandbox ? "sandbox" : "live" },
            //			{ "clientId", settings.ClientId },
            //			{ "clientSecret", settings.Secret },
            //			{ "webhook.id", setting.WebhookId },
            //		}
            //};
            //var result = global::PayPal.Api.WebhookEvent.ValidateReceivedEvent(apiContext, headers, rawJson, webhookId);
            //}

            var paymentId = (string)json.resource.parent_payment;

            if (paymentId.IsEmpty())
            {
                LogError(null, T("Plugins.SmartStore.PayPal.FoundOrderForPayment", 0, "".NaIfEmpty()), JsonConvert.SerializeObject(json, Formatting.Indented), isWarning: true);
                return(HttpStatusCode.OK);
            }

            var orders = _orderRepository.Value.Table
                         .Where(x => x.PaymentMethodSystemName == providerSystemName && x.AuthorizationTransactionCode == paymentId)
                         .ToList();

            if (orders.Count != 1)
            {
                LogError(null, T("Plugins.SmartStore.PayPal.FoundOrderForPayment", orders.Count, paymentId), JsonConvert.SerializeObject(json, Formatting.Indented), isWarning: true);
                return(HttpStatusCode.OK);
            }

            var order = orders.First();
            var store = _services.StoreService.GetStoreById(order.StoreId);

            var total           = decimal.Zero;
            var currency        = (string)json.resource.amount.currency;
            var primaryCurrency = store.PrimaryStoreCurrency.CurrencyCode;

            if (!primaryCurrency.IsCaseInsensitiveEqual(currency))
            {
                LogError(null, T("Plugins.SmartStore.PayPal.CurrencyNotEqual", currency.NaIfEmpty(), primaryCurrency), JsonConvert.SerializeObject(json, Formatting.Indented), isWarning: true);
                return(HttpStatusCode.OK);
            }

            eventType = eventType.Substring(eventType.LastIndexOf('.') + 1);

            var newPaymentStatus = GetPaymentStatus(eventType, "authorization", order.PaymentStatus);

            var isValidTotal = decimal.TryParse((string)json.resource.amount.total, NumberStyles.Currency, CultureInfo.InvariantCulture, out total);

            if (newPaymentStatus == PaymentStatus.Refunded && (Math.Abs(order.OrderTotal) - Math.Abs(total)) > decimal.Zero)
            {
                newPaymentStatus = PaymentStatus.PartiallyRefunded;
            }

            switch (newPaymentStatus)
            {
            case PaymentStatus.Pending:
                break;

            case PaymentStatus.Authorized:
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
                break;

            case PaymentStatus.Paid:
                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                }
                break;

            case PaymentStatus.Refunded:
                if (_orderProcessingService.CanRefundOffline(order))
                {
                    _orderProcessingService.RefundOffline(order);
                }
                break;

            case PaymentStatus.PartiallyRefunded:
                if (_orderProcessingService.CanPartiallyRefundOffline(order, Math.Abs(total)))
                {
                    _orderProcessingService.PartiallyRefundOffline(order, Math.Abs(total));
                }
                break;

            case PaymentStatus.Voided:
                if (_orderProcessingService.CanVoidOffline(order))
                {
                    _orderProcessingService.VoidOffline(order);
                }
                break;
            }

            order.HasNewPaymentNotification = true;

            AddOrderNote(settings, order, (string)ToInfoString(json));

            return(HttpStatusCode.OK);
        }
예제 #10
0
        public ActionResult PdtHandler()
        {
            // Get the 3 strings from ePay
            string transactionOrderId = webHelper.QueryString <string>("orderid");
            string transactionTxnId   = webHelper.QueryString <string>("txnid");
            string transactionHash    = webHelper.QueryString <string>("hash");

            string subscriptionId = webHelper.QueryString <string>("subscriptionid"); // is null if no subscription
            string maskedCCNo     = webHelper.QueryString <string>("cardno");

            // Check if ePay module is alive
            var processor = paymentService.LoadPaymentMethodBySystemName("Payments.EPay") as EPayPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("Error. The ePay module couldn't be loaded!");
            }

            // Get order from OrderNumer
            int orderNumber = 0;

            orderNumber = Convert.ToInt32(transactionOrderId);

            // build md5string
            string hash = "";
            NameValueCollection getParameters = HttpContext.Request.QueryString;

            foreach (string key in getParameters)
            {
                if (key != "hash")
                {
                    hash += getParameters[key];
                }
            }

            var order = orderService.GetOrderById(orderNumber);

            // Validate payment
            string md5Secret   = ePayPaymentSettings.Md5Secret;
            string stringToMd5 = string.Concat(hash, md5Secret);
            string md5Check    = GetMD5(stringToMd5);

            bool validated = (md5Check == transactionHash || md5Secret.Length == 0);

            // If order is ok then proceed

            if (order != null)
            {
                var sb = new StringBuilder();
                sb.AppendLine("ePay transaction:");
                sb.AppendLine("Transaction ID: " + transactionTxnId);
                sb.AppendLine("Validated transaction : " + validated);

                //order note
                order.OrderNotes.Add(new OrderNote()
                {
                    Note = sb.ToString(),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                orderService.UpdateOrder(order);

                if (validated)
                {
                    if (subscriptionId != null)
                    {
                        order.SubscriptionTransactionId = subscriptionId;
                    }

                    if (maskedCCNo != null)
                    {
                        order.MaskedCreditCardNumber = maskedCCNo;
                    }

                    if (ePayPaymentSettings.Instantcapture)
                    {
                        if (orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId = transactionTxnId;
                            orderProcessingService.MarkOrderAsPaid(order);
                            orderService.UpdateOrder(order);
                        }
                    }
                    else
                    {
                        if (orderProcessingService.CanMarkOrderAsAuthorized(order))
                        {
                            order.AuthorizationTransactionId = transactionTxnId;
                            orderProcessingService.MarkAsAuthorized(order);
                            orderService.UpdateOrder(order);
                        }
                    }
                }
                else
                {
                    throw new NopException("MD5 is not valid.");
                }
            }

            return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
        }
예제 #11
0
        public ActionResult IPNHandler()
        {
            Debug.WriteLine("PayPal Direct IPN: {0}".FormatWith(Request.ContentLength));

            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

            var provider  = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalDirect", true);
            var processor = provider != null ? provider.Value as PayPalDirectProvider : null;

            if (processor == null)
            {
                throw new SmartException(_helper.GetResource("NoModuleLoading"));
            }

            if (processor.VerifyIPN(strRequest, out values))
            {
                #region values
                decimal total = decimal.Zero;
                try
                {
                    total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                string payer_status = string.Empty;
                values.TryGetValue("payer_status", out payer_status);
                string payment_status = string.Empty;
                values.TryGetValue("payment_status", out payment_status);
                string pending_reason = string.Empty;
                values.TryGetValue("pending_reason", out pending_reason);
                string mc_currency = string.Empty;
                values.TryGetValue("mc_currency", out mc_currency);
                string txn_id = string.Empty;
                values.TryGetValue("txn_id", out txn_id);
                string txn_type = string.Empty;
                values.TryGetValue("txn_type", out txn_type);
                string rp_invoice_id = string.Empty;
                values.TryGetValue("rp_invoice_id", out rp_invoice_id);
                string payment_type = string.Empty;
                values.TryGetValue("payment_type", out payment_type);
                string payer_id = string.Empty;
                values.TryGetValue("payer_id", out payer_id);
                string receiver_id = string.Empty;
                values.TryGetValue("receiver_id", out receiver_id);
                string invoice = string.Empty;
                values.TryGetValue("invoice", out invoice);
                string payment_fee = string.Empty;
                values.TryGetValue("payment_fee", out payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("PayPal IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = PayPalHelper.GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("{0}: {1}".FormatWith(_helper.GetResource("NewPaymentStatus"), newPaymentStatus));

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                    #region Recurring payment
                {
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(0, 0, initialOrder.Id, null);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (recurringPaymentHistory.Count == 0)
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory()
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    _orderProcessingService.ProcessNextRecurringPayment(rp);
                                }
                            }
                            break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        Logger.Information(_helper.GetResource("IpnLogInfo"), new SmartException(sb.ToString()));
                    }
                    else
                    {
                        Logger.Error(_helper.GetResource("IpnOrderNotFound"), new SmartException(sb.ToString()));
                    }
                }
                    #endregion
                    break;

                default:
                    #region Standard payment
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.HasNewPaymentNotification = true;

                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        Logger.Error(_helper.GetResource("IpnOrderNotFound"), new SmartException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                Logger.Error(_helper.GetResource("IpnFailed"), new SmartException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
예제 #12
0
        public IActionResult s2sHandler()
        {
            string errorCode = "", errorDesc = "";

            string strRequest = Request.QueryString.ToString().Replace("?", "");
            Dictionary <string, string> values;

            var processor = _paymentPluginManager.LoadPluginBySystemName("Payments.GestPay") as GestPayPaymentProcessor;

            if (processor == null ||
                !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("GestPay module cannot be loaded");
            }

            processor.GetResponseDetails(strRequest, out values);
            if (values != null && values.Count > 0)
            {
                if (values.Count == 4)
                {
                    return(RedirectToRoute("Plugin.Payments.GestPay.AcceptPaymenyByLink", new { a = values["a"], status = values["Status"], paymentId = values["paymentID"], paymentToken = values["paymentToken"] }));
                }

                var    shopLogin = values["a"];
                var    encString = values["b"];
                string shopTransactionId = "", authorizationCode = "", bankTransactionId = "";
                string transactionResult = "", buyerName = "", buyerEmail = "", riskified = "", authorizationcode = "", threeDSAuthenticationLevel = "";

                var acceptedThreeDSAuthLevels = new List <string> {
                    "1H", "1F", "2F", "2C", "2E"
                };
                var checkAmount = decimal.Zero;

                var sb = new StringBuilder();
                sb.AppendLine("GestPay s2s:");

                if (processor.IsShopLoginChecked(shopLogin) && encString != null)
                {
                    var endpoint   = _gestPayPaymentSettings.UseSandbox ? WSCryptDecryptSoapClient.EndpointConfiguration.WSCryptDecryptSoap12Test : WSCryptDecryptSoapClient.EndpointConfiguration.WSCryptDecryptSoap12;
                    var objDecrypt = new WSCryptDecryptSoapClient(endpoint);

                    string xmlResponse = objDecrypt.DecryptAsync(shopLogin, encString, _gestPayPaymentSettings.ApiKey).Result.OuterXml;

                    XmlDocument XMLReturn = new XmlDocument();
                    XMLReturn.LoadXml(xmlResponse.ToLower());

                    //_logger.Information(xmlResponse.ToLower());

                    //Id transazione inviato
                    errorCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/errorcode")?.InnerText;
                    errorDesc = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/errordescription")?.InnerText;
                    //authorizationCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/authorizationcode")?.InnerText;
                    shopTransactionId = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/shoptransactionid")?.InnerText;

                    //_____ Messaggio OK _____//
                    if (errorCode == "0")
                    {
                        //Codice autorizzazione
                        authorizationCode = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/authorizationcode")?.InnerText;
                        //Codice transazione
                        bankTransactionId = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/banktransactionid")?.InnerText;
                        //Ammontare della transazione
                        var amount = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/amount")?.InnerText;
                        //Risultato transazione
                        transactionResult = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/transactionresult")?.InnerText;
                        //Nome dell'utente
                        buyerName = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/buyer/buyername")?.InnerText;
                        //Email utilizzata nella transazione
                        buyerEmail = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/buyer/buyeremail")?.InnerText;

                        //__________ ?validare il totale? __________//
                        riskified = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/riskresponsedescription")?.InnerText;

                        //  3DS authentication level (1H,1F,2F,2C,2E)
                        threeDSAuthenticationLevel = XMLReturn.SelectSingleNode("/gestpaycryptdecrypt/threeds/authenticationresult/authenticationlevel")?.InnerText?.ToUpper();

                        try
                        {
                            checkAmount = decimal.Parse(amount, new CultureInfo("en-US"));
                        }
                        catch (Exception exc)
                        {
                            _logger.Error("GestPay s2s. Error getting Amount", exc);
                        }
                        sb.AppendLine("GestPay success.");
                    }
                    else
                    {
                        sb.AppendLine("GestPay failed.");
                        _logger.Error("GestPay S2S. Transaction not found", new NopException(sb.ToString()));
                    }
                }

                //________ Inizio composizione messaggio dal server _________//
                foreach (var kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                //Recupero lo stato del pagamento
                var newPaymentStatus = GestPayHelper.GetPaymentStatus(transactionResult, "");
                sb.AppendLine("New payment status: " + newPaymentStatus);
                sb.AppendLine("Riskified = " + riskified);
                sb.AppendLine("3DS Level = " + threeDSAuthenticationLevel);

                //Cerco di recuperare l'ordine
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(shopTransactionId);
                }
                catch { }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);
                //_________ aggiorno lo stato dell'ordine _________//
                if (order != null)
                {
                    switch (newPaymentStatus)
                    {
                    case PaymentStatus.Pending:
                    {
                    }
                    break;

                    case PaymentStatus.Authorized:
                    {
                        if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                        {
                            _orderProcessingService.MarkAsAuthorized(order);
                        }
                    }
                    break;

                    case PaymentStatus.Paid:
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId   = bankTransactionId;
                            order.AuthorizationTransactionCode = authorizationCode;
                            _orderService.UpdateOrder(order);

                            if (!_gestPayPaymentSettings.EnableGuaranteedPayment || acceptedThreeDSAuthLevels.Contains(threeDSAuthenticationLevel))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                    }
                    break;

                    case PaymentStatus.Refunded:
                    {
                        if (_orderProcessingService.CanRefundOffline(order))
                        {
                            _orderProcessingService.RefundOffline(order);
                        }
                    }
                    break;

                    case PaymentStatus.Voided:
                    {
                        /*_ Visto che non si può impostare il pagamento ad Annullato
                         * _orderProcessingService.CanVoidOffline allora cancello l'ordine.
                         * C'è da decidere se avvisare o meno l'utente _*/
                        if (_orderProcessingService.CanCancelOrder(order))
                        {
                            _orderProcessingService.CancelOrder(order, true);
                        }
                    }
                    break;
                    }

                    //__________________ salvo i valori restituiti __________________//
                    sb.AppendLine("GestPay response:");
                    //Codice Errore
                    sb.AppendLine("ErrorCode: " + errorCode);
                    //Descrizione Errore
                    sb.AppendLine("ErrorDesc: " + errorDesc);
                    sb.AppendLine("TrxResult: " + transactionResult);
                    sb.AppendLine("BankTrxID: " + bankTransactionId);
                    sb.AppendLine("AuthCode: " + authorizationCode);
                    sb.AppendLine("Amount: " + checkAmount);
                    if (!Math.Round(checkAmount, 2).Equals(Math.Round(order.OrderTotal, 2)))
                    {
                        //__________ ?validare il totale? __________//
                        sb.AppendLine(String.Format("Amount difference: {0}-{1}", Math.Round(checkAmount, 2), Math.Round(order.OrderTotal, 2)));
                    }
                    sb.AppendLine("BuyerName: " + buyerName);
                    sb.AppendLine("BuyerEmail: " + buyerEmail);

                    //Inserisco la nota sull'ordine
                    var orderNote = new OrderNote
                    {
                        OrderId           = order.Id,
                        Note              = sb.ToString(),
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    };
                    _orderService.InsertOrderNote(orderNote);
                }
                else
                {
                    _logger.Error("GestPay S2S. Order is not found", new NopException(sb.ToString()));
                }
            }
            else
            {
                _logger.Error("GestPay S2S failed.", new NopException(strRequest));
            }

            //_________ Imposto il risultato __________//
            var s2SResponse = "KO";

            if (errorCode == "0")
            {
                s2SResponse = "OK";
            }
            //nothing should be rendered to visitor
            return(Content(String.Format("<html>{0}</html>", s2SResponse)));
        }
        private Order CreateOrderAndSyncWithKlarna(KlarnaCheckoutEntity klarnaRequest, Customer customer, KlarnaCheckoutOrder klarnaCheckoutOrder, Uri resourceUri)
        {
            SyncCartWithKlarnaOrder(customer, klarnaCheckoutOrder);

            var processPaymentRequest = new ProcessPaymentRequest
            {
                OrderGuid  = klarnaRequest.OrderGuid,
                CustomerId = customer.Id,
                StoreId    = _storeContext.CurrentStore.Id,
                PaymentMethodSystemName = KlarnaCheckoutProcessor.PaymentMethodSystemName
            };

            var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);

            // If you tamper with the cart after the klarna widget is rendered nop fails to create the order.
            if (!placeOrderResult.Success)
            {
                var errors = string.Join("; ", placeOrderResult.Errors);
                _logger.Error(string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Klarna has been processed but order could not be created in Nop! Klarna ID={0}, ResourceURI={1}. Errors: {2}",
                                            klarnaCheckoutOrder.Id, klarnaRequest.KlarnaResourceUri, errors), customer: customer);

                _klarnaCheckoutPaymentService.CancelPayment(klarnaCheckoutOrder.Reservation, customer);

                throw new KlarnaCheckoutException("Error creating order: " + errors);
            }

            // Order was successfully created.
            var orderId       = placeOrderResult.PlacedOrder.Id;
            var nopOrder      = _orderService.GetOrderById(orderId);
            var klarnaPayment =
                _paymentService.LoadPaymentMethodBySystemName(KlarnaCheckoutProcessor.PaymentMethodSystemName);

            klarnaPayment.PostProcessPayment(new PostProcessPaymentRequest
            {
                Order = nopOrder
            });

            var orderTotalInCurrentCurrency = _currencyService.ConvertFromPrimaryStoreCurrency(nopOrder.OrderTotal, _workContext.WorkingCurrency);

            // Due to rounding when using prices contains more than 2 decimals (e.g. currency conversion), we allow
            // a slight diff in paid price and nop's reported price.
            // For example nop rounds the prices after _all_ cart item prices have been summed but when sending
            // items to Klarna, each price needs to be rounded separately (Klarna uses 2 decimals).

            // Assume a cart with two items.
            // 1.114 + 2.114 = 3.228 which nop rounds to 3.23.
            // 1.11 + 2.11 is sent to Klarna, which totals 3.22.

            var allowedPriceDiff = orderTotalInCurrentCurrency * 0.01m;
            var diff             = Math.Abs(orderTotalInCurrentCurrency - (klarnaCheckoutOrder.Cart.TotalPriceIncludingTax.Value / 100m));

            if (diff >= allowedPriceDiff)
            {
                var orderTotalInCents = _klarnaCheckoutHelper.ConvertToCents(orderTotalInCurrentCurrency);

                nopOrder.OrderNotes.Add(new OrderNote
                {
                    Note = string.Format(CultureInfo.CurrentCulture, "KlarnaCheckout: Order total differs from Klarna order. OrderTotal: {0}, OrderTotalInCents: {1}, KlarnaTotal: {2}, AllowedDiff: {3}, Diff: {4}, Uri: {5}",
                                         orderTotalInCurrentCurrency, orderTotalInCents, klarnaCheckoutOrder.Cart.TotalPriceIncludingTax, allowedPriceDiff, diff, resourceUri),
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
            }

            nopOrder.OrderNotes.Add(new OrderNote
            {
                Note = "KlarnaCheckout: Order acknowledged. Uri: " + resourceUri,
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });
            _orderService.UpdateOrder(nopOrder);

            if (_orderProcessingService.CanMarkOrderAsAuthorized(nopOrder))
            {
                _orderProcessingService.MarkAsAuthorized(nopOrder);

                // Sometimes shipping isn't required, e.g. if only ordering virtual gift cards.
                // In those cases, make sure the Klarna order is activated.
                if (nopOrder.OrderStatus == OrderStatus.Complete || nopOrder.ShippingStatus == ShippingStatus.ShippingNotRequired)
                {
                    nopOrder.OrderNotes.Add(new OrderNote
                    {
                        Note              = "KlarnaCheckout: Order complete after payment, will try to capture payment.",
                        CreatedOnUtc      = DateTime.UtcNow,
                        DisplayToCustomer = false
                    });
                    _orderService.UpdateOrder(nopOrder);

                    if (_orderProcessingService.CanCapture(nopOrder))
                    {
                        _orderProcessingService.Capture(nopOrder);
                    }
                }
            }

            return(nopOrder);
        }
        public IActionResult IPNHandler(IFormCollection form)
        {
            //byte[] parameters;
            //using (var stream = new MemoryStream())
            //{
            //    this.Request.Body.CopyTo(stream);
            //    parameters = stream.ToArray();
            //}
            //var strRequest = Encoding.ASCII.GetString(parameters);

            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.MOLPay") as MOLPayPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("MOLPay module cannot be loaded");
            }

            //if (processor.VerifyIpn(strRequest, out Dictionary<string, string> values))
            //{
            #region values
            var mc_gross = decimal.Zero;
            try
            {
                mc_gross = decimal.Parse(form["mc_gross"], new CultureInfo("en-US"));
            }
            catch { }

            //values.TryGetValue("payer_status", out string payer_status);
            //values.TryGetValue("payment_status", out string payment_status);
            //values.TryGetValue("pending_reason", out string pending_reason);
            //values.TryGetValue("mc_currency", out string mc_currency);
            //values.TryGetValue("txn_id", out string txn_id);
            //values.TryGetValue("txn_type", out string txn_type);
            //values.TryGetValue("rp_invoice_id", out string rp_invoice_id);
            //values.TryGetValue("payment_type", out string payment_type);
            //values.TryGetValue("payer_id", out string payer_id);
            //values.TryGetValue("receiver_id", out string receiver_id);
            //values.TryGetValue("invoice", out string _);
            //values.TryGetValue("payment_fee", out string payment_fee);

            #endregion

            var    skey          = form["skey"];
            var    tranID        = form["tranID"];
            var    domain        = form["domain"];
            var    status        = form["status"];
            var    amount        = form["amount"];
            var    currency      = form["currency"];
            var    paydate       = form["paydate"];
            int    orderid       = Int32.Parse(form["orderid"]);
            var    appcode       = form["appcode"];
            var    error_code    = form["error_code"];
            var    error_desc    = form["error_desc"];
            string txn_type      = form["txn_type"];
            var    rp_invoice_id = form["rp_invoice_id"];
            var    txn_id        = form["txn_id"];
            var    channel       = form["channel"];

            var sb = new StringBuilder();
            sb.AppendLine("MOLPay IPN:");
            foreach (var kvp in form)
            {
                sb.AppendLine(kvp.Key + ": " + kvp.Value);
            }

            var captured = _molPayPaymentSettings.CapturedMode;
            var failed   = _molPayPaymentSettings.FailedMode;
            var pending  = _molPayPaymentSettings.PendingMode;
            var result   = pending;
            switch (status)
            {
            case "00":
                result = captured;
                break;

            case "11":
                result = failed;
                break;

            case "22":
                result = pending;
                break;

            default:
                break;
            }

            //var newPaymentStatus = MOLPayHelper.GetPaymentStatus(payment_status);
            var newPaymentStatus = result;
            sb.AppendLine("New payment status: " + newPaymentStatus);

            switch (txn_type)
            {
            case "recurring_payment_profile_created":
                //do nothing here
                break;

                #region Recurring payment
            case "recurring_payment":
            {
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(rp_invoice_id);
                }
                catch
                {
                }

                var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                if (initialOrder != null)
                {
                    var recurringPayments = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id);
                    foreach (var rp in recurringPayments)
                    {
                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Authorized:
                        case PaymentStatus.Paid:
                        {
                            var recurringPaymentHistory = rp.RecurringPaymentHistory;
                            if (!recurringPaymentHistory.Any())
                            {
                                //first payment
                                var rph = new RecurringPaymentHistory
                                {
                                    RecurringPaymentId = rp.Id,
                                    OrderId            = initialOrder.Id,
                                    CreatedOnUtc       = DateTime.UtcNow
                                };
                                rp.RecurringPaymentHistory.Add(rph);
                                _orderService.UpdateRecurringPayment(rp);
                            }
                            else
                            {
                                //next payments
                                var processPaymentResult = new ProcessPaymentResult
                                {
                                    NewPaymentStatus = newPaymentStatus
                                };
                                if (newPaymentStatus == PaymentStatus.Authorized)
                                {
                                    processPaymentResult.AuthorizationTransactionId = txn_id;
                                }
                                else
                                {
                                    processPaymentResult.CaptureTransactionId = txn_id;
                                }

                                _orderProcessingService.ProcessNextRecurringPayment(rp, processPaymentResult);
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                            //failed payment
                            var failedPaymentResult = new ProcessPaymentResult
                            {
                                Errors = new[] { $"MOLPay IPN. Recurring payment is {newPaymentStatus} ." },
                                RecurringPaymentFailed = true
                            };
                            _orderProcessingService.ProcessNextRecurringPayment(rp, failedPaymentResult);
                            break;
                        }
                    }

                    //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                    _logger.Information("MOLPay IPN. Recurring info", new NopException(sb.ToString()));
                }
                else
                {
                    _logger.Error("MOLPay IPN. Order is not found", new NopException(sb.ToString()));
                }
            }
            break;

            case "recurring_payment_failed":
                if (Guid.TryParse(rp_invoice_id, out Guid orderGuid))
                {
                    var initialOrder = _orderService.GetOrderByGuid(orderGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                        //failed payment
                        if (recurringPayment != null)
                        {
                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, new ProcessPaymentResult {
                                Errors = new[] { txn_type }, RecurringPaymentFailed = true
                            });
                        }
                    }
                }
                break;

                #endregion
            default:
                #region Standard payment
            {
                //values.TryGetValue("custom", out string orderNumber);
                var orderNumber     = form["custom"];
                var orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch
                {
                }

                var order = _orderService.GetOrderByGuid(orderNumberGuid);
                if (order != null)
                {
                    //order note
                    order.OrderNotes.Add(new OrderNote
                        {
                            Note = sb.ToString(),
                            DisplayToCustomer = false,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                    _orderService.UpdateOrder(order);

                    switch (newPaymentStatus)
                    {
                    case PaymentStatus.Pending:
                    {
                    }
                    break;

                    case PaymentStatus.Authorized:
                    {
                        //validate order total
                        if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                        {
                            //valid
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        else
                        {
                            //not valid
                            var errorStr =
                                $"MOLPay IPN. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                            //log
                            _logger.Error(errorStr);
                            //order note
                            order.OrderNotes.Add(new OrderNote
                                    {
                                        Note = errorStr,
                                        DisplayToCustomer = false,
                                        CreatedOnUtc      = DateTime.UtcNow
                                    });
                            _orderService.UpdateOrder(order);
                        }
                    }
                    break;

                    case PaymentStatus.Paid:
                    {
                        //validate order total
                        if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                        {
                            //valid
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                order.AuthorizationTransactionId = txn_id;
                                _orderService.UpdateOrder(order);

                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        else
                        {
                            //not valid
                            var errorStr =
                                $"MOLPay IPN. Returned order total {mc_gross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                            //log
                            _logger.Error(errorStr);
                            //order note
                            order.OrderNotes.Add(new OrderNote
                                    {
                                        Note = errorStr,
                                        DisplayToCustomer = false,
                                        CreatedOnUtc      = DateTime.UtcNow
                                    });
                            _orderService.UpdateOrder(order);
                        }
                    }
                    break;

                    case PaymentStatus.Refunded:
                    {
                        var totalToRefund = Math.Abs(mc_gross);
                        if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))
                        {
                            //refund
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                        }
                        else
                        {
                            //partial refund
                            if (_orderProcessingService.CanPartiallyRefundOffline(order, totalToRefund))
                            {
                                _orderProcessingService.PartiallyRefundOffline(order, totalToRefund);
                            }
                        }
                    }
                    break;

                    case PaymentStatus.Voided:
                    {
                        if (_orderProcessingService.CanVoidOffline(order))
                        {
                            _orderProcessingService.VoidOffline(order);
                        }
                    }
                    break;

                    default:
                        break;
                    }
                }
                else
                {
                    _logger.Error("MOLPay IPN. Order is not found", new NopException(sb.ToString()));
                }
            }
                #endregion
                break;
            }
            //}
            //else
            //{
            //    _logger.Error("MOLPay IPN failed.", new NopException(strRequest));
            //}

            //nothing should be rendered to visitor
            return(Content(""));
        }
        public ActionResult PDTHandler(FormCollection form)
        {
            string checkout_id = _webHelper.QueryString <string>("checkout_id");
            Dictionary <string, string> values;
            string response;

            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.WePay") as WePayPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("WePay module cannot be loaded");
            }

            if (processor.GetPDTDetails(checkout_id, out values, out response))
            {
                string orderNumber = string.Empty;
                values.TryGetValue("reference_id", out orderNumber);
                Guid orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch (Exception exc)
                {
                    _logger.Error("Invalid WePay Order Number Guid", exc);
                    throw new NopException("WePay PDT: Invalid order reference number");
                }

                Order order = _orderService.GetOrderByGuid(orderNumberGuid);
                if (order != null)
                {
                    decimal total = decimal.Zero;
                    try
                    {
                        total = decimal.Parse(values["gross"], new CultureInfo("en-US"));
                    }
                    catch (Exception exc)
                    {
                        _logger.Error("WePay PDT. Error getting mc_gross", exc);
                        throw new NopException("WePay PDT: Unable to capture payment");
                    }

                    string payment_status = string.Empty;
                    values.TryGetValue("state", out payment_status);
                    string mc_currency = string.Empty;
                    values.TryGetValue("currency", out mc_currency);
                    string txn_id = string.Empty;
                    values.TryGetValue("checkout_id", out txn_id);
                    string fee = string.Empty;
                    values.TryGetValue("fee", out fee);
                    string shipping_fee = string.Empty;
                    values.TryGetValue("shipping_fee", out shipping_fee);

                    var sb = new StringBuilder();
                    sb.AppendLine("WePay PDT:");
                    sb.AppendLine("total: " + total);
                    sb.AppendLine(" payment status: " + payment_status);
                    sb.AppendLine("currency: " + mc_currency);
                    sb.AppendLine("checkout_id: " + txn_id);
                    sb.AppendLine("fee: " + fee);
                    //sb.AppendLine(" shipping_fee: " + shipping_fee);

                    //order note
                    order.OrderNotes.Add(WePayPaymentHelper.GenerateOrderNote(sb.ToString()));
                    _orderService.UpdateOrder(order);

                    //load settings for a chosen store scope
                    var storeScope           = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
                    var wePayPaymentSettings = _settingService.LoadSetting <WePayPaymentSettings>(storeScope);

                    if (wePayPaymentSettings.UseSandbox)
                    {
                        _logger.Information(sb.ToString());
                    }


                    decimal payerTotal = Math.Round(order.OrderTotal + Convert.ToDecimal(fee) + Convert.ToDecimal(shipping_fee), 2);
                    decimal payeeTotal = Math.Round(order.OrderTotal + Convert.ToDecimal(shipping_fee), 2);

                    bool validTotal = true;

                    if (wePayPaymentSettings.PdtValidateOrderTotal)
                    {
                        //validate order total : payer
                        if (wePayPaymentSettings.FeePayer == "payer" && !Math.Round(total, 2).Equals(payerTotal))
                        {
                            string errorStr = string.Format("PDT Validation: WePay order total {0} doesn't equal store order total {1}. Order #{2}", total, payerTotal, order.Id);
                            _logger.Error(errorStr);
                            order.OrderNotes.Add(WePayPaymentHelper.GenerateOrderNote(errorStr));
                            _orderService.UpdateOrder(order);

                            validTotal = false;
                        }
                        //validate order total : payee
                        else if (wePayPaymentSettings.FeePayer == "payee" && !Math.Round(total, 2).Equals(payeeTotal))
                        {
                            string errorStr = string.Format("PDT Validation: WePay order total {0} doesn't equal store order total {1}. Order #{2}", total, payeeTotal, order.Id);
                            _logger.Error(errorStr);
                            order.OrderNotes.Add(WePayPaymentHelper.GenerateOrderNote(errorStr));
                            _orderService.UpdateOrder(order);

                            validTotal = false;
                        }
                    }

                    if (_wePayPaymentSettings.TransactMode == TransactMode.CreateAndCapture && validTotal)
                    {
                        //mark order as paid
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId = txn_id;
                            _orderService.UpdateOrder(order);
                            _orderProcessingService.MarkOrderAsPaid(order);
                        }
                    }
                    else
                    {
                        //mark order as authorized
                        if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                        {
                            order.AuthorizationTransactionId = txn_id;
                            _orderService.UpdateOrder(order);
                            _orderProcessingService.MarkAsAuthorized(order);
                        }
                    }
                }

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
            else
            {
                string orderNumber = string.Empty;
                values.TryGetValue("custom", out orderNumber);
                Guid orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch (Exception exc)
                {
                    _logger.Error("Invalid WePay Order Number Guid", exc);
                    throw new NopException("WePay PDT: Invalid order reference number");
                }

                Order order = _orderService.GetOrderByGuid(orderNumberGuid);
                if (order != null)
                {
                    //order note
                    string note = "WePay redirect PDT failed. " + response;
                    order.OrderNotes.Add(WePayPaymentHelper.GenerateOrderNote(note));
                    _orderService.UpdateOrder(order);
                    _logger.Error(note);
                }

                return(RedirectToAction("Orders", "Customer", new { area = "" }));
            }
        }
        public ActionResult statusHandler()
        {
            Guid orderNumberGuid = Guid.Empty;

            if ("statusUrl".Equals(Request.Params.GetValues("type")[0]))
            {
                byte[] param      = Request.BinaryRead(Request.ContentLength);
                string strRequest = Encoding.ASCII.GetString(param);
                Debug.WriteLine(Request.Params);
                var form = this.Request.Form;
                //var newPaymentStatus = PaymentStatus.Pending;
                var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.EasyPay2") as EasyPay2PaymentProcessor;
                if (processor == null ||
                    !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
                {
                    throw new NopException("PayPal Standard module cannot be loaded");
                }

                try{
                    orderNumberGuid = new Guid(form.GetValues("TM_RefNo")[0]);
                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    //Order note
                    var sb = new StringBuilder();
                    //sb.AppendLine("TM_MCode: " + form.GetValues("TM_MCode")[0]);
                    //sb.AppendLine("TM_RefNo: " + form.GetValues("TM_RefNo")[0]);
                    sb.AppendLine(form.GetValues("TM_Status")[0]);
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = sb.ToString(),
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow,
                        OrderId           = order.Id
                    });
                    _orderService.UpdateOrder(order);
                    //set status payment
                    if ("YES".Equals(form.GetValues("TM_Status")[0]))
                    {
                        if ("auth".Equals(form.GetValues("TM_TrnType")[0]))
                        {
                            //newPaymentStatus = PaymentStatus.Authorized;
                            //mark order as Authorized
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                            _logger.Information("Success !!!. PaymentStatus: Authorized");
                        }
                        else if ("sale".Equals(form.GetValues("TM_TrnType")[0]))
                        {
                            //newPaymentStatus = PaymentStatus.Paid;
                            //mark order as paid
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                _orderService.UpdateOrder(order);
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                            _logger.Information("Success !!!. PaymentStatus: PAID");
                        }
                        //return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
                    }
                    else if ("NO".Equals(form.GetValues("TM_Status")[0]))
                    {
                        _logger.Error(form.GetValues("TM_ErrorMsg")[0]);
                        //return RedirectToAction("Index", "Home", new { area = "" });
                    }
                }
                catch (Exception e) {
                    _logger.Error(e.Message + " " + e.StackTrace);
                    ErrorNotification(e.Message);
                }
            }
            else
            {
                orderNumberGuid = new Guid(Request.Params.GetValues("orderGuid")[0]);
                var order = _orderService.GetOrderByGuid(orderNumberGuid);
                //return url
                if (order.PaymentStatus == PaymentStatus.Authorized || order.PaymentStatus == PaymentStatus.Paid)
                {
                    _logger.Information(order.OrderNotes.ToString());
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }
            }

            return(RedirectToAction("Index", "Home", new { area = "" }));
            //if (order != null)
            //{
            //    var sb = new StringBuilder();
            //    //sb.AppendLine("TM_MCode: " + form.GetValues("TM_MCode")[0]);
            //    //sb.AppendLine("TM_RefNo: " + form.GetValues("TM_RefNo")[0]);
            //    //sb.AppendLine("TM_Currency: " + form.GetValues("TM_Currency")[0]);
            //    //sb.AppendLine("TM_DebitAmt: " + form.GetValues("TM_DebitAmt")[0]);
            //    sb.AppendLine("TM_Status: " + form.GetValues("TM_Status")[0]);
            //    //sb.AppendLine("TM_ErrorMsg: " + form.GetValues("TM_ErrorMsg")[0]);
            //    //sb.AppendLine("TM_PaymentType: " + form.GetValues("TM_PaymentType")[0]);
            //    //sb.AppendLine("TM_ApprovalCode: " + form.GetValues("TM_ApprovalCode")[0]);
            //    //sb.AppendLine("TM_BankRespCode: " + form.GetValues("TM_BankRespCode")[0]);
            //    //sb.AppendLine("TM_Error: " + form.GetValues("TM_Error")[0]);
            //    //sb.AppendLine("TM_UserField1: " + form.GetValues("TM_UserField1")[0]);
            //    //sb.AppendLine("TM_UserField2: " + form.GetValues("TM_UserField2")[0]);
            //    //sb.AppendLine("TM_UserField3: " + form.GetValues("TM_UserField3")[0]);
            //    //sb.AppendLine("TM_UserField4: " + form.GetValues("TM_UserField4")[0]);
            //    //sb.AppendLine("TM_UserField5: " + form.GetValues("TM_UserField5")[0]);
            //    //sb.AppendLine("TM_CCLast4Digit: " + form.GetValues("TM_CCLast4Digit")[0]);
            //    //sb.AppendLine("TM_ExpiryDate: " + form.GetValues("TM_ExpiryDate")[0]);
            //    //sb.AppendLine("TM_TrnType: " + form.GetValues("TM_TrnType")[0]);
            //    //sb.AppendLine("TM_SubTrnType: " + form.GetValues("TM_SubTrnType")[0]);
            //    //sb.AppendLine("TM_CCNum: " + form.GetValues("TM_CCNum")[0]);
            //    //sb.AppendLine("TM_IPP_FirstPayment: " + form.GetValues("TM_IPP_FirstPayment")[0]);
            //    //sb.AppendLine("TM_IPP_LastPayment: " + form.GetValues("TM_IPP_LastPayment")[0]);
            //    //sb.AppendLine("TM_IPP_MonthlyPayment: " + form.GetValues("TM_IPP_MonthlyPayment")[0]);
            //    //sb.AppendLine("TM_IPP_TransTenure: " + form.GetValues("TM_IPP_TransTenure")[0]);
            //    //sb.AppendLine("TM_IPP_TotalInterest: " + form.GetValues("TM_IPP_TotalInterest")[0]);
            //    //sb.AppendLine("TM_IPP_DownPayment: " + form.GetValues("TM_IPP_DownPayment")[0]);
            //    //sb.AppendLine("TM_IPP_MonthlyInterest: " + form.GetValues("TM_IPP_MonthlyInterest")[0]);
            //    //sb.AppendLine("TM_Original_RefNo: " + form.GetValues("TM_Original_RefNo")[0]);
            //    //sb.AppendLine("TM_Signature: " + form.GetValues("TM_Signature")[0]);
            //    //sb.AppendLine("TM_OriginalPayType: " + form.GetValues("TM_OriginalPayType")[0]);

            //    //order note
            //    order.OrderNotes.Add(new OrderNote
            //    {
            //        Note = sb.ToString(),
            //        DisplayToCustomer = false,
            //        CreatedOnUtc = DateTime.UtcNow,
            //        OrderId = order.Id,

            //    });
            //    _orderService.UpdateOrder(order);

            //    if ("YES".Equals(form.GetValues("TM_Status")[0]))
            //    {
            //        if ("auth".Equals(form.GetValues("TM_TrnType")[0]))
            //        {
            //            newPaymentStatus = PaymentStatus.Authorized;
            //        }
            //        else if ("sale".Equals(form.GetValues("TM_TrnType")[0])) {
            //            newPaymentStatus = PaymentStatus.Paid;
            //        }

            //        _logger.Information("Success !!!. PaymentStatus: PAID");
            //    }
            //    else if ("NO".Equals(form.GetValues("TM_Status")[0]))
            //    {
            //         _logger.Error(form.GetValues("TM_ErrorMsg")[0]);
            //         return RedirectToAction("Index", "Home", new { area = "" });
            //    }

            //    //mark order as paid
            //    if (newPaymentStatus == PaymentStatus.Paid)
            //    {
            //        if (_orderProcessingService.CanMarkOrderAsPaid(order))
            //        {
            //            _orderService.UpdateOrder(order);
            //            _orderProcessingService.MarkOrderAsPaid(order);
            //        }
            //    }
            //    return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
            //}
            //else {
            //    //return RedirectToRoute("CheckoutCompleted", new { orderId = Request.Params.GetValues("orderId")[0] });
            //    return RedirectToAction("Index", "Home", new { area = "" });
            //}
        }
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="orderNumber">Order number</param>
        /// <returns>Returns true for success else false</returns>
        protected virtual bool ProcessPayment(string orderNumber)
        {
            Guid orderNumberGuid;

            try
            {
                orderNumberGuid = new Guid(orderNumber);
            }
            catch
            {
                orderNumberGuid = Guid.Empty;
            }

            var order       = _orderService.GetOrderByGuid(orderNumberGuid);
            var sezzleOrder = _sezzleHttpClient.GetOrderFromSezzle(orderNumber).GetAwaiter().GetResult();

            if (sezzleOrder == null)
            {
                var note = $"Sezzle Order is not found. Sezzle Order Reference #{orderNumber}";
                _logger.Error(note, new NopException(orderNumber));

                order.OrderNotes.Add(new OrderNote
                {
                    Note = note,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                _orderService.UpdateOrder(order);
                return(false);
            }

            DateTime captureExpirationInUtc = Convert.ToDateTime(sezzleOrder.CaptureExpiration).ToUniversalTime();

            var(isValid, errorMsg) = ValidateCaptureExpiration(sezzleOrder, captureExpirationInUtc);
            if (!isValid && !String.IsNullOrEmpty(errorMsg))
            {
                _logger.Error(errorMsg, new NopException(orderNumber));

                order.OrderNotes.Add(new OrderNote
                {
                    Note = errorMsg,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                _orderService.UpdateOrder(order);
                return(false);
            }


            //validate order total
            if (!(sezzleOrder.AmountInCents).Equals((int)Math.Round(order.OrderTotal * 100, 2)))
            {
                var errorStr = $"Sezzle Returned order total {sezzleOrder.AmountInCents} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                //log
                _logger.Error(errorStr);
                //order note
                order.OrderNotes.Add(new OrderNote
                {
                    Note = errorStr,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);

                return(false);
            }

            switch (_sezzlePaymentSettings.TransactionMode)
            {
            case TransactionMode.Authorize:
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    order.AuthorizationTransactionId     = orderNumber;
                    order.AuthorizationTransactionResult = "Authorized";
                    _orderService.UpdateOrder(order);
                    _orderProcessingService.MarkAsAuthorized(order);

                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = $"Capture the payment before {captureExpirationInUtc}",
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);
                    return(true);
                }
                break;

            case TransactionMode.AuthorizeAndCapture:
                if (String.IsNullOrEmpty(sezzleOrder.CapturedAt) && _orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    var captureStatus = _sezzleHttpClient.CapturePayment(order.OrderGuid.ToString())
                                        .GetAwaiter()
                                        .GetResult();

                    if (!captureStatus)
                    {
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = $"Something went wrong while capturing",
                            DisplayToCustomer = false,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        return(false);
                    }

                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = $"Payment captured by Sezzle",
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    order.CaptureTransactionId     = orderNumber;
                    order.CaptureTransactionResult = "Captured";
                    _orderService.UpdateOrder(order);
                    _orderProcessingService.MarkOrderAsPaid(order);
                    return(true);
                }
                break;
            }
            return(false);
        }
예제 #18
0
        public void HandleIPN(string ipnData)
        {
            Dictionary <string, string> values;

            if (VerifyIPN(ipnData, out values))
            {
                #region values
                decimal total = decimal.Zero;
                try
                {
                    total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                string payer_status = string.Empty;
                values.TryGetValue("payer_status", out payer_status);
                string payment_status = string.Empty;
                values.TryGetValue("payment_status", out payment_status);
                string pending_reason = string.Empty;
                values.TryGetValue("pending_reason", out pending_reason);
                string mc_currency = string.Empty;
                values.TryGetValue("mc_currency", out mc_currency);
                string txn_id = string.Empty;
                values.TryGetValue("txn_id", out txn_id);
                string txn_type = string.Empty;
                values.TryGetValue("txn_type", out txn_type);
                string rp_invoice_id = string.Empty;
                values.TryGetValue("rp_invoice_id", out rp_invoice_id);
                string payment_type = string.Empty;
                values.TryGetValue("payment_type", out payment_type);
                string payer_id = string.Empty;
                values.TryGetValue("payer_id", out payer_id);
                string receiver_id = string.Empty;
                values.TryGetValue("receiver_id", out receiver_id);
                string invoice = string.Empty;
                values.TryGetValue("invoice", out invoice);
                string payment_fee = string.Empty;
                values.TryGetValue("payment_fee", out payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("Paypal IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                    #region Recurring payment
                {
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(0, 0, initialOrder.Id, null, 0, int.MaxValue);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (recurringPaymentHistory.Count == 0)
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory()
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    _orderProcessingService.ProcessNextRecurringPayment(rp);
                                }
                            }
                            break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        _logger.Information("PayPal IPN. Recurring info", new NopException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;

                default:
                    #region Standard payment
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote()
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("PayPal IPN failed.", new NopException(ipnData));
            }
        }
예제 #19
0
 /// <summary>
 /// Marks order as authorized
 /// </summary>
 /// <param name="order">Order</param>
 public void MarkAsAuthorized(Order order)
 {
     _orderProcessingService.MarkAsAuthorized(order);
 }
예제 #20
0
        protected virtual void ProcessPayment(string orderNumber, string ipnInfo, PaymentStatus newPaymentStatus, decimal mcGross, string transactionId)
        {
            Guid orderNumberGuid;

            try
            {
                orderNumberGuid = new Guid(orderNumber);
            }
            catch
            {
                orderNumberGuid = Guid.Empty;
            }

            var order = _orderService.GetOrderByGuid(orderNumberGuid);

            if (order == null)
            {
                _logger.Error("PayPal IPN. Order is not found", new NopException(ipnInfo));
                return;
            }

            //order note
            _orderService.InsertOrderNote(new OrderNote
            {
                OrderId           = order.Id,
                Note              = ipnInfo,
                DisplayToCustomer = false,
                CreatedOnUtc      = DateTime.UtcNow
            });

            //validate order total
            if ((newPaymentStatus == PaymentStatus.Authorized || newPaymentStatus == PaymentStatus.Paid) && !Math.Round(mcGross, 2).Equals(Math.Round(order.OrderTotal, 2)))
            {
                var errorStr = $"PayPal IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                //log
                _logger.Error(errorStr);
                //order note
                _orderService.InsertOrderNote(new OrderNote
                {
                    OrderId           = order.Id,
                    Note              = errorStr,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                return;
            }

            switch (newPaymentStatus)
            {
            case PaymentStatus.Authorized:
                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                {
                    _orderProcessingService.MarkAsAuthorized(order);
                }
                break;

            case PaymentStatus.Paid:
                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    order.AuthorizationTransactionId = transactionId;
                    _orderService.UpdateOrder(order);

                    _orderProcessingService.MarkOrderAsPaid(order);
                }

                break;

            case PaymentStatus.Refunded:
                var totalToRefund = Math.Abs(mcGross);
                if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))
                {
                    //refund
                    if (_orderProcessingService.CanRefundOffline(order))
                    {
                        _orderProcessingService.RefundOffline(order);
                    }
                }
                else
                {
                    //partial refund
                    if (_orderProcessingService.CanPartiallyRefundOffline(order, totalToRefund))
                    {
                        _orderProcessingService.PartiallyRefundOffline(order, totalToRefund);
                    }
                }

                break;

            case PaymentStatus.Voided:
                if (_orderProcessingService.CanVoidOffline(order))
                {
                    _orderProcessingService.VoidOffline(order);
                }

                break;
            }
        }
        public void HandleIPN(string ipnData)
        {
            if (VerifyIPN(ipnData, out var values))
            {
                values.TryGetValue("payer_status", out _);
                values.TryGetValue("payment_status", out var paymentStatus);
                values.TryGetValue("pending_reason", out var pendingReason);
                values.TryGetValue("mc_currency", out _);
                values.TryGetValue("txn_id", out _);
                values.TryGetValue("txn_type", out var txnType);
                values.TryGetValue("rp_invoice_id", out var rpInvoiceId);
                values.TryGetValue("payment_type", out _);
                values.TryGetValue("payer_id", out _);
                values.TryGetValue("receiver_id", out _);
                values.TryGetValue("invoice", out _);
                values.TryGetValue("payment_fee", out _);

                var sb = new StringBuilder();
                sb.AppendLine("Paypal IPN:");
                foreach (var kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = GetPaymentStatus(paymentStatus, pendingReason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txnType)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                {
                    var orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rpInvoiceId);
                    }
                    catch
                    {
                        // ignored
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(0, 0, initialOrder.Id);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (recurringPaymentHistory.Count == 0)
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    _orderProcessingService.ProcessNextRecurringPayment(rp);
                                }
                            }

                            break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        _logger.Information("PayPal IPN. Recurring info", new NopException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }

                break;

                default:
                {
                    values.TryGetValue("custom", out var orderNumber);
                    var orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                        // ignored
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                            break;

                        case PaymentStatus.Authorized:
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                            break;

                        case PaymentStatus.Paid:
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                            break;

                        case PaymentStatus.Refunded:
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                            break;

                        case PaymentStatus.Voided:
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                            break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }

                break;
                }
            }
            else
            {
                _logger.Error("PayPal IPN failed.", new NopException(ipnData));
            }
        }
예제 #22
0
        public ActionResult IPNHandler()
        {
            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") as PayPalStandardPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            if (processor.VerifyIpn(strRequest, out values))
            {
                #region values
                decimal mc_gross = decimal.Zero;
                try
                {
                    mc_gross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                string payer_status = string.Empty;
                values.TryGetValue("payer_status", out payer_status);
                string payment_status = string.Empty;
                values.TryGetValue("payment_status", out payment_status);
                string pending_reason = string.Empty;
                values.TryGetValue("pending_reason", out pending_reason);
                string mc_currency = string.Empty;
                values.TryGetValue("mc_currency", out mc_currency);
                string txn_id = string.Empty;
                values.TryGetValue("txn_id", out txn_id);
                string txn_type = string.Empty;
                values.TryGetValue("txn_type", out txn_type);
                string rp_invoice_id = string.Empty;
                values.TryGetValue("rp_invoice_id", out rp_invoice_id);
                string payment_type = string.Empty;
                values.TryGetValue("payment_type", out payment_type);
                string payer_id = string.Empty;
                values.TryGetValue("payer_id", out payer_id);
                string receiver_id = string.Empty;
                values.TryGetValue("receiver_id", out receiver_id);
                string invoice = string.Empty;
                values.TryGetValue("invoice", out invoice);
                string payment_fee = string.Empty;
                values.TryGetValue("payment_fee", out payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("Paypal IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = PaypalHelper.GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                    #region Recurring payment
                case "recurring_payment":
                {
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (!recurringPaymentHistory.Any())
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    var processPaymentResult = new ProcessPaymentResult();
                                    processPaymentResult.NewPaymentStatus = newPaymentStatus;
                                    if (newPaymentStatus == PaymentStatus.Authorized)
                                    {
                                        processPaymentResult.AuthorizationTransactionId = txn_id;
                                    }
                                    else
                                    {
                                        processPaymentResult.CaptureTransactionId = txn_id;
                                    }

                                    _orderProcessingService.ProcessNextRecurringPayment(rp, processPaymentResult);
                                }
                            }
                            break;

                            case PaymentStatus.Voided:
                                //failed payment
                                var failedPaymentResult = new ProcessPaymentResult
                                {
                                    Errors = new[] { string.Format("PayPal IPN. Recurring payment is {0} .", payment_status) },
                                    RecurringPaymentFailed = true
                                };
                                _orderProcessingService.ProcessNextRecurringPayment(rp, failedPaymentResult);
                                break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        _logger.Information("PayPal IPN. Recurring info", new NopException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                break;

                case "recurring_payment_failed":
                    var orderGuid = Guid.Empty;
                    if (Guid.TryParse(rp_invoice_id, out orderGuid))
                    {
                        var initialOrder = _orderService.GetOrderByGuid(orderGuid);
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            //failed payment
                            if (recurringPayment != null)
                            {
                                _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, new ProcessPaymentResult {
                                    Errors = new[] { txn_type }, RecurringPaymentFailed = true
                                });
                            }
                        }
                    }
                    break;

                    #endregion
                default:
                    #region Standard payment
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            //validate order total
                            if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //valid
                                if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                                {
                                    _orderProcessingService.MarkAsAuthorized(order);
                                }
                            }
                            else
                            {
                                //not valid
                                string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal, order.Id);
                                //log
                                _logger.Error(errorStr);
                                //order note
                                order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = errorStr,
                                            DisplayToCustomer = false,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });
                                _orderService.UpdateOrder(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            //validate order total
                            if (Math.Round(mc_gross, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //valid
                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                {
                                    order.AuthorizationTransactionId = txn_id;
                                    _orderService.UpdateOrder(order);

                                    _orderProcessingService.MarkOrderAsPaid(order);
                                }
                            }
                            else
                            {
                                //not valid
                                string errorStr = string.Format("PayPal IPN. Returned order total {0} doesn't equal order total {1}. Order# {2}.", mc_gross, order.OrderTotal, order.Id);
                                //log
                                _logger.Error(errorStr);
                                //order note
                                order.OrderNotes.Add(new OrderNote
                                        {
                                            Note = errorStr,
                                            DisplayToCustomer = false,
                                            CreatedOnUtc      = DateTime.UtcNow
                                        });
                                _orderService.UpdateOrder(order);
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            var totalToRefund = Math.Abs(mc_gross);
                            if (totalToRefund > 0 && Math.Round(totalToRefund, 2).Equals(Math.Round(order.OrderTotal, 2)))
                            {
                                //refund
                                if (_orderProcessingService.CanRefundOffline(order))
                                {
                                    _orderProcessingService.RefundOffline(order);
                                }
                            }
                            else
                            {
                                //partial refund
                                if (_orderProcessingService.CanPartiallyRefundOffline(order, totalToRefund))
                                {
                                    _orderProcessingService.PartiallyRefundOffline(order, totalToRefund);
                                }
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("PayPal IPN failed.", new NopException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
예제 #23
0
        public ActionResult SamanCallback(string refNum, string resNum, string state, string traceNo)
        {
            var callbackResult = new SamanCallbackResult
            {
                ReferenceNumber   = refNum,
                ReservationNumber = resNum,
                State             = state,
                TraceNumber       = traceNo
            };

            // load settings for a chosen store scope
            var  storeScope           = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var  samanPaymentSettings = _settingService.LoadSetting <SamanPaymentSettings>(storeScope);
            Guid orderGuid;

            try
            {
                orderGuid = Guid.Parse(resNum);
            }
            catch (Exception ex)
            {
                _logger.Error("Callback failed.", ex);
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }

            var order = _orderService.GetOrderByGuid(orderGuid);

            if (order == null)
            {
                _logger.Error("Callback failed.", new NopException("Order is null."));
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }

            order.AuthorizationTransactionResult = callbackResult.ToString();

            _orderService.UpdateOrder(order);

            ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return(true); };

            var service = new Sep.ReferencePayment.PaymentIFBinding();
            var result  = service.verifyTransaction(refNum, samanPaymentSettings.MerchantId);

            order.AuthorizationTransactionCode = result.ToString();

            _orderService.UpdateOrder(order);

            if (result > 0)
            {
                _orderProcessingService.MarkAsAuthorized(order);

                if (result == (double)order.OrderTotal)
                {
                    _orderProcessingService.MarkOrderAsPaid(order);
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    var reverseId = service.reverseTransaction(refNum, samanPaymentSettings.MerchantId, samanPaymentSettings.MerchantId, samanPaymentSettings.Passcode);
                    order.CaptureTransactionId = reverseId.ToString();
                    _orderService.UpdateOrder(order);

                    if (reverseId == 1)
                    {
                        _orderProcessingService.Refund(order);
                        _logger.Error("Transaction reverse process was successful.", new NopException(reverseId.ToString()));
                    }
                    else
                    {
                        _logger.Error("Transaction reverse process was not successful.", new NopException(reverseId.ToString()));
                    }

                    return(RedirectToAction("Index", "Home", new { area = "" }));
                }
            }
            else
            {
                _logger.Error("Transaction verification failed.", new NopException(result.ToString()));
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }
        }
예제 #24
0
        public ActionResult IPNHandler()
        {
            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.PayPalStandard") as PayPalStandardPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            if (processor.VerifyIpn(strRequest, out values))
            {
                #region values
                decimal total = decimal.Zero;
                try
                {
                    total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch { }

                string payer_status = string.Empty;
                values.TryGetValue("payer_status", out payer_status);
                string payment_status = string.Empty;
                values.TryGetValue("payment_status", out payment_status);
                string pending_reason = string.Empty;
                values.TryGetValue("pending_reason", out pending_reason);
                string mc_currency = string.Empty;
                values.TryGetValue("mc_currency", out mc_currency);
                string txn_id = string.Empty;
                values.TryGetValue("txn_id", out txn_id);
                string txn_type = string.Empty;
                values.TryGetValue("txn_type", out txn_type);
                string rp_invoice_id = string.Empty;
                values.TryGetValue("rp_invoice_id", out rp_invoice_id);
                string payment_type = string.Empty;
                values.TryGetValue("payment_type", out payment_type);
                string payer_id = string.Empty;
                values.TryGetValue("payer_id", out payer_id);
                string receiver_id = string.Empty;
                values.TryGetValue("receiver_id", out receiver_id);
                string invoice = string.Empty;
                values.TryGetValue("invoice", out invoice);
                string payment_fee = string.Empty;
                values.TryGetValue("payment_fee", out payment_fee);

                #endregion

                var sb = new StringBuilder();
                sb.AppendLine("Paypal IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }

                var newPaymentStatus = PaypalHelper.GetPaymentStatus(payment_status, pending_reason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txn_type)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                    #region Recurring payment
                {
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(rp_invoice_id);
                    }
                    catch
                    {
                    }

                    var initialOrder = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (initialOrder != null)
                    {
                        var recurringPayments = _orderService.SearchRecurringPayments(0, 0, initialOrder.Id, null, 0, int.MaxValue);
                        foreach (var rp in recurringPayments)
                        {
                            switch (newPaymentStatus)
                            {
                            case PaymentStatus.Authorized:
                            case PaymentStatus.Paid:
                            {
                                var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                if (recurringPaymentHistory.Count == 0)
                                {
                                    //first payment
                                    var rph = new RecurringPaymentHistory
                                    {
                                        RecurringPaymentId = rp.Id,
                                        OrderId            = initialOrder.Id,
                                        CreatedOnUtc       = DateTime.UtcNow
                                    };
                                    rp.RecurringPaymentHistory.Add(rph);
                                    _orderService.UpdateRecurringPayment(rp);
                                }
                                else
                                {
                                    //next payments
                                    _orderProcessingService.ProcessNextRecurringPayment(rp);
                                }
                            }
                            break;
                            }
                        }

                        //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                        _logger.Information("PayPal IPN. Recurring info", new NopException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;

                default:
                    #region Standard payment
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }

                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                order.AuthorizationTransactionId = txn_id;
                                _orderService.UpdateOrder(order);

                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;


                        default:
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("PayPal IPN failed.", new NopException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
        public ActionResult PayFastNotify()
        {
            _logger.InsertLog(LogLevel.Information, "PayFast ITN Received");
            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.PayFast") as PayFastPaymentProcessor;

            if (processor == null ||
                !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
            {
                throw new NopException("PayFast module cannot be loaded");
            }
            _logger.InsertLog(LogLevel.Information, "Verifying Payfast ITN");
            if (processor.VerifyIPN(strRequest, out values))
            {
                _logger.InsertLog(LogLevel.Information, "PayFast Verifying ITN Verified");
                _logger.InsertLog(LogLevel.Information, "PayFast retrieving values");

                string paymentStatus;
                values.TryGetValue("payment_status", out paymentStatus);
                string pendingReason;
                values.TryGetValue("pending_reason", out pendingReason);
                string txnId;
                values.TryGetValue("pf_payment_id", out txnId);
                string txnType;
                values.TryGetValue("txn_type", out txnType);

                var sb = new StringBuilder();
                sb.AppendLine("PayFast IPN:");
                foreach (KeyValuePair <string, string> kvp in values)
                {
                    sb.AppendLine(kvp.Key + ": " + kvp.Value);
                }
                _logger.InsertLog(LogLevel.Information, sb.ToString());
                var newPaymentStatus = PayFastHelper.GetPaymentStatus(paymentStatus, pendingReason);
                sb.AppendLine("New payment status: " + newPaymentStatus);

                switch (txnType)
                {
                case "recurring_payment_profile_created":
                    //do nothing here
                    break;

                case "recurring_payment":
                    //do nothing here
                    break;

                default:
                    #region Standard payment
                {
                    string orderNumber;
                    values.TryGetValue("m_payment_id", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch
                    {
                    }
                    _logger.InsertLog(LogLevel.Information, "Completing order: " + orderNumber);
                    var order = _orderService.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote()
                            {
                                Note = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                        _orderService.UpdateOrder(order);

                        switch (newPaymentStatus)
                        {
                        case PaymentStatus.Pending:
                        {
                        }
                        break;

                        case PaymentStatus.Authorized:
                        {
                            if (_orderProcessingService.CanMarkOrderAsAuthorized(order))
                            {
                                _orderProcessingService.MarkAsAuthorized(order);
                            }
                        }
                        break;

                        case PaymentStatus.Paid:
                        {
                            _logger.InsertLog(LogLevel.Information, "Setting order as paid");
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                order.AuthorizationTransactionId = txnId;
                                _orderService.UpdateOrder(order);

                                _orderProcessingService.MarkOrderAsPaid(order);
                                _logger.InsertLog(LogLevel.Information, string.Format("Order: {0} paid", orderNumber));
                            }
                        }
                        break;

                        case PaymentStatus.Refunded:
                        {
                            if (_orderProcessingService.CanRefundOffline(order))
                            {
                                _orderProcessingService.RefundOffline(order);
                            }
                        }
                        break;

                        case PaymentStatus.Voided:
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;

                        default:
                            _logger.InsertLog(LogLevel.Error, "No Payment status found");
                            break;
                        }
                    }
                    else
                    {
                        _logger.Error("PayFast IPN. Order is not found", new NopException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("PayFast IPN failed.", new NopException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }