public void Ensure_order_can_only_be_voided_offline_when_paymentstatus_is_authorized()
        {
            var order = new Order
            {
                OrderTotal = 1,
            };

            foreach (OrderStatus os in Enum.GetValues(typeof(OrderStatus)))
            {
                foreach (PaymentStatus ps in Enum.GetValues(typeof(PaymentStatus)))
                {
                    foreach (ShippingStatus ss in Enum.GetValues(typeof(ShippingStatus)))
                    {
                        order.OrderStatus    = os;
                        order.PaymentStatus  = ps;
                        order.ShippingStatus = ss;

                        if (ps == PaymentStatus.Authorized)
                        {
                            _orderProcessingService.CanVoidOffline(order).ShouldBeTrue();
                        }
                        else
                        {
                            _orderProcessingService.CanVoidOffline(order).ShouldBeFalse();
                        }
                    }
                }
            }
        }
        public IActionResult Success()
        {
            var   orderId          = _webHelper.QueryString <string>("x_reference");
            var   oxipayStatus     = _webHelper.QueryString <string>("x_result");
            var   oxipayOrderId    = _webHelper.QueryString <string>("x_gateway_reference");
            var   newPaymentStatus = OxipayHelper.GetPaymentStatus(oxipayStatus, null);
            Order order            = null;

            if (Guid.TryParse(orderId, out Guid orderGuid))
            {
                order = _orderService.GetOrderByGuid(orderGuid);
            }
            if (order != null)
            {
                order.OrderNotes.Add(new OrderNote
                {
                    Note = "Oxipay order ID: " + oxipayOrderId,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });
                _orderService.UpdateOrder(order);
            }
            switch (newPaymentStatus)
            {
            case PaymentStatus.Pending:
            {}
            break;

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

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

            default:
                break;
            }
            if (order == null)
            {
                return(RedirectToAction("Index", "Home", new { area = string.Empty }));
            }

            return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
        }
 /// <summary>
 /// Void
 /// </summary>
 /// <param name="order">Order</param>
 /// <param name="authorization">Authorization</param>
 private void MarkOrderAsVoided(Core.Domain.Orders.Order order, Authorization authorization)
 {
     if (_orderProcessingService.CanVoidOffline(order))
     {
         order.AuthorizationTransactionId     = authorization.Id;
         order.AuthorizationTransactionResult = $"{authorization.Status}. {authorization.AuthorizationStatusDetails?.Reason}";
         _orderService.UpdateOrder(order);
         _orderProcessingService.VoidOffline(order);
     }
 }
示例#4
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);
        }
示例#5
0
        /// <returns>A task that represents the asynchronous operation</returns>
        protected virtual async Task ProcessPaymentAsync(string orderNumber, string ipnInfo, PaymentStatus newPaymentStatus, decimal mcGross, string transactionId)
        {
            Guid orderNumberGuid;

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

            var order = await _orderService.GetOrderByGuidAsync(orderNumberGuid);

            if (order == null)
            {
                await _logger.ErrorAsync("Paytm IPN. Order is not found", new NopException(ipnInfo));

                return;
            }

            //order note
            await _orderService.InsertOrderNoteAsync(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 = $"Paytm IPN. Returned order total {mcGross} doesn't equal order total {order.OrderTotal}. Order# {order.Id}.";
                //log
                await _logger.ErrorAsync(errorStr);

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

                return;
            }

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

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

                    await _orderProcessingService.MarkOrderAsPaidAsync(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))
                    {
                        await _orderProcessingService.RefundOfflineAsync(order);
                    }
                }
                else
                {
                    //partial refund
                    if (_orderProcessingService.CanPartiallyRefundOffline(order, totalToRefund))
                    {
                        await _orderProcessingService.PartiallyRefundOfflineAsync(order, totalToRefund);
                    }
                }

                break;

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

                break;
            }
        }
示例#6
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(""));
        }
示例#7
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 NasException("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 NasException(sb.ToString()));
                    }
                    else
                    {
                        _logger.Error("PayPal IPN. Order is not found", new NasException(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;

                        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 NasException(sb.ToString()));
                    }
                }
                    #endregion
                    break;
                }
            }
            else
            {
                _logger.Error("PayPal IPN failed.", new NasException(strRequest));
            }

            //nothing should be rendered to visitor
            return(Content(""));
        }
示例#8
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));
            }
        }
示例#9
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);
        }
        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));
            }
        }
示例#11
0
 /// <summary>
 /// Gets a value indicating whether order can be marked as voided
 /// </summary>
 /// <param name="order">Order</param>
 /// <returns>A value indicating whether order can be marked as voided</returns>
 public bool CanVoidOffline(Order order)
 {
     return(_orderProcessingService.CanVoidOffline(order));
 }
        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(""));
        }
