Ejemplo n.º 1
0
        public string Button1_Click()
        {
            string PxPayUserId = _configuration.GetSection("WindCave:PxPayUserId").Value;//.AppSettings["PxPayUserId"];
            string PxPayKey    = _configuration.GetSection("WindCave:PxPayKey").Value;
            //string PxPayKey = ConfigurationManager.AppSettings["PxPayKey"];

            PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            RequestInput input = new RequestInput();

            input.AmountInput       = "123";
            input.CurrencyInput     = "NZD";
            input.MerchantReference = "My Reference";
            input.TxnType           = "Purchase";
            input.UrlFail           = "https://demo.windcave.com/SandboxSuccess.aspx";
            input.UrlSuccess        = "https://demo.windcave.com/SandboxSuccess.aspx";
            //input.UrlFail = Request.Url.GetLeftPart(UriPartial.Path);
            //input.UrlSuccess = Request.Url.GetLeftPart(UriPartial.Path);

            // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            Guid orderId = Guid.NewGuid();

            input.TxnId = orderId.ToString().Substring(0, 16);
            //input.TxnId = "123456123123123";

            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                // Redirect user to payment page

                //Response.Redirect(output.Url);
                return(output.Url);
            }

            return(output.Url);
            //PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            //RequestInput input = new RequestInput();

            //input.AmountInput = "123";
            //input.CurrencyInput = "123";
            //input.MerchantReference = "123";
            //input.TxnType = "123";
            //input.UrlFail = Request.Url.GetLeftPart(UriPartial.Path);
            //input.UrlSuccess = Request.Url.GetLeftPart(UriPartial.Path);

            //// TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            //Guid orderId = Guid.NewGuid();
            //input.TxnId = orderId.ToString().Substring(0, 16);

            //RequestOutput output = WS.GenerateRequest(input);

            //if (output.valid == "1")
            //{
            //    // Redirect user to payment page

            //    Response.Redirect(output.Url);
            //}
        }
Ejemplo n.º 2
0
        protected void submit_Click(object sender, EventArgs e)
        {
            PxPay        ws    = new PxPay("Magnetism_Dev", "c21aa727d509e3828e79a21ab4f7a4b609b758817d83e87b7f3c722d7a88cd3a");
            RequestInput input = new RequestInput();

            decimal amount = 0;

            if (decimal.TryParse(this.amount.Text, out amount) && amount > 0)
            {
                bool     isRegularGift = this.isregulargift.Checked;
                DateTime startDate     = ParseDateTime(this.startdate.Text);

                input.AmountInput       = string.Format("{0:0.00}", amount);
                input.CurrencyInput     = "NZD";
                input.EmailAddress      = this.emailaddress.Text;
                input.MerchantReference = Guid.NewGuid().ToString();
                input.TxnType           = isRegularGift ? "Auth" : "Purchase"; // for all regular gifts, authorize (hold) the card. for one-off donations, send a purchase message
                input.EnableAddBillCard = this.isregulargift.Checked ? "1" : "0";
                input.TxnData1          = this.startdate.Text;
                input.TxnData2          = this.enddate.Text;
                input.UrlFail           = string.Format("http://{0}/_test/fail.aspx", Request.Url.Authority);
                input.UrlSuccess        = string.Format("http://{0}/_test/success.aspx", Request.Url.Authority);

                RequestOutput output = ws.GenerateRequest(input);
                if (output.valid == "1")
                {
                    Response.Redirect(output.Url);
                }
            }
        }
Ejemplo n.º 3
0
        public RequestJson RequestPaymentUrl(int cartId)
        {
            string PxPayUserId = _configuration.GetSection("WindCave:PxPayUserId").Value;//.AppSettings["PxPayUserId"];
            string PxPayKey    = _configuration.GetSection("WindCave:PxPayKey").Value;

            PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            RequestInput input  = new RequestInput();
            var          card   = _context.Cart.Find(cartId);
            decimal      amount = ((decimal)card.Price - (decimal)card.SalePrice) * 0.50m + (decimal)card.SalePrice + (decimal)card.DeliveryFee;

            input.AmountInput       = Math.Round(amount, 2).ToString();
            input.CurrencyInput     = "NZD";
            input.MerchantReference = "My Reference";
            input.TxnType           = "Purchase";
            input.Opt = "TO=" + DateTime.UtcNow.AddMinutes(10).ToString("yyMMddHHmm");

            input.UrlFail    = "http://luxedreameventhire.co.nz:80/paymentresult";
            input.UrlSuccess = "http://luxedreameventhire.co.nz:80/paymentresult";

            input.UrlCallback = "http://api.luxedreameventhire.co.nz/api/pxpay/ResponseOutput";

            //input.UrlFail = "http://localhost:4200/paymentresult";
            //input.UrlSuccess = "http://localhost:4200/paymentresult";

            //input.UrlCallback = "http://localhost:5000/api/pxpay/ResponseOutput";

            // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
            Guid orderId = Guid.NewGuid();

            input.TxnId = orderId.ToString().Substring(0, 16);
            Payment payment = new Payment();

            payment.TxnId  = input.TxnId;
            payment.CardId = cartId;

            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                payment.url = output.Url;
                _context.Payment.AddAsync(payment);
                _context.SaveChangesAsync();
                return(new RequestJson {
                    Url = output.Url
                });
            }

            return(new RequestJson {
                Url = output.Url
            });
        }
