Example #1
0
        public async System.Threading.Tasks.Task <IActionResult> OrderCompleteAsync(string hash = "", int orderId = 0)
        {
            if (hash != "" && orderId > 0)
            {
                Order lastOrder = (await _orderService.GetOrderByIdAsync(orderId));

                if (lastOrder != null)
                {
                    if (lastOrder.PaymentMethodSystemName.ToLower().Equals("payments.param"))
                    {
                        if (lastOrder.OrderGuid.ToString() == hash)
                        {
                            if (lastOrder.PaymentStatus == PaymentStatus.Pending)
                            {
                                if (_orderProcessingService.CanCancelOrder(lastOrder))
                                {
                                    if (_orderProcessingService.CanMarkOrderAsPaid(lastOrder))
                                    {
                                        await _orderProcessingService.MarkOrderAsPaidAsync(lastOrder);

                                        return(RedirectToRoute("CheckoutCompleted", new { orderId = orderId }));
                                    }
                                }
                            }
                        }
                    }
                }

                return(RedirectToRoute("OrderDetails", new { orderId = orderId }));
            }

            return(RedirectToRoute("Cart"));
        }
        /// <summary>
        /// Execute task
        /// </summary>
        /// <returns>The <see cref="Task"/></returns>
        public async Task ExecuteAsync()
        {
            var stores = await _storeService.GetAllStoresAsync();

            foreach (var store in stores)
            {
                var validationResult = await _openPayService.ValidateAsync(store.Id);

                if (!validationResult.IsValid)
                {
                    await _logger.ErrorAsync($"{Defaults.SystemName}: Cannot update the status of the orders in the store '{store.Name}' when background task was processed.{Environment.NewLine}{string.Join(Environment.NewLine, validationResult.Errors)}");

                    continue;
                }

                // get all non-paid orders including previous month
                var orders = (await _orderService.SearchOrdersAsync(
                                  storeId: store.Id,
                                  createdFromUtc: DateTime.UtcNow.AddMonths(-1),
                                  psIds: new List <int>
                {
                    (int)PaymentStatus.Pending,
                    (int)PaymentStatus.Authorized
                }))?.Where(o => o.PaymentMethodSystemName == Defaults.SystemName);

                if (orders?.Any() == true)
                {
                    var openPayPaymentSettings = await _settingService.LoadSettingAsync <OpenPayPaymentSettings>(store.Id);

                    _openPayApi.ConfigureClient(openPayPaymentSettings);

                    foreach (var order in orders)
                    {
                        var result = await _openPayService.CaptureOrderAsync(order);

                        if (string.IsNullOrEmpty(result.OrderId))
                        {
                            await _logger.ErrorAsync($"{Defaults.SystemName}: Cannot update the status of the order '{order.CustomOrderNumber}' in the store '{store.Name}' when background task was processed.{Environment.NewLine}{string.Join(Environment.NewLine, result.Errors)}");
                        }
                        else if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.CaptureTransactionId = result.OrderId;
                            await _orderProcessingService.MarkOrderAsPaidAsync(order);
                        }
                    }
                }
            }
        }
