예제 #1
0
        public TransactionResult ProcessTransaction(TransactionRequest request)
        {
            switch (request.RequestType)
            {
            case TransactionRequestType.Payment:
                return(PaypalHelper.ProcessApproval(request, _paypalWithRedirectSettings));

            case TransactionRequestType.Refund:
                return(PaypalHelper.ProcessRefund(request, _paypalWithRedirectSettings));
            }

            return(null);
        }
예제 #2
0
        public IActionResult Return(string orderGuid, [FromQuery] PaymentReturnModel paymentReturnModel)
        {
            var order = _orderService.GetByGuid(orderGuid);

            if (order == null)
            {
                return(NotFound());
            }
            var transactionResult = PaypalHelper.ProcessExecution(order, paymentReturnModel, _paypalWithRedirectSettings);

            if (transactionResult.Success)
            {
                _paymentAccountant.ProcessTransactionResult(transactionResult, true);
                return(RedirectToRoute(RouteNames.CheckoutComplete, new { orderGuid = order.Guid }));
            }
            return(R.Fail.Result);
        }
예제 #3
0
        public ActionResult IPNHandler()
        {
            byte[] param      = Request.BinaryRead(Request.ContentLength);
            string strRequest = Encoding.ASCII.GetString(param);
            Dictionary <string, string> values;

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

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

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

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

                #endregion

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

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

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

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

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

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

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

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

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

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

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

                                _orderProcessingService.MarkOrderAsPaid(order);
                            }
                        }
                        break;


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

            //nothing should be rendered to visitor
            return(Content(""));
        }
예제 #4
0
        public ActionResult WebhookEventsHandler()
        {
            var storeScope = GetActiveStoreScopeConfiguration(_storeService, _workContext);
            var payPalDirectPaymentSettings = _settingService.LoadSetting <PayPalDirectPaymentSettings>(storeScope);

            try
            {
                var requestBody = string.Empty;
                using (var stream = new StreamReader(Request.InputStream))
                {
                    requestBody = stream.ReadToEnd();
                }
                var apiContext = PaypalHelper.GetApiContext(payPalDirectPaymentSettings);

                //validate request
                if (!WebhookEvent.ValidateReceivedEvent(apiContext, Request.Headers, requestBody, payPalDirectPaymentSettings.WebhookId))
                {
                    _logger.Error("PayPal error: webhook event was not validated");
                    return(new HttpStatusCodeResult(HttpStatusCode.OK));
                }

                var webhook = JsonFormatter.ConvertFromJson <WebhookEvent>(requestBody);

                //recurring payment
                if (webhook.resource_type.ToLowerInvariant().Equals("sale"))
                {
                    var sale = JsonFormatter.ConvertFromJson <Sale>(webhook.resource.ToString());
                    if (!string.IsNullOrEmpty(sale.billing_agreement_id))
                    {
                        //get agreement
                        var agreement    = Agreement.Get(apiContext, sale.billing_agreement_id);
                        var initialOrder = _orderService.GetOrderByGuid(new Guid(agreement.description));
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            if (recurringPayment != null)
                            {
                                if (sale.state.ToLowerInvariant().Equals("completed"))
                                {
                                    if (recurringPayment.RecurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        initialOrder.PaymentStatus        = PaymentStatus.Paid;
                                        initialOrder.CaptureTransactionId = sale.id;
                                        _orderService.UpdateOrder(initialOrder);

                                        recurringPayment.RecurringPaymentHistory.Add(new RecurringPaymentHistory
                                        {
                                            RecurringPaymentId = recurringPayment.Id,
                                            OrderId            = initialOrder.Id,
                                            CreatedOnUtc       = DateTime.UtcNow
                                        });
                                        _orderService.UpdateRecurringPayment(recurringPayment);
                                    }
                                    else
                                    {
                                        //next payments
                                        var orders = _orderService.GetOrdersByIds(recurringPayment.RecurringPaymentHistory.Select(order => order.OrderId).ToArray());
                                        if (!orders.Any(order => !string.IsNullOrEmpty(order.CaptureTransactionId) &&
                                                        order.CaptureTransactionId.Equals(sale.id, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            var processPaymentResult = new ProcessPaymentResult
                                            {
                                                NewPaymentStatus     = PaymentStatus.Paid,
                                                CaptureTransactionId = sale.id
                                            };
                                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, processPaymentResult);
                                        }
                                    }
                                }
                                else
                                {
                                    _logger.Error(string.Format("PayPal error: Sale is {0} for the order #{1}", sale.state, initialOrder.Id));
                                }
                            }
                        }
                    }
                }

                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        _logger.Error(string.Format("PayPal error: {0} ({1})", error.message, error.name));
                        if (error.details != null)
                        {
                            error.details.ForEach(x => _logger.Error(string.Format("{0} {1}", x.field, x.issue)));
                        }
                    }
                    else
                    {
                        _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                    }
                }
                else
                {
                    _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }

                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
        }
