public void Ensure_order_can_only_be_refunded_offline_when_paymentstatus_is_paid()
        {
            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.Paid)
                        {
                            _orderProcessingService.CanRefundOffline(order).ShouldBeTrue();
                        }
                        else
                        {
                            _orderProcessingService.CanRefundOffline(order).ShouldBeFalse();
                        }
                    }
                }
            }
        }
 /// <summary>
 /// Refund
 /// </summary>
 /// <param name="order">Order</param>
 private void MarkOrderAsRefunded(Core.Domain.Orders.Order order)
 {
     if (_orderProcessingService.CanRefundOffline(order))
     {
         _orderProcessingService.RefundOffline(order);
     }
 }
예제 #3
0
        protected virtual async Task ProcessRefundResponseAsync(WebHookRequest request, RefundResponse refundResponse)
        {
            if (refundResponse.PaymentId == Guid.Empty)
            {
                return;
            }

            // only transferred refunds
            if (request.Type != "payment.refund_transferred")
            {
                return;
            }

            try
            {
                var paymentResponse = await _paymentApi.GetPaymentAsync(refundResponse.PaymentId);

                if (paymentResponse != null)
                {
                    if (!Guid.TryParse(paymentResponse.OrderId, out var orderGuid))
                    {
                        return;
                    }

                    var order = _orderService.GetOrderByGuid(orderGuid);
                    if (order != null)
                    {
                        var refundIds = _genericAttributeService.GetAttribute <List <string> >(order, Defaults.RefundIdAttributeName)
                                        ?? new List <string>();
                        var refundId = refundResponse.Id.ToString();
                        if (!refundIds.Contains(refundId))
                        {
                            if (paymentResponse.Amount == refundResponse.Amount)
                            {
                                if (_orderProcessingService.CanRefundOffline(order))
                                {
                                    _orderProcessingService.RefundOffline(order);
                                }
                            }
                            else
                            {
                                if (_orderProcessingService.CanPartiallyRefundOffline(order, refundResponse.Amount / 100))
                                {
                                    _orderProcessingService.PartiallyRefundOffline(order, refundResponse.Amount / 100);
                                }
                            }

                            refundIds.Add(refundId);
                            _genericAttributeService.SaveAttribute(order, Defaults.RefundIdAttributeName, refundIds);
                        }
                    }
                }
            }
            catch (ApiException exception)
            {
                _logger.Error($"{Defaults.SystemName}: {exception.Message}", exception);
            }
        }
예제 #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 IActionResult s2sHandler()
        {
            string errorCode = "", errorDesc = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            if (errorCode == "0")
            {
                s2SResponse = "OK";
            }
            //nothing should be rendered to visitor
            return(Content(String.Format("<html>{0}</html>", s2SResponse)));
        }
예제 #8
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(""));
        }
예제 #9
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));
            }
        }
예제 #10
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));
            }
        }
예제 #12
0
 /// <summary>
 /// Gets a value indicating whether order can be marked as refunded
 /// </summary>
 /// <param name="order">Order</param>
 /// <returns>A value indicating whether order can be marked as refunded</returns>
 public bool CanRefundOffline(Order order)
 {
     return(_orderProcessingService.CanRefundOffline(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(""));
        }
        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(""));
        }