Ejemplo n.º 4
0
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            string pxPayUserId = SettingsHelper.Payment.UserId;
            string pxPayKey    = SettingsHelper.Payment.Key;

            try
            {
                PaymentDetails paymentDetails = ReadAndValidateInput();

                if (paymentDetails == null)
                {
                    lblMessage.Text = "There was an error processing your request, please try again.";
                    return;
                }

                PxPay wsPxPay = new PxPay(pxPayUserId, pxPayKey);

                RequestInput input = new RequestInput();
                input.AmountInput       = paymentDetails.Amount.ToString(CultureInfo.InvariantCulture);
                input.CurrencyInput     = "NZD";
                input.MerchantReference = paymentDetails.RefNumber;
                input.TxnData1          = paymentDetails.RefType;
                input.TxnData2          = paymentDetails.FullName;
                input.TxnData3          = paymentDetails.Phone;
                input.TxnType           = "Purchase";
                input.UrlFail           = CMS.DocumentEngine.DocumentContext.CurrentDocument.AbsoluteURL;
                input.UrlSuccess        = CMS.DocumentEngine.DocumentContext.CurrentDocument.AbsoluteURL;

                // TODO: GUID representing unique identifier for the transaction within the shopping cart (normally would be an order ID or similar)
                Guid orderId = Guid.NewGuid();
                input.TxnId = orderId.ToString().Substring(0, 16);

                RequestOutput output = wsPxPay.GenerateRequest(input);

                if (output.valid == "1")
                {
                    // Redirect user to payment page

                    Response.Redirect(output.Url);
                }
            }
            catch (Exception ex)
            {
                //log exception to Kentico
                EventLogProvider.LogException("Payment", "POST", ex, 0, "Payment Express Control", null);
                lblMessage.Text = "There was an error processing your request, please contact Vector.";
            }
        }
Ejemplo n.º 5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            Title          = DataHelper.GetNotEmpty(GetValue(Constants.PageTypes.Title), string.Empty);
            Description    = DataHelper.GetNotEmpty(GetValue(Constants.PageTypes.Description), string.Empty);
            SuccessMessage = DataHelper.GetNotEmpty(GetValue(Constants.PageTypes.SuccessMessage), string.Empty);
            FailMessage    = DataHelper.GetNotEmpty(GetValue(Constants.PageTypes.FailMessage), string.Empty);

            //Determine if the page request is for a user returning from the payment page
            string resultQs = Request.QueryString["result"];

            if (!string.IsNullOrEmpty(resultQs))
            {
                string pxPayUserId = SettingsHelper.Payment.UserId;
                string pxPayKey    = SettingsHelper.Payment.Key;

                try
                {
                    // Obtain the transaction result
                    PxPay wsPxPay = new PxPay(pxPayUserId, pxPayKey);

                    ResponseOutput output = wsPxPay.ProcessResponse(resultQs);

                    lblResponse.Text = (output.Success == "1") ? SuccessMessage : FailMessage;

                    pnlPaymentExpressControlPreviewMode.Visible = false;
                    pnlPaymentExpressControlLoad.Visible        = true;

                    // Sending invoices/updating order status within database etc.

                    if (!IsProcessed(output.TxnId) && output.valid == "1" && output.Success == "1")
                    {
                        // TODO: Send emails, generate invoices, update order status etc.
                    }
                }
                catch (Exception ex)
                {
                    //log exception to Kentico
                    EventLogProvider.LogException("Payment", "GET", ex, 0, "Payment Express Control", null);
                }
            }
        }
Ejemplo n.º 6
0
        private void ProcessDpsPayment(string result)
        {
            PxPay          ws     = new PxPay("Magnetism_Dev", "c21aa727d509e3828e79a21ab4f7a4b609b758817d83e87b7f3c722d7a88cd3a");
            ResponseOutput output = ws.ProcessResponse(result);

            string[] nameSplit = output.CardHolderName.Split(' ');
            string   firstName = nameSplit[0];
            string   lastName  = string.Join(" ", nameSplit.Skip(1).ToList());

            this.amount.Text               = output.AmountSettlement;
            this.emailaddress.Text         = output.EmailAddress;
            this.firstname.Text            = firstName;
            this.lastname.Text             = lastName;
            this.dpsbillingid.Text         = output.DpsBillingId;
            this.transactionreference.Text = output.DpsTxnRef;
            this.ccexpirydate.Text         = output.DateExpiry;
            this.dpsresponse.Text          = output.ResponseText;
            this.startdate.Text            = output.TxnData1;
            this.enddate.Text              = output.TxnData2;
            this.isregulargift.Checked     = !string.IsNullOrEmpty(this.dpsbillingid.Text); // if the billing id contains data, it's a regular gift
        }