예제 #5
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(""));
        }
예제 #6
0
        public ActionResult PDTHandler(FormCollection form)
        {
            var tx = _webHelper.QueryString <string>("tx");
            Dictionary <string, string> values;
            string response;

            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.GetPdtDetails(tx, out values, out response))
            {
                string orderNumber = string.Empty;
                values.TryGetValue("custom", out orderNumber);
                Guid orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch { }
                Order order = _orderService.GetOrderByGuid(orderNumberGuid);
                if (order != null)
                {
                    decimal mc_gross = decimal.Zero;
                    try
                    {
                        mc_gross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                    }
                    catch (Exception exc)
                    {
                        _logger.Error("PayPal PDT. Error getting mc_gross", exc);
                    }

                    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 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);

                    var sb = new StringBuilder();
                    sb.AppendLine("Paypal PDT:");
                    sb.AppendLine("mc_gross: " + mc_gross);
                    sb.AppendLine("Payer status: " + payer_status);
                    sb.AppendLine("Payment status: " + payment_status);
                    sb.AppendLine("Pending reason: " + pending_reason);
                    sb.AppendLine("mc_currency: " + mc_currency);
                    sb.AppendLine("txn_id: " + txn_id);
                    sb.AppendLine("payment_type: " + payment_type);
                    sb.AppendLine("payer_id: " + payer_id);
                    sb.AppendLine("receiver_id: " + receiver_id);
                    sb.AppendLine("invoice: " + invoice);
                    sb.AppendLine("payment_fee: " + payment_fee);

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

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

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

                    //validate order total
                    if (payPalStandardPaymentSettings.PdtValidateOrderTotal && Math.Abs(mc_gross - order.OrderTotal) > 0.01M)
                    {
                        string errorStr = string.Format("PayPal PDT. 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);

                        return(RedirectToAction("Index", "Home", new { area = "" }));
                    }

                    //mark order as paid
                    if (newPaymentStatus == PaymentStatus.Paid)
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId = txn_id;
                            _orderService.UpdateOrder(order);

                            _orderProcessingService.MarkOrderAsPaid(order);
                        }
                    }
                }

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
            else
            {
                string orderNumber = string.Empty;
                values.TryGetValue("custom", out orderNumber);
                Guid orderNumberGuid = Guid.Empty;
                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch { }
                Order order = _orderService.GetOrderByGuid(orderNumberGuid);
                if (order != null)
                {
                    //order note
                    order.OrderNotes.Add(new OrderNote
                    {
                        Note = "PayPal PDT failed. " + response,
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);
                }
                return(RedirectToAction("Index", "Home", new { area = "" }));
            }
        }