Example #3
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;
            }
        }
        public async Task <IActionResult> PDTHandler()
        {
            var tx = _webHelper.QueryString <string>("tx");

            if (await _paymentPluginManager.LoadPluginBySystemNameAsync("Payments.PayPalStandard") is not PayPalStandardPaymentProcessor processor || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("PayPal Standard module cannot be loaded");
            }

            var(result, values, response) = await processor.GetPdtDetailsAsync(tx);

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

                var order = await _orderService.GetOrderByGuidAsync(orderNumberGuid);

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

                var mcGross = decimal.Zero;

                try
                {
                    mcGross = decimal.Parse(values["mc_gross"], new CultureInfo("en-US"));
                }
                catch (Exception exc)
                {
                    await _logger.ErrorAsync("PayPal PDT. Error getting mc_gross", exc);
                }

                values.TryGetValue("payer_status", out var payerStatus);
                values.TryGetValue("payment_status", out var paymentStatus);
                values.TryGetValue("pending_reason", out var pendingReason);
                values.TryGetValue("mc_currency", out var mcCurrency);
                values.TryGetValue("txn_id", out var txnId);
                values.TryGetValue("payment_type", out var paymentType);
                values.TryGetValue("payer_id", out var payerId);
                values.TryGetValue("receiver_id", out var receiverId);
                values.TryGetValue("invoice", out var invoice);
                values.TryGetValue("mc_fee", out var mcFee);

                var sb = new StringBuilder();
                sb.AppendLine("PayPal PDT:");
                sb.AppendLine("mc_gross: " + mcGross);
                sb.AppendLine("Payer status: " + payerStatus);
                sb.AppendLine("Payment status: " + paymentStatus);
                sb.AppendLine("Pending reason: " + pendingReason);
                sb.AppendLine("mc_currency: " + mcCurrency);
                sb.AppendLine("txn_id: " + txnId);
                sb.AppendLine("payment_type: " + paymentType);
                sb.AppendLine("payer_id: " + payerId);
                sb.AppendLine("receiver_id: " + receiverId);
                sb.AppendLine("invoice: " + invoice);
                sb.AppendLine("mc_fee: " + mcFee);

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

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

                //validate order total
                var orderTotalSentToPayPal = await _genericAttributeService.GetAttributeAsync <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal);

                if (orderTotalSentToPayPal.HasValue && mcGross != orderTotalSentToPayPal.Value)
                {
                    var errorStr = $"PayPal PDT. 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(RedirectToAction("Index", "Home", new { area = string.Empty }));
                }

                //clear attribute
                if (orderTotalSentToPayPal.HasValue)
                {
                    await _genericAttributeService.SaveAttributeAsync <decimal?>(order, PayPalHelper.OrderTotalSentToPayPal, null);
                }

                if (newPaymentStatus != PaymentStatus.Paid)
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                if (!_orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }

                //mark order as paid
                order.AuthorizationTransactionId = txnId;
                await _orderService.UpdateOrderAsync(order);

                await _orderProcessingService.MarkOrderAsPaidAsync(order);

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
            else
            {
                if (!values.TryGetValue("custom", out var orderNumber))
                {
                    orderNumber = _webHelper.QueryString <string>("cm");
                }

                var orderNumberGuid = Guid.Empty;

                try
                {
                    orderNumberGuid = new Guid(orderNumber);
                }
                catch
                {
                    // ignored
                }

                var order = await _orderService.GetOrderByGuidAsync(orderNumberGuid);

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

                //order note
                await _orderService.InsertOrderNoteAsync(new OrderNote
                {
                    OrderId           = order.Id,
                    Note              = "PayPal PDT failed. " + response,
                    DisplayToCustomer = false,
                    CreatedOnUtc      = DateTime.UtcNow
                });

                return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
            }
        }