Ejemplo n.º 7
0
        public IActionResult CreateDpsUI([FromBody] DpsInputDto dpsInput)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Invalid input!"));
            }
            var orderId   = dpsInput.OrderId;
            var returnUrl = dpsInput.ReturnUrl;

            var    siteName          = _config["CurrentSite"];
            string host_url          = "http://" + HttpContext.Request.Host + siteName;
            string host_url1         = _config["ApiUrl"] + siteName; // "http://api171.gpos.nz/dollaritems";
            string sReturnUrlFail    = host_url1 + "/api/dps/result?t=result&ret=fail&orderId=" + orderId;
            string sReturnUrlSuccess = host_url1 + "/api/dps/result?action=paymentSuccess&orderId=" + orderId;

            //PxPayUserId = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "PxPayUserId").FirstOrDefault().Value;
            //PxPayKey = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "PxPayKey").FirstOrDefault().Value;
            //sServiceUrl = _contextf.Settings.Where(s => s.Cat == "DPS" && s.Name == "sServiceUrl").FirstOrDefault().Value;
            //if (PxPayUserId == null || PxPayKey == null || sServiceUrl == null)
            //{
            //    PxPayUserId = Startup.Configuration["PxPayUserId"];
            //    PxPayKey = Startup.Configuration["PxPayKey"];
            //    sServiceUrl = Startup.Configuration["sServiceUrl"];
            //}
            //get order total

            var order = _context.Orders.Where(o => o.Id == Convert.ToInt32(orderId))
                        .Join(_context.Invoice,
                              o => o.InvoiceNumber,
                              i => i.InvoiceNumber,
                              (o, i) => new { o.InvoiceNumber, o.Id, Total = i.Total ?? 0 }).FirstOrDefault();
            decimal orderAmount = 0;

            if (order != null)
            {
                orderAmount = order.Total;
            }
            else
            {
                return(BadRequest());
            }

            PxPay        WS    = new PxPay(sServiceUrl, PxPayUserId, PxPayKey);
            RequestInput input = new RequestInput();

            input.AmountInput       = Math.Round(orderAmount, 2).ToString();
            input.CurrencyInput     = "NZD";
            input.MerchantReference = orderId;
            input.TxnType           = "Purchase";
            input.UrlFail           = sReturnUrlFail;
            input.UrlSuccess        = sReturnUrlSuccess;
            input.TxnData1          = returnUrl;

            Guid newOrderId = Guid.NewGuid();

            input.TxnId = newOrderId.ToString().Substring(0, 16);
            RequestOutput output = WS.GenerateRequest(input);

            if (output.valid == "1")
            {
                var result = output.Url;
                return(Ok(result));
            }

            return(NotFound());
        }
