コード例 #1
0
        public ActionResult iPay88CheckOut(string destinationUrl, PaymentSubmitModels payment, bool requireAuthCapture = false)
        {
            bool isUseAuthCapt = bool.TryParse(Core.GetAppSettingValueEnhanced("iPay88CCAuthCapture"), out isUseAuthCapt) ? isUseAuthCapt : isUseAuthCapt;

            if (payment == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            string paymentId = null;

            switch (payment.PaymentMethod.ToLower())
            {
            case "ipacc":
                paymentId = requireAuthCapture && isUseAuthCapt ? "55" : "2";
                break;

            case "ipafpx":
                paymentId = "16";
                break;

            default:
                break;
            }

            NameValueCollection formData = new NameValueCollection();
            string iPay88POSTURL         = Core.GetAppSettingValueEnhanced("iPay88POSTURL");

            if (!string.IsNullOrEmpty(payment.BookingNo))
            {
                // The Merchant Code provided by iPay88 and use to uniquely identify the Merchant.
                string iPay88AppId = Core.GetAppSettingValueEnhanced("iPay88AppId");

                string iPay88Testing = Core.GetAppSettingValueEnhanced("iPay88Testing");
                bool   isTestingAcc  = bool.TryParse(iPay88Testing, out isTestingAcc) ? isTestingAcc : isTestingAcc;

                formData.Add("AppId", iPay88AppId);
                // Refer to Appendix I.pdf
                formData.Add("PaymentId", paymentId);

                // Ref No only allow 20 char.
                formData.Add("RefNo", payment.BookingId + " - " + payment.BookingNo);
                formData.Add("Amount", isTestingAcc ? "1.00" : payment.PaymentAmount.ToString("n2"));

                formData.Add("Currency", payment.Currency);
                formData.Add("ProdDesc", "MayFlower Booking Payment - " + payment.BookingNo);
                formData.Add("UserName", payment.UserName);
                formData.Add("UserEmail", payment.UserEmail);
                formData.Add("UserContact", string.IsNullOrEmpty(payment.UserContact) ? "-" : payment.UserContact);
                // Refer to Technical Spec
                //formData.Add("Lang", "UTF-8");
                formData.Add("ResponseURL", destinationUrl);
            }

            string postURL = iPay88POSTURL;
            string strForm = PreparePOSTForm(postURL, formData);

            return(Content(strForm));
        }
コード例 #2
0
        public static PaymentSubmitModels PopulatePaymentSubmitModel(DateTime bookingDate, int bookingId, string bookingNo, string currencyCode, decimal totalAmount, string paymentMethod, string userContact, string userEmail, string userFullName)
        {
            PaymentSubmitModels paymentSubmitModel = new PaymentSubmitModels();

            paymentSubmitModel.BookingDate   = bookingDate;
            paymentSubmitModel.BookingId     = bookingId;
            paymentSubmitModel.BookingNo     = bookingNo;
            paymentSubmitModel.Currency      = currencyCode;
            paymentSubmitModel.PaymentAmount = totalAmount;
            paymentSubmitModel.PaymentMethod = paymentMethod;
            paymentSubmitModel.UserContact   = userContact;
            paymentSubmitModel.UserEmail     = userEmail;
            paymentSubmitModel.UserName      = userFullName;

            return(paymentSubmitModel);
        }
コード例 #3
0
        public async Task <ActionResult> Checkout(PaymentCheckout payment, string paymentID = null)
        {
            string _pMethod = payment.PaymentMethod?.ToLower();

            if (_pMethod != null && _pMethod.Contains("adyen"))
            {
                // Reflection get credit card property to remove model validation
                var ccModel = typeof(Alphareds.Module.Model.CreditCard);

                foreach (var item in ccModel.GetProperties())
                {
                    // Remove model validtion
                    ModelState[item.Name]?.Errors.Clear();
                }
            }

            // If member not verify email, block place booking.
            if (User.Identity.IsAuthenticated && !CustomPrincipal.IsProfileActive && !CustomPrincipal.IsAgent)
            {
                ModelState.AddModelError("Error", "Please verify your account first, before place order.");
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Account inactive."));
            }

            string _paymentInfo = null;

            Cryptography.AES.TryDecrypt(paymentID, out _paymentInfo);

            var _superPNR = db.SuperPNRs.FirstOrDefault(x => x.SuperPNRID.ToString() == _paymentInfo);

            // Check model error before postback
            if (!ModelState.IsValid)
            {
                if (_superPNR.MainProductType == ProductTypes.Flight)
                {
                    return(RedirectToAction("OrderHistory", "Flight", new { tripid, bookingID = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else if (_superPNR.MainProductType == ProductTypes.Hotel)
                {
                    return(RedirectToAction("OrderHistory", "Hotel", new { tripid, confirmid = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Product Undefined."));
                }
            }

            var    _paymentList    = _superPNR.GetAllPaymentRecords();
            string paymentCurrency = "MYR";

            _superPNR.LoadPaymentDetailList(true, paymentCurrency);
            var paymentDtlList = _superPNR.PaymentDetailsList.FirstOrDefault(); // take converted rate, only one result

            SqlCommand command = new SqlCommand();

            // Can pass in user preferred currency code into ChkCreditAmtRemin, with optional parameter
            // Use this method to handle multi currency code in different order issues.
            decimal            creditUserAvail     = MemberServiceController.ChkCreditAmtRemain.ByUserId(CustomPrincipal.UserId, CustomPrincipal.UserTypeCode, command, paymentCurrency);
            decimal            cashWalletUserAvail = MemberServiceController.GetUserCashCredit(CustomPrincipal.UserId, command);
            CheckoutController checkoutCtl         = new CheckoutController(ControllerContext);

            decimal thisBookUsableAmt = checkoutCtl.CalcTravelCreditUsable(paymentDtlList.TotalPendingAmount, creditUserAvail, cashWalletUserAvail, DiscountType.TC);

            if (creditUserAvail >= thisBookUsableAmt && payment.UseCredit && (paymentDtlList.TotalPendingAmount <= thisBookUsableAmt))
            {
                payment.PaymentMethod = CustomPrincipal.IsAgent ? "AC" : "SC";
            }

            payment = new PaymentCheckout
            {
                AvailableCredit      = creditUserAvail,
                CreditUsed           = payment.UseCredit ? thisBookUsableAmt : 0m,
                PaymentMethod        = string.IsNullOrWhiteSpace(payment.PaymentMethod) ? CustomPrincipal.IsAgent ? "AC" : "SC" : payment.PaymentMethod,
                Policy               = payment.Policy,
                TnC                  = payment.TnC,
                UseCredit            = payment.UseCredit,
                CreditCard           = payment.CreditCard,
                CreditTerm           = CustomPrincipal.CreditTerm,
                PaymentCurrencyCode  = paymentDtlList.CurrencyCode,
                GrandTotalForPayment = paymentDtlList.TotalPendingAmount
            };

            PromoCodeFunctions  promoCodeFunctions          = new PromoCodeFunctions(_superPNR._MainPromoID, db);
            decimal             ttlOrderUsedTCAmountUseable = payment.CreditUsed;
            decimal             ttlTCAmtUsed         = 0m;
            List <PaymentOrder> paymentOrderToInsert = new List <PaymentOrder>();

            foreach (var _orderId in paymentDtlList.OrdersPendingPayment)
            {
                var _orders = _superPNR.SuperPNROrders.FirstOrDefault(x => x.OrderID == _orderId);

                #region Insert/Update Processing Fee
                var           feeChargeOrder = _orders.FeeChargeOrders.FirstOrDefault();
                ProcessingFee pf             = new ProcessingFee(payment.PaymentMethod, _orders.PendingPaymentAmt, _superPNR.MainProductType, promoCodeFunctions, paymentCurrency);

                var latestFeeCharge = new FeeChargeOrder
                {
                    OrderID         = _orders.OrderID,
                    CreatedByID     = _superPNR.CreatedByID,
                    CurrencyCode    = _orders.CurrencyCode,
                    FeeChargeAmount = pf.Amt,
                    FeeCode         = string.IsNullOrWhiteSpace(pf.FeeCode) ? payment.PaymentMethod : pf.FeeCode,
                    TaxCode         = string.IsNullOrWhiteSpace(pf.TaxCode) ? "ES" : pf.TaxCode,
                    TaxAmount       = pf.GST,
                    ModifiedByID    = CurrentUserID,
                    SuperPNROrder   = _orders,
                };

                if (feeChargeOrder == null)
                {
                    _orders.FeeChargeOrders.Add(latestFeeCharge); // for model calculation
                    PaymentServiceController.InsertFeeChargeOrder(latestFeeCharge, command);
                }
                else
                {
                    // For model calculation only
                    feeChargeOrder.CurrencyCode    = _orders.CurrencyCode;
                    feeChargeOrder.FeeChargeAmount = pf.Amt;
                    feeChargeOrder.FeeCode         = string.IsNullOrWhiteSpace(pf.FeeCode) ? payment.PaymentMethod : pf.FeeCode;
                    feeChargeOrder.TaxCode         = string.IsNullOrWhiteSpace(pf.TaxCode) ? "ES" : pf.TaxCode;
                    feeChargeOrder.TaxAmount       = pf.GST;

                    PaymentServiceController.UpdateFeeChargeOrder(latestFeeCharge, command);
                }
                #endregion

                if (payment != null && payment.UseCredit && payment.CreditUsed > 0 && (payment.PaymentMethod != "SC" && payment.PaymentMethod != "AC"))
                {
                    decimal _thisTransAmt      = _orders.PendingPaymentAmt;
                    decimal _thisTransUseTCAmt = ttlOrderUsedTCAmountUseable;
                    bool    usedAllTC          = ttlTCAmtUsed == payment.CreditUsed;

                    if (ttlOrderUsedTCAmountUseable > _thisTransAmt && !usedAllTC)
                    {
                        _thisTransUseTCAmt = _thisTransAmt;
                    }

                    if (ttlOrderUsedTCAmountUseable > 0 && !usedAllTC)
                    {
                        ttlOrderUsedTCAmountUseable -= _thisTransUseTCAmt;
                        ttlTCAmtUsed += _thisTransUseTCAmt;

                        PaymentOrder tcPaymentOrder = new PaymentOrder
                        {
                            OrderID             = _orders.OrderID,
                            PaymentDate         = DateTime.Now,
                            PaymentMethodCode   = CustomPrincipal.IsAgent ? "AC" : "SC",
                            PaymentStatusCode   = "PEND",
                            CurrencyCode        = _orders.CurrencyCode,
                            PaymentAmount       = _thisTransUseTCAmt,
                            ImagePath           = string.Empty,
                            Ipay88RefNo         = string.Empty,
                            Ipay88TransactionID = string.Empty,
                            CreatedByID         = CurrentUserID,
                            ModifiedByID        = CurrentUserID
                        };

                        paymentOrderToInsert.Add(tcPaymentOrder);

                        // Update SuperPNR Order indicated is Credit Used.
                        _orders.CreditAmount += _thisTransUseTCAmt;
                        _orders.IsCreditUsed  = _orders.CreditAmount > 0;
                        HotelServiceController.UpdateSuperPNROrder(_orders, command);
                    }
                }
                else
                {
                    // Update SuperPNR Order indicated is Credit Used.
                    _orders.CreditAmount = _orders.PaymentOrders.Where(x => (x.PaymentMethodCode == "AC" || x.PaymentMethodCode == "SC") && x.PaymentStatusCode == "PAID").Sum(s => s.PaymentAmount);
                    _orders.IsCreditUsed = _orders.CreditAmount > 0;
                    HotelServiceController.UpdateSuperPNROrder(_orders, command);
                }

                decimal paymentPrepareToInsert = paymentOrderToInsert.Where(x => x.OrderID == _orders.OrderID).Sum(s => s.PaymentAmount);

                if (paymentPrepareToInsert < _orders.PendingPaymentAmt)
                {
                    PaymentOrder normalPayment = new PaymentOrder
                    {
                        OrderID             = _orders.OrderID,
                        PaymentDate         = DateTime.Now,
                        PaymentMethodCode   = payment.PaymentMethod,
                        PaymentStatusCode   = "PEND",
                        CurrencyCode        = _orders.CurrencyCode,
                        PaymentAmount       = _orders.PendingPaymentAmt - paymentPrepareToInsert,
                        ImagePath           = string.Empty,
                        Ipay88RefNo         = string.Empty,
                        Ipay88TransactionID = string.Empty,
                        CreatedByID         = CurrentUserID,
                        ModifiedByID        = CurrentUserID
                    };

                    paymentOrderToInsert.Add(normalPayment);
                }
            }

            decimal    ttlAmtPOSTGateway    = paymentOrderToInsert.Where(x => x.PaymentMethodCode != "SC" && x.PaymentMethodCode != "AC").Sum(s => s.PaymentAmount);
            List <int> paymentOrderInserted = new List <int>();

            #region Insert SupperPNROrders records into DB
            try
            {
                foreach (var paymentRecord in paymentOrderToInsert)
                {
                    paymentOrderInserted.Add(PaymentServiceController.InsertPaymentOrder(paymentRecord, command));
                }

                #region Payment Gateway Redirect
                _superPNR.GetContactPerson();
                var contactPerson             = _superPNR.ContactPerson;
                PaymentSubmitModels iPayModel = PaymentController.PopulatePaymentSubmitModel(DateTime.Now, _superPNR.SuperPNRID, _superPNR.SuperPNRNo, paymentCurrency, ttlAmtPOSTGateway, payment.PaymentMethod, contactPerson.Phone1, contactPerson.Email, contactPerson.FullName);

                // Save transaction before redirect
                command.Transaction.Commit();

                string clientIP              = HttpContext.Request.UserHostAddress;
                string paymentMethod         = payment.PaymentMethod.ToUpper();
                string token                 = _superPNR.SuperPNRID.ToString() + "," + _superPNR.SuperPNRNo;
                string encToken              = General.CustomizeBaseEncoding.CodeBase64(token);
                string encPaymentOrderIDList = Cryptography.AES.Encrypt(paymentOrderInserted.JoinToString(","));

                FormCollection             form = new FormCollection();
                adyenCaptureResponseModels captureResponseModels2 = new adyenCaptureResponseModels();
                iPayCaptureResponseModels  captureResponseModels  = new iPayCaptureResponseModels
                {
                    Status = "1", Amount = iPayModel.PaymentAmount, TransId = ""
                };

                switch (payment.PaymentMethod.ToLower())
                {
                case "sc":
                    form.Add("Status", captureResponseModels.Status);
                    form.Add("Amount", captureResponseModels.Amount.ToString("n2"));

                    return(await checkoutCtl.PaymentCheckOut(form, captureResponseModels, captureResponseModels2, encToken, tripid, encPaymentOrderIDList, true));

                case "ac":
                    form.Add("Status", captureResponseModels.Status);
                    form.Add("Amount", captureResponseModels.Amount.ToString("n2"));

                    return(await checkoutCtl.PaymentCheckOut(form, captureResponseModels, captureResponseModels2, encToken, tripid, encPaymentOrderIDList, true));

                case "ipacc":
                    return(iPay88CheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), iPayModel, true));

                case "ipafpx":
                    return(iPay88CheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), iPayModel));

                case "adyenc":
                    AdyenCardPaymentModels adyenModel = PaymentController.PopulateAdyenPaymentSubmitModel(_superPNR.SuperPNRID, Request.Url.Scheme, _superPNR.SuperPNRNo, paymentCurrency, ttlAmtPOSTGateway, contactPerson.Email, payment.CreditCard);
                    return(AdyenCheckOut(Url.Action("PaymentCheckOut", "Checkout", new { token = encToken, tripid, paymentOdToken = encPaymentOrderIDList, fromRepay = true }, Request.Url.Scheme), adyenModel, Request.Form));

                default:
                    ModelState.AddModelError("Error", "Payment Method Not Found.");
                    break;
                }

                #endregion
            }
            catch (Exception ex)
            {
                // Insert payment record failed.
                command?.Transaction?.Rollback();

                // Handle redirect back to OrderHistory Page
                ViewBag.PaymentDetails = payment;
                ModelState.AddModelError("Error", "Unexpected error occured, please try again later.");

                string errorMsg = $"Insert Payment Order record failed on OrderHistory repayment.";
                logger.Fatal(ex, errorMsg);

                if (_superPNR.MainProductType == ProductTypes.Flight)
                {
                    return(RedirectToAction("OrderHistory", "Flight", new { tripid, bookingID = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else if (_superPNR.MainProductType == ProductTypes.Hotel)
                {
                    return(RedirectToAction("OrderHistory", "Hotel", new { tripid, confirmid = _superPNR.SuperPNRNo, status = "payment-fail" }));
                }
                else
                {
                    return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Product Undefined."));
                }
            }
            #endregion

            return(null);
        }