Example #5
0
        public async Task <IActionResult> SuccessfulPayment(string status, string planId, int?orderId)
        {
            if (await _paymentPluginManager.LoadPluginBySystemNameAsync(Defaults.SystemName) is not OpenPayPaymentProcessor processor || !_paymentPluginManager.IsPluginActive(processor))
            {
                return(await ProduceErrorResponseAsync());
            }

            if (!orderId.HasValue || string.IsNullOrEmpty(planId) || string.IsNullOrEmpty(status))
            {
                return(await ProduceErrorResponseAsync());
            }

            var order = await _orderService.GetOrderByIdAsync(orderId.Value);

            if (order == null || order.Deleted)
            {
                return(await ProduceErrorResponseAsync(null, $"Invalid processing payment after the order successfully placed on OpenPay. The order '{order.CustomOrderNumber}' not found or was deleted."));
            }

            var openPayOrder = await _openPayApi.GetOrderStatusByIdAsync(planId);

            if (openPayOrder == null)
            {
                return(await ProduceErrorResponseAsync(order.Id, $"Invalid processing payment after the order successfully placed on OpenPay. Cannot get the OpenPay order by id '{planId}'."));
            }

            if (!openPayOrder.PlanStatus.Equals(status, StringComparison.InvariantCultureIgnoreCase))
            {
                return(await ProduceErrorResponseAsync(order.Id, $"Invalid processing payment after the order successfully placed on OpenPay. The OpenPay plan status '{status}' is invalid."));
            }

            if (!openPayOrder.OrderStatus.Equals("Pending", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await ProduceErrorResponseAsync(order.Id, $"Invalid processing payment after the order successfully placed on OpenPay. The OpenPay order status '{openPayOrder.OrderStatus}' is invalid."));
            }

            if (!openPayOrder.PlanStatus.Equals("Lodged", StringComparison.InvariantCultureIgnoreCase))
            {
                return(await ProduceErrorResponseAsync(order.Id, "Invalid processing payment after the order successfully placed on OpenPay. The OpenPay plan status should be 'Lodged'."));
            }

            if (!_orderProcessingService.CanMarkOrderAsPaid(order))
            {
                return(await ProduceErrorResponseAsync(order.Id, $"Invalid processing payment after the order successfully placed on OpenPay. The order '{order.CustomOrderNumber}' already marked as paid."));
            }

            var result = await _openPayService.CaptureOrderAsync(order);

            if (string.IsNullOrEmpty(result.OrderId))
            {
                return(await ProduceErrorResponseAsync(order.Id, string.Join(Environment.NewLine, result.Errors)));
            }

            order.CaptureTransactionId = result.OrderId;

            if (_orderProcessingService.CanMarkOrderAsPaid(order))
            {
                await _orderProcessingService.MarkOrderAsPaidAsync(order);
            }

            _notificationService.SuccessNotification(
                await _localizationService.GetResourceAsync("Plugins.Payments.OpenPay.SuccessfulPayment"));

            return(RedirectToAction("Completed", "Checkout", new { orderId = order.Id }));
        }