Ejemplo n.º 8
0
        //   [Consumes("application/x-www-form-urlencoded")]
        public async Task <IActionResult> GetPaymentResult([FromQuery] string result, [FromQuery] string action, [FromQuery] string orderId)
        {
            if (result == null)
            {
                return(NotFound());
            }
            if (action != "paymentSuccess")
            {
                return(BadRequest());
            }

            PxPay          WS        = new PxPay(sServiceUrl, PxPayUserId, PxPayKey);
            ResponseOutput outputQs  = WS.ProcessResponse(result);
            string         DpsTxnRef = outputQs.DpsTxnRef;
            string         sSuccess  = outputQs.Success;
            string         returnUrl = outputQs.TxnData1;

            if (returnUrl == "")
            {
                returnUrl = "www.google.com";
            }

            var isProcessed = _context.TranDetail.Any(td => td.Note == DpsTxnRef || td.PaymentRef == DpsTxnRef);

            if (isProcessed)
            {
                // return BadRequest("Order " + orderId + " has been processed!");
                return(Redirect(returnUrl));
            }

            PropertyInfo[] properties = outputQs.GetType().GetProperties();
            foreach (PropertyInfo oPropertyInfo in properties)
            {
                if (oPropertyInfo.CanRead)
                {
                    string name  = oPropertyInfo.Name;
                    string value = (string)oPropertyInfo.GetValue(outputQs, null);
                }
            }

            var order = _context.Orders.Where(o => o.Id == Convert.ToInt32(orderId))
                        .Join(_context.Invoice,
                              o => o.InvoiceNumber,
                              i => i.InvoiceNumber,
                              (o, i) => new { o.InvoiceNumber, o.Id, o.CardId, Total = i.Total ?? 0 }).FirstOrDefault();
            int     cardId        = 0;
            decimal orderAmount   = 0;
            string  customerEmail = "";

            var customer = await _context.Card.FirstOrDefaultAsync(c => c.Id == order.CardId);

            if (customer != null)
            {
                customerEmail = customer.Email;
            }
            if (order != null)
            {
                cardId      = order.CardId;
                orderAmount = order.Total;
            }

            int paymentmethod = _isettings.getIdByPaymentMethod("dps");// 14; // paymentMethodCast(paymentInfo.payment_method);

            if (sSuccess == "1")
            {
                var connect       = _context.Database.GetDbConnection();
                var connectstring = _context.Database.GetDbConnection().ConnectionString;
                connect.Open();
                System.Data.Common.DbCommand dbCommand = connect.CreateCommand();

                //            using (var dbContextTransaction = connect.BeginTransaction())
                {
                    //input payment info
                    try
                    {
                        var note = dbCommand.CreateParameter();
                        note.ParameterName = "@note";
                        note.DbType        = System.Data.DbType.String;
                        note.Value         = DpsTxnRef;     //insert dps ref to tran_detail tables

                        var Payment_Ref = dbCommand.CreateParameter();
                        Payment_Ref.ParameterName = "@payment_ref";
                        Payment_Ref.DbType        = System.Data.DbType.String;
                        Payment_Ref.Value         = DpsTxnRef;

                        var shop_branch = dbCommand.CreateParameter();
                        shop_branch.ParameterName = "@shop_branch";
                        shop_branch.DbType        = System.Data.DbType.Int32;
                        shop_branch.Value         = _isettings.getOnlineShopId();

                        var Amount = dbCommand.CreateParameter();
                        Amount.ParameterName = "@Amount";
                        Amount.DbType        = System.Data.DbType.String;
                        Amount.Value         = order.Total;


                        var nDest = dbCommand.CreateParameter();
                        nDest.ParameterName = "@nDest";
                        nDest.DbType        = System.Data.DbType.Int32;
                        nDest.Value         = "1116";

                        var staff_id = dbCommand.CreateParameter();
                        staff_id.ParameterName = "@staff_id";
                        staff_id.DbType        = System.Data.DbType.Int32;
                        staff_id.Value         = order.CardId.ToString();

                        var card_id = dbCommand.CreateParameter();
                        card_id.ParameterName = "@card_id";
                        card_id.DbType        = System.Data.DbType.Int32;
                        card_id.Value         = order.CardId.ToString();

                        var payment_method = dbCommand.CreateParameter();
                        payment_method.ParameterName = "@payment_method";
                        payment_method.DbType        = System.Data.DbType.Int32;
                        payment_method.Value         = paymentmethod;

                        var invoice_number = dbCommand.CreateParameter();
                        invoice_number.ParameterName = "@invoice_number";
                        invoice_number.DbType        = System.Data.DbType.Int32;
                        invoice_number.Value         = Convert.ToInt32(order.InvoiceNumber);

                        var amountList = dbCommand.CreateParameter();
                        amountList.ParameterName = "@amountList";
                        amountList.DbType        = System.Data.DbType.String;
                        amountList.Value         = orderAmount;


                        var return_tran_id = dbCommand.CreateParameter();
                        return_tran_id.ParameterName = "@return_tran_id";
                        return_tran_id.Direction     = System.Data.ParameterDirection.Output;
                        return_tran_id.DbType        = System.Data.DbType.Int32;

                        var return_exist_trans = dbCommand.CreateParameter();
                        return_exist_trans.ParameterName = "@return_exist_trans";
                        return_exist_trans.Direction     = System.Data.ParameterDirection.Output;
                        return_exist_trans.DbType        = System.Data.DbType.Boolean;

                        dbCommand.Parameters.Add(note);
                        dbCommand.Parameters.Add(Payment_Ref);
                        dbCommand.Parameters.Add(shop_branch);
                        dbCommand.Parameters.Add(Amount);
                        dbCommand.Parameters.Add(staff_id);
                        dbCommand.Parameters.Add(card_id);
                        dbCommand.Parameters.Add(payment_method);
                        dbCommand.Parameters.Add(invoice_number);
                        dbCommand.Parameters.Add(amountList);
                        dbCommand.Parameters.Add(return_tran_id);
                        dbCommand.Parameters.Add(return_exist_trans);
                        dbCommand.CommandText = "eznz_payment";
                        dbCommand.CommandType = System.Data.CommandType.StoredProcedure;
                        var obj = await dbCommand.ExecuteNonQueryAsync();


                        //if trans exists, do not send invoice and order
                        string sExist_trans = return_exist_trans.Value.ToString();//dbCommand.Parameters["@return_exist_trans"].Value.ToString();
                        if (sExist_trans == null || sExist_trans == "0" || sExist_trans == "")
                        {
                            try
                            {
                                //create invoice pdf
                                var    host        = "http://" + HttpContext.Request.Host;
                                string host1       = _config["ApiUrl"]; // "http://api171.gpos.nz";
                                var    currentSite = _config["CurrentSite"];
                                try
                                {
                                    using (var client = new HttpClient())
                                    {
                                        client.BaseAddress = new Uri(host1);

                                        var responseTask = client.GetAsync(currentSite + "/api/invoice/pdf/" + orderId);
                                        responseTask.Wait();
                                        var getResult = responseTask.Result;
                                        if (getResult.IsSuccessStatusCode)
                                        {
                                            //send order to customer by email
                                            var myAttachment = new Attachment(_config["PdfPath"] + orderId + ".pdf");
                                            _mail.sendEmail(customerEmail, "Invoice", "DoNotReply! <br><br> Dear customer: <br>Thank you for your order from<a href='http://dollaritems.co.nz/ecom'> dollaritems.co.nz</a><br> Your order invoice is in attachment.", myAttachment);
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    throw;
                                }

                                //if payment susseed, send order to supplier
                                try
                                {
                                    using (var client = new HttpClient())
                                    {
                                        client.BaseAddress = new Uri(host1);

                                        var responseTask = client.GetAsync(currentSite + "/api/order/SendOrderToSupplier/" + orderId);
                                        responseTask.Wait();
                                        var getResult = responseTask.Result;
                                        if (getResult.IsSuccessStatusCode)
                                        {
                                            //                      return Ok("order sent!");
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                    throw;
                                }
                            }
                            catch (Exception)
                            {
                                throw;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        //                    dbContextTransaction.Rollback();
                        return(BadRequest(ex));
                    }
                    finally
                    {
                        connect.Close();
                        connect.Dispose();
                    }
                }
            }
            return(Redirect(returnUrl));
        }
Ejemplo n.º 9
0
        public async Task <ResponseOutput> ResponseOutput(string result, string userid)
        {
            string PxPayUserId = _configuration.GetSection("WindCave:PxPayUserId").Value;//.AppSettings["PxPayUserId"];
            string PxPayKey    = _configuration.GetSection("WindCave:PxPayKey").Value;
            //string PxPayKey = ConfigurationManager.AppSettings["PxPayKey"];

            PxPay WS = new PxPay(PxPayUserId, PxPayKey);

            ResponseOutput response     = WS.ProcessResponse(result);
            var            payment      = UpdatePaymentFromResponse(response);
            var            cart         = _context.Cart.Where(x => x.CartId == payment.CardId).First();
            var            contact      = _context.Contact.Where(x => x.ContactId == cart.ContactId).First();
            var            producttimes = _context.ProductTimetable.Where(x => x.CartId == payment.CardId).ToList();
            var            saleprods    = _context.CartProd.Where(x => x.CartId == payment.CardId && x.SaleProdId != null).ToList();
            var            cartProd     = GetCartProds(payment.CardId);

            if (payment.Success == 1)
            {
                cart.IsPay         = 1;
                cart.CartStatusId  = 1;
                cart.RentalPaidFee = Convert.ToDecimal(payment.AmountSettlemen);
            }
            if (payment.Success == 0)
            {
                cart.IsExpired = 1;
                foreach (var producttime in producttimes)
                {
                    producttime.IsActive = 0;
                    _context.ProductTimetable.Update(producttime);
                }
                foreach (CartProd saleProd in saleprods)
                {
                    var saleProdToUpdate = await _context.SaleProducts.Where(x => x.SaleProdId == saleProd.SaleProdId).FirstOrDefaultAsync();

                    saleProdToUpdate.AvailableStock += saleProd.Quantity;
                    _context.SaleProducts.Update(saleProdToUpdate);
                }
                Popup popup = await _context.Popups.Where(x => x.Coupon == cart.Coupon).FirstOrDefaultAsync();

                if (popup != null)
                {
                    popup.IsValid = 1;
                    _context.Popups.Update(popup);
                }
            }
            _context.Payment.Update(payment);
            _context.Cart.Update(cart);

            await _context.SaveChangesAsync();

            CartModel cartModel = new CartModel
            {
                CartId         = cart.CartId,
                Location       = cart.Location,
                Price          = cart.Price,
                SavedAmount    = cart.SavedAmount,
                DeliveryFee    = cart.DeliveryFee,
                DepositFee     = cart.DepositFee,
                DepositPaidFee = cart.DepositPaidFee,
                RentalPaidFee  = cart.RentalPaidFee,
                IsPickup       = cart.IsPickup,
                EventStartDate = (DateTime)cart.EventStartDate,
                EventEndDate   = (DateTime)cart.EventEndDate,
                CartProd       = cartProd,
                Contact        = contact,
            };

            if (payment.Success == 1 && cart.IsEmailSend != 1)
            {
                SendCartEmail(cartModel);
                cart.IsEmailSend = 1;
                _context.Cart.Update(cart);
                _context.SaveChanges();
            }

            return(response);
        }
        //   [Consumes("application/x-www-form-urlencoded")]
        public async Task <IActionResult> GetPaymentResult([FromQuery] string result, [FromQuery] string action, [FromQuery] string orderId)
        {
            PxPay          WS        = new PxPay(sServiceUrl, PxPayUserId, PxPayKey);
            ResponseOutput outputQs  = WS.ProcessResponse(result);
            string         DpsTxnRef = outputQs.DpsTxnRef;
            string         sSuccess  = outputQs.Success;
            string         returnUrl = outputQs.TxnData1;

            if (returnUrl == "")
            {
                returnUrl = "www.google.com";
            }

            if (result == null)
            {
                return(NotFound());
            }
            if (action != "paymentSuccess")
            {
                return(BadRequest("Sorry, payment unsuccessful. Please try later. "));
            }


            //1. Check if payment info record
            if (await _context.DpsOutput.AnyAsync(d => d.OrderId.ToString() == orderId)) //&& d.TxnId == outputQs.TxnId))
            {
                //if info recorded
            }
            else
            {
                //Record dps payment status
                var connectionString = _config.GetConnectionString("appContext");//_context.Database.GetDbConnection().ConnectionString;
                var conn             = new SqlConnection(connectionString);
                conn.Open();
                var comm = new SqlCommand("insert into DpsOutput(Order_Id, valid, Amount_Settlement, Auth_Code,Card_Name,CardNumber,Date_Expiry,Dps_Txn_Ref,Success," +
                                          "Response_Text,Dps_Billing_Id,Card_Holder_Name,Currency_Settlement,Txn_Data1,Txn_Data2,Txn_Data3,Txn_Type, Currency_Input,Merchant_Reference," +
                                          "Client_Info,Txn_Id, Email_Address,Billing_Id,Txn_Mac )values('" + orderId + "','" + outputQs.valid + "', " +
                                          "                                                                                   '" + outputQs.AmountSettlement + "', " +
                                          "                                                                                   '" + outputQs.AuthCode + "'," +
                                          "                                                                                   '" + outputQs.CardName + "'," +
                                          "                                                                                   '" + outputQs.CardNumber + "', " +
                                          "                                                                   '" + outputQs.DateExpiry + "', " +
                                          "                                                   '" + outputQs.DpsTxnRef + "', " +
                                          "                                   '" + outputQs.Success + "', " +
                                          "                   '" + outputQs.ResponseText + "', " +
                                          "                                                                                   '" + outputQs.DpsBillingId + "', " +
                                          "                                                                                   '" + outputQs.CardHolderName + "', " +
                                          "                                                                                   '" + outputQs.CurrencySettlement + "', " +
                                          "                                                                                   '" + outputQs.TxnData1 + "', " +
                                          "                                                                                   '" + outputQs.TxnData2 + "', " +
                                          "                                                                                   '" + outputQs.TxnData3 + "', " +
                                          "                                                                                   '" + outputQs.TxnType + "', " +
                                          "                                                                                   '" + outputQs.CurrencyInput + "', " +
                                          "                                                                                   '" + outputQs.MerchantReference + "', " +
                                          "                                                                                   '" + outputQs.ClientInfo + "', " +
                                          "                                                                                   '" + outputQs.TxnId + "', " +
                                          "                                                                                   '" + outputQs.EmailAddress + "', " +
                                          "                                                                                   '" + outputQs.BillingId + "', " +
                                          "                                                                                   '" + outputQs.TxnMac + "'" +
                                          "                                                                                        )");

                try
                {
                    comm.Connection = conn;
                    comm.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex.Message + "\r\n" + $"Record dps payment info error, order id: {orderId}.");
                    return(BadRequest(ex.Message));
                }
                finally
                {
                    conn.Close();
                }
            }


            var isProcessed = _context.TranDetail.Any(td => td.Note == DpsTxnRef || td.PaymentRef == DpsTxnRef);

            if (isProcessed)
            {
                // return BadRequest("Order " + orderId + " has been processed!");
                return(Ok(returnUrl));
            }

            PropertyInfo[] properties = outputQs.GetType().GetProperties();
            foreach (PropertyInfo oPropertyInfo in properties)
            {
                if (oPropertyInfo.CanRead)
                {
                    string name  = oPropertyInfo.Name;
                    string value = (string)oPropertyInfo.GetValue(outputQs, null);
                }
            }

            var order = _context.Orders.Where(o => o.Id == Convert.ToInt32(orderId))
                        .Join(_context.Invoices,
                              o => o.InvoiceNumber,
                              i => i.InvoiceNumber,
                              (o, i) => new { o.InvoiceNumber, o.Id, o.CardId, Total = i.Total ?? 0 }).FirstOrDefault();
            int     cardId        = 0;
            decimal orderAmount   = 0;
            string  customerEmail = "";

            var customer = await _context.Cards.FirstOrDefaultAsync(c => c.Id == order.CardId);

            if (customer != null)
            {
                customerEmail = customer.Email;
            }
            if (order != null)
            {
                cardId      = order.CardId;
                orderAmount = order.Total;
            }

            int paymentmethod = _isettings.getIdByPaymentMethod("dps");// 14; // paymentMethodCast(paymentInfo.payment_method);

            if (sSuccess == "1")
            {
                var invoiceExists = await _context.TranInvoices.AnyAsync(ti => ti.InvoiceNumber == order.InvoiceNumber);

                if (invoiceExists)
                {
                    return(BadRequest($"This order {orderId} has already been processed!"));
                }
                var connect       = _context.Database.GetDbConnection();
                var connectstring = _context.Database.GetDbConnection().ConnectionString;
                connect.Open();
                System.Data.Common.DbCommand dbCommand = connect.CreateCommand();

                //              using (var dbContextTransaction = connect.BeginTransaction())
                {
                    //input payment info
                    try
                    {
                        var note = dbCommand.CreateParameter();
                        note.ParameterName = "@note";
                        note.DbType        = System.Data.DbType.String;
                        note.Value         = DpsTxnRef;     //insert dps ref to tran_detail tables

                        var Payment_Ref = dbCommand.CreateParameter();
                        Payment_Ref.ParameterName = "@payment_ref";
                        Payment_Ref.DbType        = System.Data.DbType.String;
                        Payment_Ref.Value         = DpsTxnRef;

                        var shop_branch = dbCommand.CreateParameter();
                        shop_branch.ParameterName = "@shop_branch";
                        shop_branch.DbType        = System.Data.DbType.Int32;
                        shop_branch.Value         = _isettings.getOnlineShopId();

                        var Amount = dbCommand.CreateParameter();
                        Amount.ParameterName = "@Amount";
                        Amount.DbType        = System.Data.DbType.String;
                        Amount.Value         = order.Total;


                        var nDest = dbCommand.CreateParameter();
                        nDest.ParameterName = "@nDest";
                        nDest.DbType        = System.Data.DbType.Int32;
                        nDest.Value         = "1116";

                        var staff_id = dbCommand.CreateParameter();
                        staff_id.ParameterName = "@staff_id";
                        staff_id.DbType        = System.Data.DbType.Int32;
                        staff_id.Value         = order.CardId.ToString();

                        var card_id = dbCommand.CreateParameter();
                        card_id.ParameterName = "@card_id";
                        card_id.DbType        = System.Data.DbType.Int32;
                        card_id.Value         = order.CardId.ToString();

                        var payment_method = dbCommand.CreateParameter();
                        payment_method.ParameterName = "@payment_method";
                        payment_method.DbType        = System.Data.DbType.Int32;
                        payment_method.Value         = paymentmethod;

                        var invoice_number = dbCommand.CreateParameter();
                        invoice_number.ParameterName = "@invoice_number";
                        invoice_number.DbType        = System.Data.DbType.Int32;
                        invoice_number.Value         = Convert.ToInt32(order.InvoiceNumber);

                        var amountList = dbCommand.CreateParameter();
                        amountList.ParameterName = "@amountList";
                        amountList.DbType        = System.Data.DbType.String;
                        amountList.Value         = orderAmount;


                        var return_tran_id = dbCommand.CreateParameter();
                        return_tran_id.ParameterName = "@return_tran_id";
                        return_tran_id.Direction     = System.Data.ParameterDirection.Output;
                        return_tran_id.DbType        = System.Data.DbType.Int32;

                        var return_exist_trans = dbCommand.CreateParameter();
                        return_exist_trans.ParameterName = "@return_exist_trans";
                        return_exist_trans.Direction     = System.Data.ParameterDirection.Output;
                        return_exist_trans.DbType        = System.Data.DbType.Boolean;

                        dbCommand.Parameters.Add(note);
                        dbCommand.Parameters.Add(Payment_Ref);
                        dbCommand.Parameters.Add(shop_branch);
                        dbCommand.Parameters.Add(Amount);
                        dbCommand.Parameters.Add(staff_id);
                        dbCommand.Parameters.Add(card_id);
                        dbCommand.Parameters.Add(payment_method);
                        dbCommand.Parameters.Add(invoice_number);
                        dbCommand.Parameters.Add(amountList);
                        dbCommand.Parameters.Add(return_tran_id);
                        dbCommand.Parameters.Add(return_exist_trans);
                        dbCommand.CommandText = "eznz_payment";
                        dbCommand.CommandType = System.Data.CommandType.StoredProcedure;
                        var obj = await dbCommand.ExecuteNonQueryAsync();


                        //if trans exists, do not send invoice and order
                        string sExist_trans = return_exist_trans.Value.ToString();//dbCommand.Parameters["@return_exist_trans"].Value.ToString();
                        if (sExist_trans == null || sExist_trans == "0" || sExist_trans == "")
                        {
                            try
                            {
                                //create invoice pdf
                                var    host        = "http://" + HttpContext.Request.Host;
                                string host1       = _config["ApiUrl"]; // "http://api171.gpos.nz";
                                var    currentSite = _config["CurrentSite"];
                                var    PdfUrl      = _config["PdfUrl"];
                                try
                                {
                                    //ConversionOptions options = new ConversionOptions(PageSize.A4, PageOrientation.Portrait, 5.0f);
                                    //var directory = _config["PdfPath"] + "//invoice//" + order.InvoiceNumber + ".pdf";
                                    //try
                                    //{
                                    //    // Set Metadata for the PDF
                                    //    options.Author = "Myself";
                                    //    options.Title = "My Webpage";
                                    //    // Set Header and Footer text
                                    //    options.Header = "";
                                    //    options.Footer = "";
                                    //    Converter.Convert(new Uri(_config["PdfUrl"] + order.InvoiceNumber), directory, options);
                                    //    //send pdf to customer
                                    //    var myAttachment = new Attachment(_config["PdfPath"] + "//invoice//" + order.InvoiceNumber + ".pdf");
                                    //    await _mail.sendEmail(customerEmail, "Invoice", "DoNotReply! <br><br> Dear customer: <br>Thank you for your order.</a><br> Your order invoice is in attachment.", myAttachment);
                                    //}
                                    //catch (Exception ex)
                                    //{
                                    //    _logger.LogError(ex.Message + "\r\n" + $"Send pdf to customer order unsuccessful, order id: {orderId}.");
                                    //    return BadRequest(ex.Message);
                                    //}

                                    using (var client = new HttpClient())
                                    {
                                        var data = new PdfDto()
                                        {
                                            InvoiceNumber = order.InvoiceNumber ?? 0,
                                            Url           = PdfUrl + order.InvoiceNumber
                                        };
                                        var myContent   = JsonConvert.SerializeObject(data);
                                        var buffer      = System.Text.Encoding.UTF8.GetBytes(myContent);
                                        var byteContent = new ByteArrayContent(buffer);
                                        byteContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");

                                        client.BaseAddress = new Uri(host1);
//										var responseTask = client.GetAsync(currentSite + "/api/invoice/pdf/" + orderId);
                                        var responseTask = client.PostAsync(currentSite + "/api/invoice/pdf", byteContent);
                                        responseTask.Wait();

                                        var getResult = responseTask.Result;
                                        if (getResult.IsSuccessStatusCode)
                                        {
                                            //send order to customer by email
                                            var myAttachment = new Attachment(_config["PdfPath"] + "//invoice//" + order.InvoiceNumber + ".pdf");
                                            await _mail.sendEmail(customerEmail, "Invoice", "DoNotReply! <br><br> Dear customer: <br>Thank you for your order from<a href='http://dollaritems.co.nz/ecom'> dollaritems.co.nz</a><br> Your order invoice is in attachment.", myAttachment);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    _logger.LogError(ex.Message + "\r\n" + $"Send pdf to customer order unsuccessful, order id: {orderId}.");
                                    return(BadRequest(ex.Message));
                                }

                                var manage = _config["Management"];
                                if (manage == "true")
                                {
                                    //if payment susseed, send order to supplier
                                    try
                                    {
                                        using (var client = new HttpClient())
                                        {
                                            client.BaseAddress = new Uri(host1);

                                            var responseTask = client.GetAsync(currentSite + "/api/order/SendOrderToSupplier/" + orderId);
                                            responseTask.Wait();
                                            var getResult = responseTask.Result;
                                            if (getResult.IsSuccessStatusCode)
                                            {
                                                //set a key, if order send to supplier successfully
                                                var currentOrderDpsOutput = await _context.DpsOutput.FirstOrDefaultAsync(d => d.OrderId.ToString() == orderId);

                                                if (currentOrderDpsOutput == null)
                                                {
                                                    _logger.LogError($"Cannot find this order, when send order to supplier, order id: {orderId}.");
                                                    return(NotFound());
                                                }
                                                currentOrderDpsOutput.OrderSent = true;
                                                _context.DpsOutput.Update(currentOrderDpsOutput);
                                                await _context.SaveChangesAsync();
                                            }
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        _logger.LogError(ex.Message + "\r\n" + $"Send order to supplier unsuccessful, order id: {orderId}.");
                                        BadRequest(ex);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex.Message + "\r\n" + $"Send order to supplier unsuccessful, order id: {orderId}.");
                                BadRequest(ex.Message);
                            }
                        }
                        else
                        {
                            _logger.LogError($"Transcation for this order exists, order id: {orderId}.");
                        }
                    }
                    catch (Exception ex)
                    {
                        //                    dbContextTransaction.Rollback();
                        _logger.LogError(ex.Message + "\r\n" + $"Insert transaction into Db unsuccessful, order id: {orderId}.");
                        return(BadRequest(ex));
                    }
                    finally
                    {
                        connect.Close();
                        connect.Dispose();
                    }
                }
            }
            else
            {
                _logger.LogError($"Payment for order {orderId} unsuccessful.");
            }
            return(Ok(returnUrl));
        }