예제 #7
0
        protected void Page_Load(object sender, EventArgs e)
        {
            CommonHelper.SetResponseNoCache(Response);

            if (!Page.IsPostBack)
            {
                string tx = CommonHelper.QueryString("tx");
                Dictionary <string, string> values;
                string response;

                //Rui
                string digest_paypal;

                PayPalStandardPaymentProcessor processor = new PayPalStandardPaymentProcessor();
                if (processor.GetPDTDetails(tx, out values, out response, out digest_paypal))   //Rui
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch { }
                    Order order = OrderManager.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        decimal total = decimal.Zero;
                        try
                        {
                            total = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                        }
                        catch (Exception exc)
                        {
                            LogManager.InsertLog(LogTypeEnum.OrderError, "PayPal IPN. Error getting orderGUID", exc);
                        }

                        //Rui:begin
                        if (order.OrderTotal != total)
                        {
                            return;
                        }
                        //Rui:end

                        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 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);

                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine("Paypal PDT:");
                        sb.AppendLine("total: " + total);
                        sb.AppendLine("Payer status: " + payer_status);
                        sb.AppendLine("Payment status: " + payment_status);
                        sb.AppendLine("Pending reason: " + pending_reason);
                        sb.AppendLine("mc_currency: " + mc_currency);
                        sb.AppendLine("txn_id: " + txn_id);
                        sb.AppendLine("payment_type: " + payment_type);
                        sb.AppendLine("payer_id: " + payer_id);
                        sb.AppendLine("receiver_id: " + receiver_id);
                        sb.AppendLine("invoice: " + invoice);
                        sb.AppendLine("payment_fee: " + payment_fee);

                        OrderManager.InsertOrderNote(order.OrderId, sb.ToString(), false, DateTime.UtcNow);

                        //RUI begin
                        string SourceCode_FinishOrder = @"
namespace NopSolutions.NopCommerce.Web
{
    using NopSolutions.NopCommerce.Payment.Methods.PayPal;

    public partial class PayPalStandardReturn1
    {
        public canonicalRequestResponse Response;
        public Page Page;
        public canonicalRequestResponse Request;
        Picker p;
        public PayPalStandardReturn1()
        {
            Request = new canonicalRequestResponse();
            Response = new canonicalRequestResponse();
            Page = new Page();
        }

        public int Page_Load(object sender, EventArgs e, int checkedOut_orderID)
        {
	        int tx = Convert.ToInt32(CommonHelper.QueryStringInt(""tx""));
            int witness;
            payment_record payment;
            
            orderRecord order;
            
            Dictionary<string, string> values = null;
            if ((witness=PayPalStandardPaymentProcessor1.getPDTDetails(tx, out payment))>=0)
            {
                string orderNumber = string.Empty;
                values.TryGetValue(""custom"", out orderNumber);
                Guid orderNumberGuid = Guid.Empty;
                
                try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch { }
                    //Order order = OrderManager.GetOrderByGuid(orderNumberGuid);

                    //payment.orderID is essentially the custom field in PDT
                    Contract.Assume(checkedOut_orderID == payment.orderID);  //this should be an assignment  ""checkedOut_orderID = payment.orderID"", but the support for ""out parameter"" is wierd 
                    order = GlobalState.tstore.orders[checkedOut_orderID];
                    Contract.Assume(order.id == checkedOut_orderID);

                    if (order != null)
                    {
                        decimal total = decimal.Zero;
                        try
                        {
                            total = decimal.Parse(values[""mc_gross""], new CultureInfo(""en-US""));
                        }
                        catch (Exception exc)
                        {
                            
                        }
                        if (order.gross != total) {
                            Contract.Assume(false);
                        }

                        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 payment_type = string.Empty;
                        values.TryGetValue(""payment_type"", out payment_type);
                        string payer_id = string.Empty;
                        values.TryGetValue(""ayer_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);

                        StringBuilder sb = new StringBuilder();
                        sb.AppendLine(""Paypal PDT:"");
                        sb.AppendLine(""total: "" + total);
                        sb.AppendLine(""Payer status: "" + payer_status);
                        sb.AppendLine(""Payment status: "" + payment_status);
                        sb.AppendLine(""Pending reason: "" + pending_reason);
                        sb.AppendLine(""mc_currency: "" + mc_currency);
                        sb.AppendLine(""txn_id: "" + txn_id);
                        sb.AppendLine(""payment_type: "" + payment_type);
                        sb.AppendLine(""payer_id: "" + payer_id);
                        sb.AppendLine(""receiver_id: "" + receiver_id);
                        sb.AppendLine(""invoice: "" + invoice);
                        sb.AppendLine(""payment_fee: "" + payment_fee);

                        OrderManager.InsertOrderNote(order.id, sb.ToString(), false, DateTime.UtcNow);
                    }

	                if (order.gross != payment.gross)
                    {
                        Contract.Assume(false);
                    }
 
                   if (payment.status!=CaasReturnStatus.Sucess)
                        Contract.Assume(false);
                   order.status = Global.OrderStatusEnum.Paid;
            } else {
                Contract.Assume(false);
            }
            return witness;
        }
    }
}

namespace NopSolutions.NopCommerce.Payment.Methods.PayPal
{
    using NopSolutions.NopCommerce.Web;
    public class PayPalStandardPaymentProcessor1
    {
        public static int getPDTDetails(int tx, out payment_record values)
        {
            values = null;
            return GlobalState.paypal.getPDTDetails(GlobalState.tstore.myAccount,tx, out values);
	    }
    }
}
";
                        Debug.WriteLine("PDTDigest=" + digest_paypal + "\n");
                        // Boogie check
                        string old_hash = CommonHelper.QueryString("path_digest"); //get digest from query string
                        string new_hash = string.Empty;
                        new_hash = PaypalHelper.code_to_hash(SourceCode_FinishOrder);
                        string path_digest = "Merchant[" + new_hash + "((CaaS[" + digest_paypal + "(" + old_hash + ")]))]";
                        Debug.WriteLine("path_digest=" + path_digest + "\n");

                        PaypalHelper.generate_cs_file_from_symval(path_digest);

                        if (!PaypalHelper.checkLogicProperty())
                        {
                            return;
                        }
                        //RUI end


                        if (OrderManager.CanMarkOrderAsPaid(order))
                        {
                            OrderManager.MarkOrderAsPaid(order.OrderId);
                        }
                    }
                    Response.Redirect("~/checkoutcompleted.aspx");
                }
                else
                {
                    string orderNumber = string.Empty;
                    values.TryGetValue("custom", out orderNumber);
                    Guid orderNumberGuid = Guid.Empty;
                    try
                    {
                        orderNumberGuid = new Guid(orderNumber);
                    }
                    catch { }
                    Order order = OrderManager.GetOrderByGuid(orderNumberGuid);
                    if (order != null)
                    {
                        OrderManager.InsertOrderNote(order.OrderId, "PayPal PDT failed. " + response, false, DateTime.UtcNow);
                    }
                    Response.Redirect(CommonHelper.GetStoreLocation());
                }
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            CommonHelper.SetResponseNoCache(Response);

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

                PayPalStandardPaymentProcessor processor = new PayPalStandardPaymentProcessor();
                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

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

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

                    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
                        {
                        }

                        Order initialOrder = this.OrderService.GetOrderByGuid(orderNumberGuid);
                        if (initialOrder != null)
                        {
                            var recurringPayments = this.OrderService.SearchRecurringPayments(0, initialOrder.OrderId, null);
                            foreach (var rp in recurringPayments)
                            {
                                switch (newPaymentStatus)
                                {
                                case PaymentStatusEnum.Authorized:
                                case PaymentStatusEnum.Paid:
                                {
                                    var recurringPaymentHistory = rp.RecurringPaymentHistory;
                                    if (recurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        var rph = new RecurringPaymentHistory()
                                        {
                                            RecurringPaymentId = rp.RecurringPaymentId,
                                            OrderId            = initialOrder.OrderId,
                                            CreatedOn          = DateTime.UtcNow
                                        };
                                        this.OrderService.InsertRecurringPaymentHistory(rph);
                                    }
                                    else
                                    {
                                        //next payments
                                        this.OrderService.ProcessNextRecurringPayment(rp.RecurringPaymentId);
                                        //UNDONE change new order status according to newPaymentStatus
                                        //UNDONE refund/void is not supported
                                    }
                                }
                                break;
                                }
                            }

                            //this.OrderService.InsertOrderNote(newOrder.OrderId, sb.ToString(), DateTime.UtcNow);
                            this.LogService.InsertLog(LogTypeEnum.Unknown, "PayPal IPN. Recurring info", new NopException(sb.ToString()));
                        }
                        else
                        {
                            this.LogService.InsertLog(LogTypeEnum.OrderError, "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
                        {
                        }

                        Order order = this.OrderService.GetOrderByGuid(orderNumberGuid);
                        if (order != null)
                        {
                            this.OrderService.InsertOrderNote(order.OrderId, sb.ToString(), false, DateTime.UtcNow);
                            switch (newPaymentStatus)
                            {
                            case PaymentStatusEnum.Pending:
                            {
                            }
                            break;

                            case PaymentStatusEnum.Authorized:
                            {
                                if (this.OrderService.CanMarkOrderAsAuthorized(order))
                                {
                                    this.OrderService.MarkAsAuthorized(order.OrderId);
                                }
                            }
                            break;

                            case PaymentStatusEnum.Paid:
                            {
                                if (this.OrderService.CanMarkOrderAsPaid(order))
                                {
                                    this.OrderService.MarkOrderAsPaid(order.OrderId);
                                }
                            }
                            break;

                            case PaymentStatusEnum.Refunded:
                            {
                                if (this.OrderService.CanRefundOffline(order))
                                {
                                    this.OrderService.RefundOffline(order.OrderId);
                                }
                            }
                            break;

                            case PaymentStatusEnum.Voided:
                            {
                                if (this.OrderService.CanVoidOffline(order))
                                {
                                    this.OrderService.VoidOffline(order.OrderId);
                                }
                            }
                            break;

                            default:
                                break;
                            }
                        }
                        else
                        {
                            this.LogService.InsertLog(LogTypeEnum.OrderError, "PayPal IPN. Order is not found", new NopException(sb.ToString()));
                        }
                    }
                        #endregion
                        break;
                    }
                }
                else
                {
                    this.LogService.InsertLog(LogTypeEnum.OrderError, "PayPal IPN failed.", strRequest);
                }
            }
        }