Example #6
0
        public ActionResult Return()
        {
            var processor = _paymentPluginManager.LoadPluginBySystemNameAsync("Payments.Paytm").Result as PaytmPaymentProcessor;

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


            var    myUtility = new PaytmHelper();
            string orderId, amount, authDesc, resCode;
            bool   checkSumMatch = false;

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

            string workingKey    = _paytmPaymentSettings.MerchantKey;
            string paytmChecksum = null;

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

            if (Request.Form.Keys.Count > 0)
            {
                foreach (string key in Request.Form.Keys)
                {
                    if (Request.Form[key].Contains("|"))
                    {
                        parameters.Add(key.Trim(), "");
                    }
                    else
                    {
                        parameters.Add(key.Trim(), Request.Form[key]);
                    }
                }

                if (parameters.ContainsKey("CHECKSUMHASH"))
                {
                    paytmChecksum = parameters["CHECKSUMHASH"];
                    parameters.Remove("CHECKSUMHASH");
                }


                if (!string.IsNullOrEmpty(paytmChecksum) && Checksum.verifySignature(parameters, workingKey, paytmChecksum))
                {
                    checkSumMatch = true;
                }
            }

            orderId  = parameters["ORDERID"];
            amount   = parameters["TXNAMOUNT"];
            resCode  = parameters["RESPCODE"];
            authDesc = parameters["STATUS"];



            var order = _orderService.GetOrderByCustomOrderNumberAsync(orderId).Result;

            if (checkSumMatch == true)
            {
                if (resCode == "01" && authDesc == "TXN_SUCCESS")
                {
                    if (TxnStatus(orderId, order.OrderTotal.ToString("0.00")))
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            _orderProcessingService.MarkOrderAsPaidAsync(order);
                        }
                        return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                    }
                    else
                    {
                        return(Content("Amount Mismatch"));
                    }
                }
                else if (authDesc == "TXN_FAILURE")
                {
                    _orderProcessingService.CancelOrderAsync(order, false);
                    order.OrderStatus = OrderStatus.Cancelled;
                    _orderService.UpdateOrderAsync(order);
                    return(RedirectToRoute("OrderDetails", new { orderId = order.Id }));
                }
                else
                {
                    return(Content("Security Error. Illegal access detected"));
                }
            }
            else if (string.IsNullOrEmpty(paytmChecksum))
            {
                return(Content("Please Contact Customer Care"));
            }
            else
            {
                return(Content("Security Error. Illegal access detected, Checksum failed"));
            }
        }
        //public IActionResult PayGateNotifyHandler(IFormCollection form)
        public async void PayGateNotifyHandler(IFormCollection form)
        {
            /**
             * Enable IPN if it is set
             */
            await Response.WriteAsync("OK");

            var  reference = Request.Query["pgnopcommerce"];
            bool isPaid;

            await _logger.InformationAsync("PayGateNotifyHandler start. Order no.: " + reference);

            //Order order = _orderService.GetOrderById(Int32.Parse(Request.Query["pgnopcommerce"]));
            Order order = await _orderService.GetOrderByIdAsync(Int32.Parse(reference));

            int orderId = 0;

            if (order != null)
            {
                orderId = order.Id;
            }
            await _logger.InformationAsync("PayGateNotifyHandler: Order Payment Status: " + order.PaymentStatus);

            isPaid = order.PaymentStatus == PaymentStatus.Paid ? true : false;

            if (!isPaid)
            {
                var sBuilder          = new StringBuilder();
                var query_status      = PaymentStatus.Pending;
                var payrequestId      = "";
                var transactionStatus = "";

                var testMode      = _payGatePaymentSettings.TestMode;
                var paygateId     = "10011072130";
                var encryptionKey = "secret";
                if (!testMode)
                {
                    paygateId     = _payGatePaymentSettings.PayGateID;
                    encryptionKey = _payGatePaymentSettings.EncryptionKey;
                }

                //Validate checksum for the posted form fields
                var formData    = new NameValueCollection();
                var formDataJS  = "";
                var checkstring = "";

                foreach (var entry in form)
                {
                    var key = entry.Key;
                    var val = entry.Value;
                    formData[key] = val;
                    if (key != "CHECKSUM")
                    {
                        checkstring += val;
                        formDataJS  += key + "=" + val + "&";
                    }
                }

                await _logger.InformationAsync("PayGateNotifyHandler: POST: " + formDataJS);

                var checksum = formData["CHECKSUM"];
                checkstring += encryptionKey;

                var ourChecksum = new PayGateHelper().CalculateMD5Hash(checkstring);
                if (ourChecksum.Equals(checksum, StringComparison.OrdinalIgnoreCase))
                {
                    var trans_status = formData["TRANSACTION_STATUS"];
                    transactionStatus = trans_status;
                    var query_status_desc = "";
                    payrequestId = formData["PAY_REQUEST_ID"];
                    switch (trans_status)
                    {
                    case "1":
                        query_status      = PaymentStatus.Paid;
                        query_status_desc = "Approved";
                        break;

                    case "2":
                        query_status      = PaymentStatus.Voided;
                        query_status_desc = "Declined";
                        break;

                    case "4":
                        query_status      = PaymentStatus.Voided;
                        query_status_desc = "Cancelled By Customer with back button on payment page";
                        break;

                    case "0":
                        query_status      = PaymentStatus.Voided;
                        query_status_desc = "Not Done";
                        break;

                    default:
                        break;
                    }

                    sBuilder.AppendLine("PayGate Notify Handler");
                    sBuilder.AppendLine("PayGate Query Data");
                    sBuilder.AppendLine("=======================");
                    sBuilder.AppendLine("PayGate Transaction_Id: " + formData["TRANSACTION_ID"]);
                    sBuilder.AppendLine("PayGate Status Desc: " + query_status_desc);
                    sBuilder.AppendLine("");

                    //order note
                    await _orderService.InsertOrderNoteAsync(new OrderNote
                    {
                        OrderId           = orderId,
                        Note              = sBuilder.ToString(),//sbbustring.Format("Order status has been changed to {0}", PaymentStatus.Paid),
                        DisplayToCustomer = false,
                        CreatedOnUtc      = DateTime.UtcNow
                    });

                    await _orderService.UpdateOrderAsync(order);

                    //load settings for a chosen store scope
                    var storeScope             = this.GetActiveStoreScopeConfiguration(_storeService, _workContext);
                    var payGatePaymentSettings = _settingService.LoadSettingAsync <PayGatePaymentSettings>(storeScope);

                    //mark order as paid
                    if (query_status == PaymentStatus.Paid)
                    {
                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            order.AuthorizationTransactionId = payrequestId;
                            await _orderService.UpdateOrderAsync(order);

                            await _orderProcessingService.MarkOrderAsPaidAsync(order);
                        }
                        await _orderService.UpdateOrderAsync(order);

                        RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
                    }
                    else
                    {
                        order.AuthorizationTransactionId = payrequestId;
                        OrderNote note = new OrderNote();
                        note.OrderId           = orderId;
                        note.CreatedOnUtc      = DateTime.Now;
                        note.DisplayToCustomer = true;
                        note.Note = "Payment failed with the following description: " + transactionStatus;
                        if (_orderProcessingService.CanCancelOrder(order))
                        {
                            await _orderProcessingService.CancelOrderAsync(order, false);
                        }
                        await _orderService.InsertOrderNoteAsync(note);

                        await _orderService.UpdateOrderAsync(order);

                        RedirectToRoute("OrderDetails", new { orderId = order.Id.ToString().Trim() });
                    }
                }
                else
                {
                    await _logger.ErrorAsync("PayGateNotifyHandler: Checksum mismatch: " + ourChecksum + " : " + checksum);
                }
            }
        }
        /*
         *
         * [NonAction]
         * public override IList<string> ValidatePaymentForm(FormCollection form)
         * {
         *  var warnings = new List<string>();
         *  return warnings;
         * }
         *
         * [NonAction]
         * public override ProcessPaymentRequest Ge                                                                                                                                                                                         tPaymentInfo(FormCollection form)
         * {
         *  var paymentInfo = new ProcessPaymentRequest();
         *  return paymentInfo;
         * }
         */

        //[ValidateInput(false)]
        public async Task <IActionResult> Return(IpnModel model)
        {
            try
            {
                /*
                 * var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.Payu") as PayuPaymentProcessor;
                 * if (processor == null ||
                 *  !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed)
                 *  throw new NopException("Payu module cannot be loaded");
                 *
                 */
                var    myUtility = new PayuHelper();
                string orderId, merchantId, amount, productinfo, firstname, email, hash, status, checksum;

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


                merchantId  = _payuPaymentSettings.MerchantId.ToString();
                orderId     = model.Form["txnid"];
                amount      = model.Form["amount"];
                productinfo = model.Form["productinfo"];
                firstname   = model.Form["firstname"];
                email       = model.Form["email"];
                hash        = model.Form["hash"];
                status      = model.Form["status"];

                checksum = myUtility.verifychecksum(merchantId, orderId, amount, productinfo, firstname, email, status, _payuPaymentSettings.Key);

                if (checksum == hash)
                {
                    if (status == "success")
                    {
                        /*
                         *  Here you need to put in the routines for a successful
                         *   transaction such as sending an email to customer,
                         *   setting database status, informing logistics etc etc
                         */

                        var order = await _orderService.GetOrderByIdAsync(Convert.ToInt32(orderId));

                        if (_orderProcessingService.CanMarkOrderAsPaid(order))
                        {
                            await _orderProcessingService.MarkOrderAsPaidAsync(order);

                            var sb = new StringBuilder();
                            sb.AppendLine("PayU IPN:");
                            foreach (var v in model.Form)
                            {
                                sb.AppendLine(v.Key + ": " + v.Value);
                            }
                            //order note
                            //OrderNoteAdd
                            await _orderService.InsertOrderNoteAsync(new OrderNote
                            {
                                OrderId           = order.Id,
                                Note              = sb.ToString(),
                                DisplayToCustomer = false,
                                CreatedOnUtc      = DateTime.UtcNow
                            });

                            await _orderService.UpdateOrderAsync(order);
                        }

                        //Thank you for shopping with us. Your credit card has been charged and your transaction is successful
                        return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                    }

                    else
                    {
                        /*
                         *  Here you need to put in the routines for a failed
                         *  transaction such as sending an email to customer
                         *  setting database status etc etc
                         */

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


                else
                {
                    /*
                     *  Here you need to simply ignore this and dont need
                     *  to perform any operation in this condition
                     */

                    return(Content("Security Error. Illegal access detected"));
                }
            }
            catch (Exception ex)
            {
                return(Content("Error Occured :" + ex.Message));
            }
        }
Example #9
0
        public async Task <ActionResult> ResultHandler(string status, string authority, string oGUID)
        {
            if (!(await _paymentPluginManager.LoadPluginBySystemNameAsync("Payments.Zarinpal") is ZarinPalPaymentProcessor processor) || !_paymentPluginManager.IsPluginActive(processor))
            {
                throw new NopException("ZarinPal module cannot be loaded");
            }

            var orderNumberGuid = Guid.Empty;

            orderNumberGuid = new Guid(oGUID);


            var order = await _orderService.GetOrderByGuidAsync(orderNumberGuid);

            var total = Convert.ToInt32(Math.Round(order.OrderTotal, 2));

            if (_zarinPalPaymentSettings.RialToToman)
            {
                total = total / 10;
            }


            if (string.IsNullOrEmpty(status) == false && string.IsNullOrEmpty(authority) == false)
            {
                var refId = "0";
                System.Net.ServicePointManager.Expect100Continue = false;
                var statusCode = -1;
                var storeScope = await _storeContext.GetActiveStoreScopeConfigurationAsync();

                var zarinPalSettings = await _settingService.LoadSettingAsync <ZarinpalPaymentSettings>(storeScope);

                if (_zarinPalPaymentSettings.Method == EnumMethod.SOAP)
                {
                    if (_zarinPalPaymentSettings.UseSandbox)
                    {
                        using (PaymentGatewayImplementationServicePortTypeClient zpalSr = new PaymentGatewayImplementationServicePortTypeClient())
                        {
                            var res = zpalSr.PaymentVerificationAsync
                                      (
                                zarinPalSettings.MerchantID,
                                authority,
                                total
                                      ).Result; //test

                            statusCode = res.Body.Status;
                            refId      = res.Body.RefID.ToString();
                        }
                    }
                    else
                    {
                        using (PaymentGatewayImplementationServicePortTypeClient zpalSr = new ServiceReferenceZarinpal.PaymentGatewayImplementationServicePortTypeClient())
                        {
                            var res = zpalSr.PaymentVerificationAsync(
                                zarinPalSettings.MerchantID,
                                authority,
                                total).Result;
                            statusCode = res.Body.Status;
                            refId      = res.Body.RefID.ToString();
                        }
                    }
                }
                else if (_zarinPalPaymentSettings.Method == EnumMethod.REST)
                {
                    var url    = $"https://{(_zarinPalPaymentSettings.UseSandbox ? "sandbox" : "www")}.zarinpal.com/pg/rest/WebGate/PaymentVerification.json";
                    var values = new Dictionary <string, string>
                    {
                        { "MerchantID", zarinPalSettings.MerchantID },
                        { "Authority", authority },
                        { "Amount", total.ToString() }     //Toman
                    };

                    var paymenResponsetJsonValue = JsonConvert.SerializeObject(values);
                    var content = new StringContent(paymenResponsetJsonValue, Encoding.UTF8, "application/json");

                    var response       = ZarinPalPaymentProcessor.ClientZarinPal.PostAsync(url, content).Result;
                    var responseString = response.Content.ReadAsStringAsync().Result;

                    var restVerifyModel =
                        JsonConvert.DeserializeObject <RestVerifyModel>(responseString);
                    statusCode = restVerifyModel.Status;
                    refId      = restVerifyModel.RefID;
                }

                var result = ZarinpalHelper.StatusToMessage(statusCode);

                var orderNote = new OrderNote()
                {
                    OrderId = order.Id,
                    Note    = string.Concat(
                        "پرداخت ",
                        (result.IsOk ? "" : "نا"), "موفق", " - ",
                        "پیغام درگاه : ", result.Message,
                        result.IsOk ? string.Concat(" - ", "کد پی گیری : ", refId) : ""
                        ),
                    DisplayToCustomer = true,
                    CreatedOnUtc      = DateTime.UtcNow
                };

                await _orderService.InsertOrderNoteAsync(orderNote);

                if (result.IsOk && _orderProcessingService.CanMarkOrderAsPaid(order))
                {
                    order.AuthorizationTransactionId = refId;
                    await _orderService.UpdateOrderAsync(order);

                    await _orderProcessingService.MarkOrderAsPaidAsync(order);

                    return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id }));
                }
            }

            return(RedirectToRoute("orderdetails", new { orderId = order.Id }));
        }