示例#13
0
        public ActionResult Return()
        {
            var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.IpayAfrica") as IpayAfricaPaymentProcessor;

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


            var    myUtility = new IpayAfricaHelper();
            string orderId, Amount, AuthDesc, ResCode;
            bool   checkSumMatch = false;

            //Assign following values to send it to verifychecksum function.
            if (String.IsNullOrWhiteSpace(_IpayAfricaPaymentSettings.MerchantKey))
            {
                throw new NopException("IpayAfrica key is not set");
            }

            string workingKey         = _IpayAfricaPaymentSettings.MerchantKey;
            string IpayAfricaChecksum = null;
            string transactinon_code  = HttpContext.Request.Query["txncd"];
            string qwh = HttpContext.Request.Query["qwh"];
            string afd = HttpContext.Request.Query["afd"];
            string agt = HttpContext.Request.Query["agt"];
            string uyt = HttpContext.Request.Query["uyt"];
            string ifd = HttpContext.Request.Query["ifd"];
            string poi = HttpContext.Request.Query["poi"];
            string returned_order_id      = HttpContext.Request.Query["id"];
            string returned_order_invoice = HttpContext.Request.Query["ivm"];
            string status       = HttpContext.Request.Query["status"];
            string paid_total   = HttpContext.Request.Query["mc"] + "00";
            string p1           = HttpContext.Request.Query["p1"];
            string p2           = HttpContext.Request.Query["p2"];
            string p3           = HttpContext.Request.Query["p3"];
            string p4           = HttpContext.Request.Query["p4"];
            string msisdn_id    = HttpContext.Request.Query["msisdn_id"];
            string msisdn_idnum = HttpContext.Request.Query["msisdn_idnum"];
            string channel      = HttpContext.Request.Query["channel"];
            string hash_id      = HttpContext.Request.Query["hsh"];

            Dictionary <string, string> parameters = new Dictionary <string, string>();

            Dictionary <string, string> parameters1 = new Dictionary <string, string>
            {
                ["txncd"]        = transactinon_code,
                ["qwh"]          = qwh,
                ["afd"]          = afd,
                ["poi"]          = poi,
                ["uyt"]          = uyt,
                ["ifd"]          = ifd,
                ["agt"]          = agt,
                ["id"]           = returned_order_id,
                ["status"]       = status,
                ["ivm"]          = returned_order_invoice,
                ["mc"]           = paid_total,
                ["p1"]           = p1,
                ["p2"]           = p2,
                ["p3"]           = p3,
                ["p4"]           = p4,
                ["msisdn_id"]    = p1,
                ["msisdn_idnum"] = p2,
                ["channel"]      = p3,
                ["p4"]           = p4,
                ["hsh"]          = HttpContext.Request.Query["hsh"]
            };

            var    live           = "1";
            string key            = _IpayAfricaPaymentSettings.MerchantKey;
            var    storeLocation  = _webHelper.GetStoreLocation();
            string vendor_id      = _IpayAfricaPaymentSettings.MerchantId;
            string currency       = p3;
            string customer_email = p1;
            string mobile_number  = msisdn_idnum;
            string callback_url   = p2;
            string email_notify   = "1";
            string curl           = p4;

            if (mobile_number.Length > 10)
            {
                mobile_number = mobile_number.Remove(0, 3).Insert(0, "0");
            }

            string datastring = live.ToString() + returned_order_id + returned_order_invoice + paid_total + mobile_number + customer_email + vendor_id + currency + p1 + p2 + p3 + p4 + callback_url + email_notify + curl;

            byte[] keyByte      = new ASCIIEncoding().GetBytes(key);
            byte[] messageBytes = new ASCIIEncoding().GetBytes(datastring);
            byte[] hashmessage  = new HMACSHA1(keyByte).ComputeHash(messageBytes);
            String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2")));
            string hash_message = String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2")));

            if (hash_id != null)
            {
                IpayAfricaChecksum = hash_id;
            }
            if (IpayAfricaChecksum == String.Concat(Array.ConvertAll(hashmessage, x => x.ToString("x2"))))
            {
                checkSumMatch = true;
            }

            orderId  = returned_order_id;
            Amount   = HttpContext.Request.Query["mc"];
            ResCode  = returned_order_invoice;
            AuthDesc = status;

            var order = _orderService.GetOrderById(Convert.ToInt32(orderId));

            if (checkSumMatch == true)
            {
                if (AuthDesc == "aei7p7yrx4ae34")
                {
                    string ipnurl2 = "https://www.ipayafrica.com/ipn/?vendor=" + _IpayAfricaPaymentSettings.MerchantId + "&id=" + HttpContext.Request.Query["id"] + "&ivm=" + HttpContext.Request.Query["ivm"] + "&qwh=" + HttpContext.Request.Query["qwh"] + "&afd=" + HttpContext.Request.Query["afd"] + "&poi=" + HttpContext.Request.Query["poi"] + "&uyt=" + HttpContext.Request.Query["uyt"] + "&ifd=" + HttpContext.Request.Query["ifd"];

                    string html = string.Empty;
                    string url  = ipnurl2;

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        using (Stream stream = response.GetResponseStream())
                            using (StreamReader reader = new StreamReader(stream))
                            {
                                html = reader.ReadToEnd();
                            }
                    if (TxnStatus(orderId, order.OrderTotal.ToString("0.00")))
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            //order note
                            order.OrderNotes.Add(new OrderNote
                            {
                                Note = "Thank you for shopping with us. Your " + channel + " transaction was successful. Your transaction code was " + transactinon_code,
                                DisplayToCustomer = true,
                                CreatedOnUtc      = DateTime.UtcNow
                            });
                            //_orderService.UpdateOrder(order);
                            _orderProcessingService.MarkOrderAsPaid(order);
                        }
                        return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                    }
                    else
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Failed due to amount mismatch. Your attempt to pay via " + channel + " was successful. Your transaction code was " + transactinon_code,
                            DisplayToCustomer = true,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        //_orderService.UpdateOrder(order);
                        return(Content("Amount Mismatch" + " " + html + " " + order.OrderTotal.ToString()));
                    }
                }
                else if (AuthDesc == "fe2707etr5s4wq")
                {
                    _orderProcessingService.CancelOrder(order, false);
                    order.OrderStatus = OrderStatus.Cancelled;
                    _orderService.UpdateOrder(order);
                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
                else
                {
                    return(Content("Security Error. Illegal access detected. Please try again"));
                }
            }
            else if (string.IsNullOrEmpty(IpayAfricaChecksum))
            {
                return(Content("Please Contact Customer Care"));
            }
            else if (status == "dtfi4p7yty45wq")//less paid
            {
                return(Content("Payment Failed. You Paid less than what was requested"));
            }
            else if (status == "eq3i7p5yt7645e")//more paid
            {
                string ipnurl2 = "https://www.ipayafrica.com/ipn/?vendor=" + _IpayAfricaPaymentSettings.MerchantId + "&id=" + HttpContext.Request.Query["id"] + "&ivm=" + HttpContext.Request.Query["ivm"] + "&qwh=" + HttpContext.Request.Query["qwh"] + "&afd=" + HttpContext.Request.Query["afd"] + "&poi=" + HttpContext.Request.Query["poi"] + "&uyt=" + HttpContext.Request.Query["uyt"] + "&ifd=" + HttpContext.Request.Query["ifd"];

                string html = string.Empty;
                string url  = ipnurl2;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            html = reader.ReadToEnd();
                        }
                //if (html.Contains("aei7p7yrx4ae34") || html.Contains("eq3i7p5yt7645e"))
                if (html.Contains("aei7p7yrx4ae34") || html.Contains("eq3i7p5yt7645e") && System.Convert.ToDecimal(paid_total) >= order.OrderTotal)
                {
                    if (_orderProcessingService.CanMarkOrderAsPaid(order))
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Thank you for shopping with us. Your " + channel + " transaction was successful. Your transaction code was " + transactinon_code,
                            DisplayToCustomer = true,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        //_orderService.UpdateOrder(order);
                        _orderProcessingService.MarkOrderAsPaid(order);
                    }
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "Failed due to amount mismatch. You paid " + paid_total + " instead of " + order.OrderTotal + " via " + channel + " Your transaction code was " + transactinon_code,
                        DisplayToCustomer = true,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);
                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
            }
            else if (status == "bdi6p2yy76etrs")//pending
            {
                return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
            }
            else if (status == "fe2707etr5s4wq")//failed
            {
                //return Content("Security Error. Illegal access detected, Checksum failed");
                if (_orderProcessingService.CanVoidOffline(order))
                {
                    _orderProcessingService.VoidOffline(order);
                }
                return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
            }
            else
            {
                string ipnurl2 = "https://www.ipayafrica.com/ipn/?vendor=" + _IpayAfricaPaymentSettings.MerchantId + "&id=" + HttpContext.Request.Query["id"] + "&ivm=" + HttpContext.Request.Query["ivm"] + "&qwh=" + HttpContext.Request.Query["qwh"] + "&afd=" + HttpContext.Request.Query["afd"] + "&poi=" + HttpContext.Request.Query["poi"] + "&uyt=" + HttpContext.Request.Query["uyt"] + "&ifd=" + HttpContext.Request.Query["ifd"];

                string html = string.Empty;
                string url  = ipnurl2;

                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    using (Stream stream = response.GetResponseStream())
                        using (StreamReader reader = new StreamReader(stream))
                        {
                            html = reader.ReadToEnd();
                        }
                if (html.Contains("aei7p7yrx4ae34") || html.Contains("eq3i7p5yt7645e") && System.Convert.ToDecimal(paid_total) >= order.OrderTotal)
                {
                    if (_orderProcessingService.CanMarkOrderAsPaid(order))
                    {
                        //order note
                        order.OrderNotes.Add(new OrderNote
                        {
                            Note = "Thank you for shopping with us. Your " + channel + " transaction was successful. Your transaction code was " + transactinon_code,
                            DisplayToCustomer = true,
                            CreatedOnUtc      = DateTime.UtcNow
                        });
                        _orderProcessingService.MarkOrderAsPaid(order);
                    }
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
                else
                {
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "Failed due to amount mismatch. You paid " + paid_total + " instead of " + order.OrderTotal + " via " + channel + " Your transaction code was " + transactinon_code,
                        DisplayToCustomer = true,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
            }
        }
        public IActionResult IPNHandler()
        {
            var vkey     = _molPayPaymentSettings.Vkey;
            var tranID   = Request.Form["tranID"];
            var orderid  = Request.Form["orderid"];
            var status   = Request.Form["status"];
            var domain   = Request.Form["domain"];
            var amount   = Request.Form["amount"];
            var currency = Request.Form["currency"];
            var appcode  = Request.Form["appcode"];
            var paydate  = Request.Form["paydate"];
            var skey     = Request.Form["skey"];
            var nbcb     = Request.Form["nbcb"];

            var key0 = md5encode(tranID + orderid + status + domain + amount + currency);
            var key1 = md5encode(paydate + domain + key0 + appcode + vkey);

            if (skey == key1)
            {
                if (nbcb == "1")
                {
                    var order = _orderService.GetOrderByNumber(Int32.Parse(orderid));

                    var sb = new StringBuilder();
                    sb.AppendLine("MOLPay PDT:");
                    sb.AppendLine("tranID: " + tranID);
                    sb.AppendLine("orderid: " + orderid);
                    sb.AppendLine("Payment status: " + status);
                    sb.AppendLine("domain: " + domain);
                    sb.AppendLine("amount: " + amount);
                    sb.AppendLine("currency: " + currency);
                    sb.AppendLine("appcode: " + appcode);
                    sb.AppendLine("paydate: " + paydate);
                    sb.AppendLine("skey: " + skey);

                    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 = result;
                    sb.AppendLine("New payment status: " + newPaymentStatus);

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

                    if (order != null)
                    {
                        switch (status)
                        {
                        case "00":
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                order.AuthorizationTransactionId = tranID;
                                _orderService.UpdateOrder(order);

                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;

                        case "11":
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;
                        }
                    }
                    //Response.WriteAsync("CBTOKEN:MPSTATOK");
                    return(Content(Response.WriteAsync("CBTOKEN:MPSTATOK").ToString()));
                }

                if (nbcb == "2")
                {
                    var order = _orderService.GetOrderByNumber(Int32.Parse(orderid));

                    var sb = new StringBuilder();
                    sb.AppendLine("MOLPay PDT:");
                    sb.AppendLine("tranID: " + tranID);
                    sb.AppendLine("orderid: " + orderid);
                    sb.AppendLine("Payment status: " + status);
                    sb.AppendLine("domain: " + domain);
                    sb.AppendLine("amount: " + amount);
                    sb.AppendLine("currency: " + currency);
                    sb.AppendLine("appcode: " + appcode);
                    sb.AppendLine("paydate: " + paydate);
                    sb.AppendLine("skey: " + skey);

                    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 = result;
                    sb.AppendLine("New payment status: " + newPaymentStatus);

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

                    if (order != null)
                    {
                        switch (status)
                        {
                        case "00":
                        {
                            if (_orderProcessingService.CanMarkOrderAsPaid(order))
                            {
                                order.AuthorizationTransactionId = tranID;
                                _orderService.UpdateOrder(order);

                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;

                        case "11":
                        {
                            if (_orderProcessingService.CanVoidOffline(order))
                            {
                                _orderProcessingService.VoidOffline(order);
                            }
                        }
                        break;
                        }
                    }
                } //End nbcb == 2
            }


            //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(""));
        }