예제 #9
0
        public IActionResult WebhookEventsHandler()
        {
            var storeScope = _storeContext.ActiveStoreScopeConfiguration;
            var payPalDirectPaymentSettings = _settingService.LoadSetting <PayPalDirectPaymentSettings>(storeScope);

            try
            {
                var requestBody = string.Empty;
                using (var stream = new StreamReader(this.Request.Body, Encoding.UTF8))
                {
                    requestBody = stream.ReadToEnd();
                }
                var apiContext = PaypalHelper.GetApiContext(payPalDirectPaymentSettings);

                //validate request
                var headers = new NameValueCollection();
                this.Request.Headers.ToList().ForEach(header => headers.Add(header.Key, header.Value));
                if (!WebhookEvent.ValidateReceivedEvent(apiContext, headers, requestBody, payPalDirectPaymentSettings.WebhookId))
                {
                    _logger.Error("PayPal error: webhook event was not validated");
                    return(Ok());
                }

                var webhook = JsonFormatter.ConvertFromJson <WebhookEvent>(requestBody);

                if (webhook.resource_type.ToLowerInvariant().Equals("sale"))
                {
                    var sale = JsonFormatter.ConvertFromJson <Sale>(webhook.resource.ToString());

                    //recurring payment
                    if (!string.IsNullOrEmpty(sale.billing_agreement_id))
                    {
                        //get agreement
                        var agreement    = Agreement.Get(apiContext, sale.billing_agreement_id);
                        var initialOrder = _orderService.GetOrderByGuid(new Guid(agreement.description));
                        if (initialOrder != null)
                        {
                            var recurringPayment = _orderService.SearchRecurringPayments(initialOrderId: initialOrder.Id).FirstOrDefault();
                            if (recurringPayment != null)
                            {
                                if (sale.state.ToLowerInvariant().Equals("completed"))
                                {
                                    if (recurringPayment.RecurringPaymentHistory.Count == 0)
                                    {
                                        //first payment
                                        initialOrder.PaymentStatus        = PaymentStatus.Paid;
                                        initialOrder.CaptureTransactionId = sale.id;
                                        _orderService.UpdateOrder(initialOrder);

                                        recurringPayment.RecurringPaymentHistory.Add(new RecurringPaymentHistory
                                        {
                                            RecurringPaymentId = recurringPayment.Id,
                                            OrderId            = initialOrder.Id,
                                            CreatedOnUtc       = DateTime.UtcNow
                                        });
                                        _orderService.UpdateRecurringPayment(recurringPayment);
                                    }
                                    else
                                    {
                                        //next payments
                                        var orders = _orderService.GetOrdersByIds(recurringPayment.RecurringPaymentHistory.Select(order => order.OrderId).ToArray());
                                        if (!orders.Any(order => !string.IsNullOrEmpty(order.CaptureTransactionId) &&
                                                        order.CaptureTransactionId.Equals(sale.id, StringComparison.InvariantCultureIgnoreCase)))
                                        {
                                            var processPaymentResult = new ProcessPaymentResult
                                            {
                                                NewPaymentStatus     = PaymentStatus.Paid,
                                                CaptureTransactionId = sale.id,
                                                AvsResult            = sale.processor_response?.avs_code ?? string.Empty,
                                                Cvv2Result           = sale.processor_response?.cvv_code ?? string.Empty
                                            };
                                            _orderProcessingService.ProcessNextRecurringPayment(recurringPayment, processPaymentResult);
                                        }
                                    }
                                }
                                else if (sale.state.ToLowerInvariant().Equals("denied"))
                                {
                                    //payment denied
                                    _orderProcessingService.ProcessNextRecurringPayment(recurringPayment,
                                                                                        new ProcessPaymentResult {
                                        Errors = new[] { webhook.summary }, RecurringPaymentFailed = true
                                    });
                                }
                                else
                                {
                                    _logger.Error(
                                        $"PayPal error: Sale is {sale.state} for the order #{initialOrder.Id}");
                                }
                            }
                        }
                    }
                    else
                    //standard payment
                    {
                        var order = _orderService.GetOrderByGuid(new Guid(sale.invoice_number));
                        if (order != null)
                        {
                            if (sale.state.ToLowerInvariant().Equals("completed"))
                            {
                                if (_orderProcessingService.CanMarkOrderAsPaid(order))
                                {
                                    order.CaptureTransactionId     = sale.id;
                                    order.CaptureTransactionResult = sale.state;
                                    _orderService.UpdateOrder(order);
                                    _orderProcessingService.MarkOrderAsPaid(order);
                                }
                            }
                            if (sale.state.ToLowerInvariant().Equals("denied"))
                            {
                                var reason =
                                    $"Payment is denied. {(sale.fmf_details != null ? $"Based on fraud filter: {sale.fmf_details.name}. {sale.fmf_details.description}" : string.Empty)}";
                                order.OrderNotes.Add(new OrderNote
                                {
                                    Note = reason,
                                    DisplayToCustomer = false,
                                    CreatedOnUtc      = DateTime.UtcNow
                                });
                                _logger.Error($"PayPal error: {reason}");
                            }
                        }
                        else
                        {
                            _logger.Error($"PayPal error: Order with GUID {sale.invoice_number} was not found");
                        }
                    }
                }

                return(Ok());
            }
            catch (PayPal.PayPalException exc)
            {
                if (exc is PayPal.ConnectionException)
                {
                    var error = JsonFormatter.ConvertFromJson <Error>((exc as PayPal.ConnectionException).Response);
                    if (error != null)
                    {
                        _logger.Error($"PayPal error: {error.message} ({error.name})");
                        if (error.details != null)
                        {
                            error.details.ForEach(x => _logger.Error($"{x.field} {x.issue}"));
                        }
                    }
                    else
                    {
                        _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                    }
                }
                else
                {
                    _logger.Error(exc.InnerException != null ? exc.InnerException.Message : exc.Message);
                }

                return(Ok());
            }
        }