/// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            int reffNumber = postProcessPaymentRequest.Order.Id;
            if (_bPayPaymentSettings.RefNumberBaseOn.Equals("CustomerNumber", StringComparison.InvariantCultureIgnoreCase))
            {
                reffNumber = postProcessPaymentRequest.Order.CustomerId;
            }
            //Generate BPAY CRN
            string bPayReff = BPayHelper.GenerateBPayCRN(reffNumber.ToString());
            
            var order = _orderService.GetOrderById(postProcessPaymentRequest.Order.Id);
                if (order != null)
                {
                
                    var sb = new StringBuilder();
                    sb.AppendLine("BPay Payment Detail:");
                    sb.AppendLine("Biller Code: "+ _bPayPaymentSettings.BillerCode);
                    sb.AppendLine("Ref : " + bPayReff);

                    //order note
                    order.OrderNotes.Add(new OrderNote()
                    {
                        Note = sb.ToString(),
                        DisplayToCustomer = true,
                        CreatedOnUtc = DateTime.UtcNow
                    });
                    _orderService.UpdateOrder(order);
                }
                
            }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        /// public void
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //Todo: اگر مشخصات اولیه درگاه ثبت نشده باشد، نباید خطا داشته باشیم.
            var order = postProcessPaymentRequest.Order;
            #region [Call bpMellat Web Service]

            var orderTotal = Math.Round(order.OrderTotal, 2);
            var mellatOrderId = _mellatPaymentSettings.OrderId;
            var terminalId = _mellatPaymentSettings.TerminalId;
            var userName = _mellatPaymentSettings.UserName;
            var userPassword = _mellatPaymentSettings.UserPassword;
            var price = Convert.ToInt64(orderTotal);
            const string description = "خرید از بازار اینترنتی";
            var callBackUrl = _webHelper.GetStoreLocation(false)
                              + "Plugins/PaymentMellat/CallBack?OrderId="
                              + order.Id;
            do
            {
                BypassCertificateError();
                var payDate = DateTime.Now.Year +
                              DateTime.Now.Month.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') +
                              DateTime.Now.Day.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');
                var payTime = DateTime.Now.Hour.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') +
                              DateTime.Now.Minute.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0') +
                              DateTime.Now.Second.ToString(CultureInfo.InvariantCulture).PadLeft(2, '0');

                var bpService = new ir.shaparak.bpm.PaymentGatewayImplService();
                var result = bpService.bpPayRequest(Int64.Parse(terminalId),
                    userName,
                    userPassword,
                    mellatOrderId,
                    price,
                    payDate,
                    payTime,
                    description,
                    callBackUrl,
                    0);

                string url, comment;
                var resultArray = result.Split(',');
                if (resultArray[0] == "0") // آماده برای انتقال به بانک
                {
                    order.CaptureTransactionId = mellatOrderId.ToString(CultureInfo.InvariantCulture);
                    _orderService.UpdateOrder(order);
                    UpdateOrderId(++mellatOrderId, null);
                    url = (_webHelper.GetStoreLocation(false)
                                             + "Plugins/PaymentMellat/Pay?result="
                                             + resultArray[1]);
                    _httpContext.Response.Redirect(url, true);
                }
                switch (result)
                {
                    case "41": // Order Id Already Exist
                        mellatOrderId++;
                        break;
                    case "421":// Invalid IP
                        comment = Utility.ErrorCode("bpPayRequest", result);
                        url = (_webHelper.GetStoreLocation(false)
                                                 + string.Format("Plugins/PaymentMellat/Error?result={0}&cashRefId={1}&insRefId={2}&cachOrder={3}&insOrder={4}&id={5}"
                                                     , comment, "", "", mellatOrderId, "", order.Id));
                        _httpContext.Response.Redirect(url, true);
                        break;
                    default:   // Other Errors
                        comment = Utility.ErrorCode("bpPayRequest");
                        url = (_webHelper.GetStoreLocation(false)
                                                 + string.Format("Plugins/PaymentMellat/Error?result={0}&cashRefId={1}&insRefId={2}&cachOrder={3}&insOrder={4}&id={5}"
                                                     , comment, "", "", mellatOrderId, "", order.Id));
                        _httpContext.Response.Redirect(url, true);
                        break;
                }
            }
            while (true);
            #endregion
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //��ѯ΢��֧���Ƿ����
            WxPayApi.OrderQuery()
            string service = "create_direct_pay_by_user";

            string seller_email = _weixinPayPaymentSettings.SellerEmail;
            string sign_type = "MD5";
            string key = _weixinPayPaymentSettings.Key;
            string partner = _weixinPayPaymentSettings.Partner;
            string input_charset = "utf-8";

            string show_url = _webHelper.GetStoreLocation(false);

            string out_trade_no = postProcessPaymentRequest.Order.OrderGuid.ToString();
            string subject = string.IsNullOrEmpty(_weixinPayPaymentSettings.InvoiceSubject) ? _storeContext.CurrentStore.Name : _weixinPayPaymentSettings.InvoiceSubject;
            //string body = _weixinPayPaymentSettings.InvoiceBody;
            string body = "";
            foreach (var item in postProcessPaymentRequest.Order.OrderItems)
            {
                if (item.Product.Name.Length > 100)
                    body += item.Product.Name.Substring(0, 100) + "...,";
                else
                    body += item.Product.Name + ",";

            }
            body = body.Substring(0, body.Length - 1);
            if (body.Length > 999)
            {
                body = body.Substring(0, 996) + "...";
            }

            string total_fee = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);

            string notify_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentWeiXinPay/Notify";
            string return_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentWeiXinPay/Return";

            var paymethod = "directPay"; //bankPay:����֧���� directPay:֧������ʱ����
            var defaultBank = "";

            var customInfo = postProcessPaymentRequest.Order.DeserializeCustomValues();
            if (customInfo != null && customInfo.Count > 0)
            {
                if (customInfo.ContainsKey(WeiXinPayPaymentSystemNames.SelectedAlipayPayMethod))
                {
                    paymethod = customInfo[WeiXinPayPaymentSystemNames.SelectedAlipayPayMethod].ToString();
                    if (!string.IsNullOrEmpty(paymethod) && paymethod != WeiXinPayPaymentSystemNames.DirectPay)
                    {
                        //Ĭ������
                        defaultBank = paymethod;//������ݵ�paymethod������directPay,���ʾʹ������֧����paymethod��ʾ���б���

                        //Ĭ��֧����ʽ
                        paymethod = WeiXinPayPaymentSystemNames.BankPay;
                    }
                }
            }

            IList<string> paraList = new List<string>();
            paraList.Add("service=" + service);
            paraList.Add("partner=" + partner);
            paraList.Add("seller_email=" + seller_email);
            paraList.Add("out_trade_no=" + out_trade_no);
            paraList.Add("subject=" + subject);
            paraList.Add("body=" + body);
            paraList.Add("total_fee=" + total_fee);
            paraList.Add("show_url=" + show_url);
            paraList.Add("return_url=" + return_url);
            paraList.Add("notify_url=" + notify_url);
            paraList.Add("payment_type=1");
            paraList.Add("paymethod=" + paymethod);
            if (!string.IsNullOrEmpty(defaultBank))
            {
                paraList.Add("defaultbank=" + defaultBank);
            }
            paraList.Add("_input_charset=" + input_charset);

            string aliay_url = CreatUrl(
                paraList.ToArray(),
                input_charset,
                key
                );
            var post = new RemotePost();
            post.FormName = "weixinpaysubmit";
            post.Url = "https://mapi.weixinpay.com/gateway.do?_input_charset=utf-8";
            post.Method = "POST";

            post.Add("service", service);
            post.Add("partner", partner);
            post.Add("seller_email", seller_email);
            post.Add("out_trade_no", out_trade_no);
            post.Add("subject", subject);
            post.Add("body", body);
            post.Add("total_fee", total_fee);
            post.Add("show_url", show_url);
            post.Add("return_url", return_url);
            post.Add("notify_url", notify_url);
            post.Add("payment_type", "1");
            post.Add("paymethod", paymethod);
            if (!string.IsNullOrEmpty(defaultBank))
            {
                post.Add("defaultbank", defaultBank);
            }
            post.Add("sign", aliay_url);
            post.Add("sign_type", sign_type);

            post.Post();
        }
 /// <summary>
 /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
 /// </summary>
 /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
 public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     // we don't use this
 }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var builder = new StringBuilder();

            var helper = new PaymentExpressHelper(_PaymentExpressPaymentSettings.PxUrl, _PaymentExpressPaymentSettings.PxUserId, _PaymentExpressPaymentSettings.PxPassword);

            RequestInput input = new RequestInput();


            input.AmountInput = postProcessPaymentRequest.Order.OrderTotal.ToString("F");
            input.CurrencyInput = _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode;
            input.MerchantReference = postProcessPaymentRequest.Order.Id.ToString();
            input.TxnType = "Purchase";
            input.UrlFail = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPaymentExpress/CancelOrder";
            input.UrlSuccess = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPaymentExpress/PaymentComplete";
            input.TxnId = postProcessPaymentRequest.Order.Id.ToString();

            RequestOutput output = helper.GenerateRequest(input);

            if (output.valid == "1")
            {
                // Redirect user to payment page
                _httpContext.Response.Redirect(output.Url);
            }
            else
            {
                string errorStr = string.Format("Failed to process Payment Express request. Message {0}", output.URI);
                _logger.Error(errorStr);

                throw new Exception("There was an issue connecting with our Payment Provider.");
            }
        }
Exemplo n.º 6
0
        public ActionResult ConfirmFastCheckout(CheckoutDTO checkoutInfo)
        {
            checkoutInfo.UpdateShippingMethod();

            var customer = _workContext.CurrentCustomer;

            #region validation
            //validation
            var cart = customer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            if (cart.Count == 0)
                throw new Exception("Your cart is empty");

            if (!UseOnePageCheckout())
                throw new Exception("One page checkout is disabled");

            if ((customer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                throw new Exception("Anonymous checkout is not allowed");

            //prevent 2 orders being placed within an X seconds time frame
            if (!IsMinimumOrderPlacementIntervalValid(customer))
                throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));
            #endregion

            // 1. SaveBilling
            customer.SetBillingAddress(null);

            // 2. Shipping Address
            if (checkoutInfo.ShippingMethod == ShippingType.courier)
            {
                Address addressForShipping;

                string addr = checkoutInfo.Address.Trim();
                Address existingAddress = customer.Addresses.FirstOrDefault(a => a.Address1.Trim().Equals(addr, StringComparison.CurrentCultureIgnoreCase));

                if (existingAddress == null)
                {
                    addressForShipping = new Address
                    {
                        CreatedOnUtc = DateTime.UtcNow,
                        Address1 = checkoutInfo.Address,
                        PhoneNumber = checkoutInfo.MobilePhone,
                        Email = customer.Email
                    };
                    customer.AddAddress(addressForShipping);
                }
                else
                {
                    addressForShipping = existingAddress;
                }
                customer.SetShippingAddress(addressForShipping);
            }

            //3. Shipping method
            var shippingOptions = _shippingService.GetShippingOptions(cart, _workContext.CurrentCustomer.ShippingAddress, "Shipping.FixedRate");
            var shippingMethod = checkoutInfo.ShippingMethod == ShippingType.courier ? shippingOptions.ShippingOptions[1] : shippingOptions.ShippingOptions[0];
            _customerService.SaveCustomerAttribute<ShippingOption>(customer, SystemCustomerAttributeNames.LastShippingOption, shippingMethod);

            // 4. Payment method
            string paymentMethodSysName = "Payments.CashOnDelivery";
            customer.SelectedPaymentMethodSystemName = paymentMethodSysName;

            _customerService.UpdateCustomer(_workContext.CurrentCustomer);

            // Ordering...

            IPaymentMethod paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSysName);
            var paymentControllerType = paymentMethod.GetControllerType();
            var paymentController = DependencyResolver.Current.GetService(paymentControllerType) as BaseNopPaymentController;

            var processPaymentRequest = paymentController.GetPaymentInfo(new FormCollection());

            processPaymentRequest.CustomerId = customer.Id;
            processPaymentRequest.PaymentMethodSystemName = customer.SelectedPaymentMethodSystemName;

            var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
            var order = placeOrderResult.PlacedOrder;
            if (placeOrderResult.Success)
            {
                var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = order
                    };
                _paymentService.PostProcessPayment(postProcessPaymentRequest);
            }
            else
            {
                throw new Exception("Не удалось создать заказ.");
            }

            // Add comments: Note and Modile Phone
            if (!string.IsNullOrWhiteSpace(checkoutInfo.Comments))
            {
                order.OrderNotes.Add(new OrderNote
                    {
                        Note = checkoutInfo.Comments,
                        DisplayToCustomer = true,
                        CreatedOnUtc = DateTime.UtcNow
                    });
            }

            order.OrderNotes.Add(new OrderNote
            {
                Note = "Мобильный телефон: " + checkoutInfo.MobilePhone,
                DisplayToCustomer = false,
                CreatedOnUtc = DateTime.UtcNow
            });

            _orderService.UpdateOrder(order);

            return new JsonNetResult
            {
                Data = new
                {
                    redirectUrl = Url.Action("Completed")
                }
            };
        }
Exemplo n.º 7
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var myUtility = new PayuHelper();
            var orderId= postProcessPaymentRequest.Order.Id;
            var remotePostHelper = new RemotePost();
            remotePostHelper.FormName = "PayuForm";
            remotePostHelper.Url = _PayuPaymentSettings.PayUri;
            remotePostHelper.Add("key", _PayuPaymentSettings.MerchantId.ToString());
            remotePostHelper.Add("amount", postProcessPaymentRequest.Order.TotalTransactionAmount.ToString(new CultureInfo("en-US", false).NumberFormat));
			remotePostHelper.Add("productinfo", "productinfo");
            remotePostHelper.Add("Currency", _currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode);
            remotePostHelper.Add("Order_Id", orderId.ToString());
			remotePostHelper.Add("txnid", postProcessPaymentRequest.Order.OrderGuid.ToString());
			
            remotePostHelper.Add("surl", _webHelper.GetStoreLocation(true) + "PaymentPayu/Return");
			remotePostHelper.Add("furl", _webHelper.GetStoreLocation(true) + "PaymentPayu/Return");
            remotePostHelper.Add("hash", myUtility.getchecksum(_PayuPaymentSettings.MerchantId.ToString(),
                postProcessPaymentRequest.Order.OrderGuid.ToString(), postProcessPaymentRequest.Order.TotalTransactionAmount.ToString(new CultureInfo("en-US", false).NumberFormat),
                "productinfo",postProcessPaymentRequest.Order.BillingAddress.FirstName.ToString(),
                postProcessPaymentRequest.Order.BillingAddress.Email.ToString(),_PayuPaymentSettings.Key));


            //Billing details
            remotePostHelper.Add("firstname", postProcessPaymentRequest.Order.BillingAddress.FirstName.ToString());
            remotePostHelper.Add("billing_cust_address", postProcessPaymentRequest.Order.BillingAddress.Address1);
            remotePostHelper.Add("phone", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber);
            remotePostHelper.Add("email", postProcessPaymentRequest.Order.BillingAddress.Email.ToString());
            remotePostHelper.Add("billing_cust_city", postProcessPaymentRequest.Order.BillingAddress.City);
            var billingStateProvince = postProcessPaymentRequest.Order.BillingAddress.StateProvince;
            if (billingStateProvince != null)
                remotePostHelper.Add("billing_cust_state", billingStateProvince.Abbreviation);
            else
                remotePostHelper.Add("billing_cust_state", "");
            remotePostHelper.Add("billing_zip_code", postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode);
            var billingCountry = postProcessPaymentRequest.Order.BillingAddress.Country;
            if (billingCountry != null)
                remotePostHelper.Add("billing_cust_country", billingCountry.ThreeLetterIsoCode);
            else
                remotePostHelper.Add("billing_cust_country", "");

            //Delivery details

            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
            {
                remotePostHelper.Add("delivery_cust_name", postProcessPaymentRequest.Order.ShippingAddress.FirstName);
                remotePostHelper.Add("delivery_cust_address", postProcessPaymentRequest.Order.ShippingAddress.Address1);
                remotePostHelper.Add("delivery_cust_notes", string.Empty);
                remotePostHelper.Add("delivery_cust_tel", postProcessPaymentRequest.Order.ShippingAddress.PhoneNumber);
                remotePostHelper.Add("delivery_cust_city", postProcessPaymentRequest.Order.ShippingAddress.City);
                var deliveryStateProvince = postProcessPaymentRequest.Order.ShippingAddress.StateProvince;
                if (deliveryStateProvince != null)
                    remotePostHelper.Add("delivery_cust_state", deliveryStateProvince.Abbreviation);
                else
                    remotePostHelper.Add("delivery_cust_state", "");
                remotePostHelper.Add("delivery_zip_code", postProcessPaymentRequest.Order.ShippingAddress.ZipPostalCode);
                var deliveryCountry = postProcessPaymentRequest.Order.ShippingAddress.Country;
                if (deliveryCountry != null)
                    remotePostHelper.Add("delivery_cust_country", deliveryCountry.ThreeLetterIsoCode);
                else
                    remotePostHelper.Add("delivery_cust_country", "");
            }

          //  remotePostHelper.Add("Merchant_Param", _PayuPaymentSettings.MerchantParam);
            remotePostHelper.Post();
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            RemotePost post = new RemotePost();
            post.FormName = "chinabanksubmit";
            post.Url = "https://pay3.chinabank.com.cn/PayGate";
            post.Method = "POST";

            //��Ҫ�Ľ�����Ϣ
            string v_amount;       // �������
            string v_moneytype;    // ����
            string v_md5info;      // ��ƴ�մ�MD5˽Կ���ܺ��ֵ
            string v_mid;		 // �̻���
            string v_url;		 // ����ҳ��ַ
            string v_oid;		 // �Ƽ������Ź��ɸ�ʽΪ ������-�̻���-Сʱ������
            //�ջ���Ϣ
            string v_rcvname;      // �ջ���
            string v_rcvaddr;      // �ջ���ַ
            string v_rcvtel;       // �ջ��˵绰
            string v_rcvpost;      // �ջ����ʱ�
            string v_rcvemail;     // �ջ����ʼ�
            string v_rcvmobile;    // �ջ����ֻ���
            //��������Ϣ
            string v_ordername;    // ����������
            string v_orderaddr;    // �����˵�ַ
            string v_ordertel;     // �����˵绰
            string v_orderpost;    // �������ʱ�
            string v_orderemail;   // �������ʼ�
            string v_ordermobile;  // �������ֻ���

            //������ע
            string remark1;
            string remark2;

            v_mid = _chinabankPayPaymentSettings.Vmid;
            v_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentChinabank/Notify";
            string key = _chinabankPayPaymentSettings.Key;
            v_oid = postProcessPaymentRequest.Order.Id.ToString();

            if (v_oid == null || v_oid.Equals(""))
            {
                DateTime dt = DateTime.Now;
                string v_ymd = dt.ToString("yyyyMMdd"); // yyyyMMdd
                string timeStr = dt.ToString("HHmmss"); // HHmmss
                v_oid = v_ymd + v_mid + timeStr;
            }

            v_amount = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);
            v_moneytype = "CNY";
            string text = v_amount + v_moneytype + v_oid + v_mid + v_url + key; // ƴ�ռ��ܴ�
            v_md5info = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(text, "md5").ToUpper();

            //�ջ���Ϣ
            v_rcvname = String.Empty;
            v_rcvaddr = postProcessPaymentRequest.Order.BillingAddress.Address1;
            v_rcvtel = postProcessPaymentRequest.Order.BillingAddress.PhoneNumber;
            v_rcvpost = postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode;
            v_rcvemail = postProcessPaymentRequest.Order.BillingAddress.Email;
            v_rcvmobile = postProcessPaymentRequest.Order.BillingAddress.PhoneNumber;
            //��������Ϣ
            v_ordername = String.Empty;
            v_orderaddr = postProcessPaymentRequest.Order.ShippingAddress.Address1;
            v_ordertel = postProcessPaymentRequest.Order.ShippingAddress.PhoneNumber;
            v_orderpost = postProcessPaymentRequest.Order.ShippingAddress.ZipPostalCode;
            v_orderemail = postProcessPaymentRequest.Order.ShippingAddress.Email;
            v_ordermobile = postProcessPaymentRequest.Order.ShippingAddress.PhoneNumber;
            //������Ϣ
            remark1 = "";
            remark2 = "";

            post.Add("v_md5info", v_md5info);
            post.Add("v_mid", v_mid);
            post.Add("v_oid", v_oid);
            post.Add("v_amount", v_amount);
            post.Add("v_moneytype", v_moneytype);
            post.Add("v_url", v_url);
            post.Add("v_rcvname", v_rcvname);
            post.Add("v_rcvaddr", v_rcvaddr);
            post.Add("v_rcvtel", v_rcvtel);
            post.Add("v_rcvpost", v_rcvpost);
            post.Add("v_rcvemail", v_rcvemail);
            post.Add("v_rcvmobile", v_rcvmobile);
            post.Add("v_ordername", v_ordername);
            post.Add("v_orderaddr", v_orderaddr);
            post.Add("v_ordertel", v_ordertel);
            post.Add("v_orderpost", v_orderpost);
            post.Add("v_orderemail", v_orderemail);
            post.Add("v_ordermobile", v_ordermobile);
            post.Add("remark1", remark1);
            post.Add("remark2", remark2);

            post.Post();
        }
Exemplo n.º 9
0
            /// <summary>
            /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
            /// </summary>
            /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
            //public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
            //{

            //    PGResponse objPGResponse = new PGResponse();
            //    CustomerDetails oCustomer = new CustomerDetails();
            //    SessionDetail oSession = new SessionDetail();
            //    AirLineTransaction oAirLine = new AirLineTransaction();
            //    MerchanDise oMerchanDise = new MerchanDise();

            //    SFA.CardInfo objCardInfo = new SFA.CardInfo();

            //    SFA.Merchant objMerchant = new SFA.Merchant();

            //    ShipToAddress objShipToAddress = new ShipToAddress();
            //    BillToAddress oBillToAddress = new BillToAddress();
            //    ShipToAddress oShipToAddress = new ShipToAddress();
            //    MPIData objMPI = new MPIData();
            //    PGReserveData oPGreservData = new PGReserveData();
            //    Address oHomeAddress = new Address();
            //    Address oOfficeAddress = new Address();
            //    // For getting unique MerchantTxnID 
            //    // Only for testing purpose. 
            //    // In actual scenario the merchant has to pass his transactionID
            //    DateTime oldTime = new DateTime(1970, 01, 01, 00, 00, 00);
            //    DateTime currentTime = DateTime.Now;
            //    TimeSpan structTimespan = currentTime - oldTime;
            //    string lMrtTxnID = ((long)structTimespan.TotalMilliseconds).ToString();
            //    var merchantId = _EmiPaymentSettings.MerchantId.ToString();
            //    var orderId = postProcessPaymentRequest.Order.Id;
            //    var Id = orderId.ToString();
            //    var amount = postProcessPaymentRequest.Order.TotalTransactionAmount.ToString(new CultureInfo("en-US", false).NumberFormat);
            //    //Setting Merchant Details
            //    objMerchant.setMerchantDetails(merchantId, "", "", "", lMrtTxnID, Id, "PaymentEmi/Return", "POST", "INR", "INV123", "req.Sale", amount, "GMT+05:30", "ASP.NET64", "true", "ASP.NET64", "ASP.NET64", "ASP.NET64");

            //    // Setting BillToAddress Details
            //    oBillToAddress.setAddressDetails(postProcessPaymentRequest.Order.CustomerId.ToString(),
            //                                      postProcessPaymentRequest.Order.Customer.SystemName,
            //                                      postProcessPaymentRequest.Order.BillingAddress.Address1,
            //                                      postProcessPaymentRequest.Order.BillingAddress.Address2,
            //                                      "",
            //                                      postProcessPaymentRequest.Order.BillingAddress.City,
            //                                      "", postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode,
            //                                      postProcessPaymentRequest.Order.BillingAddress.Country.Name,
            //                                      postProcessPaymentRequest.Order.Customer.Email);

            //    // Setting ShipToAddress Details
            //    oShipToAddress.setAddressDetails(postProcessPaymentRequest.Order.BillingAddress.Address1,
            //                                    postProcessPaymentRequest.Order.BillingAddress.Address2,
            //                                    "",
            //                                    postProcessPaymentRequest.Order.BillingAddress.City,
            //                                    "",
            //                                    postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode,
            //                                    postProcessPaymentRequest.Order.BillingAddress.Country.Name,
            //                                    postProcessPaymentRequest.Order.Customer.Email);

            //    //Setting MPI datails.
            //    //objMPI.setMPIRequestDetails ("1000","INR10.00","356","2","2 shirts","","","","0","","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*","Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");

            //    // Setting Name home/office Address Details 
            //    // Order of Parameters =>        AddLine1, AddLine2,      AddLine3,   City,   State ,  Zip,          Country, Email id
            //    oHomeAddress.setAddressDetails("2Sandeep", "Uttam Corner", "Chinchwad", "Pune", "state", "4385435873", "IND", "*****@*****.**");

            //    // Order of Parameters =>        AddLine1, AddLine2,      AddLine3,   City,   State ,  Zip,          Country, Email id
            //    oOfficeAddress.setAddressDetails("2Opus", "MayFairTowers", "Wakdewadi", "Pune", "state", "4385435873", "IND", "*****@*****.**");

            //    // Stting  Customer Details 
            //    // Order of Parameters =>  First Name,LastName ,Office Address Object,Home Address Object,Mobile No,RegistrationDate, flag for matching bill to address and ship to address 
            //    oCustomer.setCustomerDetails(postProcessPaymentRequest.Order.Customer.SystemName, "", oOfficeAddress, oHomeAddress, "", "13-06-2007", "Y");

            //    //Setting Merchant Dise Details 
            //    // Order of Parameters =>       Item Purchased,Quantity,Brand,ModelNumber,Buyers Name,flag value for matching CardName and BuyerName
            //    oMerchanDise.setMerchanDiseDetails("Computer", "2", "Intel", "P4", "Sandeep Patil", "Y");

            //    //Setting  Session Details        
            //    // Order of Parameters =>     Remote Address, Cookies Value            Browser Country,Browser Local Language,Browser Local Lang Variant,Browser User Agent'
            //    oSession.setSessionDetails(getRemoteAddr(), getSecureCookie(HttpContext.Current.Request), "", HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"], "", HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]);

            //    //Settingr AirLine Transaction Details  
            //    //Order of Parameters =>               Booking Date,FlightDate,Flight   Time,Flight Number,Passenger Name,Number Of Tickets,flag for matching card name and customer name,PNR,sector from,sector to'
            //    oAirLine.setAirLineTransactionDetails("10-06-2007", "22-06-2007", "13:20", "119", "Sandeep", "1", "Y", "25c", "Pune", "Mumbai");

            //    SFAClient objSFAClient = new SFAClient("c:\\inetpub\\wwwroot\\SFAClient\\Config\\");
            //    objPGResponse = objSFAClient.postSSL(objMPI, objMerchant, oBillToAddress, oShipToAddress, oPGreservData, oCustomer, oSession, oAirLine, oMerchanDise);

            //    if (objPGResponse.RedirectionUrl != "" & objPGResponse.RedirectionUrl != null)
            //    {
            //        string strResponseURL = objPGResponse.RedirectionUrl;
            //        HttpContext.Current.Response.Redirect(strResponseURL);
            //    }
            //    else
            //    {
            //        HttpContext.Current.Response.Write("Response Code:" + objPGResponse.RespCode);
            //        HttpContext.Current.Response.Write("Response message:" + objPGResponse.RespMessage);
            //    }

            //}

            public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
            {

                PGResponse objPGResponse = new PGResponse();
                CustomerDetails oCustomer = new CustomerDetails();
                SessionDetail oSession = new SessionDetail();
                AirLineTransaction oAirLine = new AirLineTransaction();
                MerchanDise oMerchanDise = new MerchanDise();

                SFA.CardInfo objCardInfo = new SFA.CardInfo();

                SFA.Merchant objMerchant = new SFA.Merchant();

                ShipToAddress objShipToAddress = new ShipToAddress();
                BillToAddress oBillToAddress = new BillToAddress();
                ShipToAddress oShipToAddress = new ShipToAddress();
                MPIData objMPI = new MPIData();
                PGReserveData oPGreservData = new PGReserveData();
                Address oHomeAddress = new Address();
                Address oOfficeAddress = new Address();
                // For getting unique MerchantTxnID 
                // Only for testing purpose. 
                // In actual scenario the merchant has to pass his transactionID
                DateTime oldTime = new DateTime(1970, 01, 01, 00, 00, 00);
                DateTime currentTime = DateTime.Now;
                TimeSpan structTimespan = currentTime - oldTime;
                string lMrtTxnID = ((long)structTimespan.TotalMilliseconds).ToString();
                var merchantId = _EmiPaymentSettings.MerchantId.ToString();
                var orderId = postProcessPaymentRequest.Order.Id;
                
                var Id = orderId.ToString();
                var amount = postProcessPaymentRequest.Order.TotalTransactionAmount.ToString(new CultureInfo("en-US", false).NumberFormat);
             

                //Setting Merchant Details
                objMerchant.setMerchantDetails(merchantId, "", "", "", lMrtTxnID, Id, "https://www.laorigin.com/PaymentEmi/Return?orderId=" + Id, "POST", "INR", "INV123", "req.Sale", amount, "GMT+05:30", "ASP.NET64", "true", "ASP.NET64", "ASP.NET64", "ASP.NET64");

                // Setting BillToAddress Details
                   oBillToAddress.setAddressDetails(postProcessPaymentRequest.Order.CustomerId.ToString(),
                                                      postProcessPaymentRequest.Order.Customer.SystemName,
                                                   postProcessPaymentRequest.Order.BillingAddress.Address1,
                                                    postProcessPaymentRequest.Order.BillingAddress.Address2,
                                                    "",
                                                     postProcessPaymentRequest.Order.BillingAddress.City,
                                                    postProcessPaymentRequest.Order.BillingAddress.StateProvince.Name
                                                    , postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode,
                                                    postProcessPaymentRequest.Order.BillingAddress.Country.Name,
                                                     postProcessPaymentRequest.Order.Customer.Email);

                   // Setting ShipToAddress Details
                   oShipToAddress.setAddressDetails(postProcessPaymentRequest.Order.BillingAddress.Address1,
                                                   postProcessPaymentRequest.Order.BillingAddress.Address2,
                                                   "",
                                                   postProcessPaymentRequest.Order.BillingAddress.City,
                                                   postProcessPaymentRequest.Order.BillingAddress.StateProvince.Name,
                                                 
                                                   postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode,
                                                   postProcessPaymentRequest.Order.BillingAddress.Country.Name,
                                                   postProcessPaymentRequest.Order.Customer.Email);

                   //Setting MPI datails.
                   //objMPI.setMPIRequestDetails ("1000","INR10.00","356","2","2 shirts","","","","0","","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, application/x-shockwave-flash, */*","Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)");

                   // Setting Name home/office Address Details 
                   // Order of Parameters =>        AddLine1, AddLine2,      AddLine3,   City,   State ,  Zip,          Country, Email id
                   oHomeAddress.setAddressDetails("2Sandeep", "Uttam Corner", "Chinchwad", "Pune", "state", "4385435873", "IND", "*****@*****.**");

                   // Order of Parameters =>        AddLine1, AddLine2,      AddLine3,   City,   State ,  Zip,          Country, Email id
                   oOfficeAddress.setAddressDetails("2Opus", "MayFairTowers", "Wakdewadi", "Pune", "state", "4385435873", "IND", "*****@*****.**");

                   // Stting  Customer Details 
                   // Order of Parameters =>  First Name,LastName ,Office Address Object,Home Address Object,Mobile No,RegistrationDate, flag for matching bill to address and ship to address 
                   oCustomer.setCustomerDetails(postProcessPaymentRequest.Order.Customer.SystemName, "", oOfficeAddress, oHomeAddress, "", "13-06-2007", "Y");

                   //Setting Merchant Dise Details 
                   // Order of Parameters =>       Item Purchased,Quantity,Brand,ModelNumber,Buyers Name,flag value for matching CardName and BuyerName
                   oMerchanDise.setMerchanDiseDetails("Computer", "2", "Intel", "P4", "Sandeep Patil", "Y");

                //Setting  Session Details        
                // Order of Parameters =>     Remote Address, Cookies Value            Browser Country,Browser Local Language,Browser Local Lang Variant,Browser User Agent'
                oSession.setSessionDetails(getRemoteAddr(), getSecureCookie(HttpContext.Current.Request), "", HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"], "", HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"]);

                //Settingr AirLine Transaction Details  
                //Order of Parameters =>               Booking Date,FlightDate,Flight   Time,Flight Number,Passenger Name,Number Of Tickets,flag for matching card name and customer name,PNR,sector from,sector to'
                oAirLine.setAirLineTransactionDetails("10-06-2007", "22-06-2007", "13:20", "119", "Sandeep", "1", "Y", "25c", "Pune", "Mumbai");

                SFAClient objSFAClient = new SFAClient("c:\\inetpub\\wwwroot\\SFAClient\\Config\\");
                objPGResponse = objSFAClient.postSSL(objMPI, objMerchant, oBillToAddress, oShipToAddress, oPGreservData, oCustomer, oSession, oAirLine, oMerchanDise);

                if (objPGResponse.RedirectionUrl != "" & objPGResponse.RedirectionUrl != null)
                {
                    string strResponseURL = objPGResponse.RedirectionUrl;
                    HttpContext.Current.Response.Redirect(strResponseURL);
                }
                else
                {
                    HttpContext.Current.Response.Write("Response Code:" + objPGResponse.RespCode);
                    HttpContext.Current.Response.Write("Response message:" + objPGResponse.RespMessage);
                }

            }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            bool isSecure = _webHelper.IsCurrentConnectionSecured();
            string redirectUrl = _webHelper.GetStoreLocation(isSecure).Trim() + "ppa/payment/" + postProcessPaymentRequest.Order.Id;

            // Check license
            bool isLicensed = this._licenseService.IsLicensed(HttpContext.Current.Request.Url.Host);            
            if (!isLicensed && postProcessPaymentRequest.Order.OrderTotal > 5.00M)
            {
                redirectUrl = _webHelper.GetStoreLocation(isSecure).Trim() + "ppa/license";
            }
                        
            _httpContext.Response.Redirect(redirectUrl);
        }                
Exemplo n.º 11
0
        public ActionResult GetPaymentLink(int orderId)
        {
            var order = _orderService.GetOrderById(orderId);

            var postProcessPaymentRequest = new PostProcessPaymentRequest()
            {
                Order = order
            };
            _paymentService.PostProcessPayment(postProcessPaymentRequest);

            if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
            {
                //redirection or POST has been done in PostProcessPayment
                return Content("Redirected");
            }
            else
            {
                //if no redirection has been done (to a third-party payment page)
                //theoretically it's not possible
                return Redirect("~/");
            }
        }
Exemplo n.º 12
0
        public ActionResult ConfirmOrder()
        {
            var deliveryDate = TempData["deliveryDate"];
            var pickupDate = TempData["pickupDate"];
            var pickupLocation = TempData["pickupLocation"];
            var customerNote = TempData["customerNote"];

            if (!string.IsNullOrEmpty(deliveryDate.ToString()))
            {
                DateTime dtDeliveryDate = Convert.ToDateTime(deliveryDate);
                //If Hour is not 0 then error and return to select shipping method
                if (dtDeliveryDate.Hour > 0)
                {
                    return RedirectToRoute(new
                    {
                        controller = "Checkout",
                        action = "ShippingMethod"
                    });
                }

                //DateTime dtDeliveryDate = Convert.ToDateTime(deliveryDate);
                DateTime dtNow = DateTime.Now;
                if (dtDeliveryDate.Year == dtNow.Year && dtDeliveryDate.Month == dtNow.Month && dtDeliveryDate.Day == dtNow.Day)
                {
                    return RedirectToRoute(new
                    {
                        controller = "Checkout",
                        action = "ShippingMethod"
                    });
                }

                //If Hour is not 0 then error and return to select shipping method
                if (dtDeliveryDate.Hour > 0 || dtDeliveryDate.Minute > 0 || dtDeliveryDate.Second > 0)
                {
                    return RedirectToRoute(new
                    {
                        controller = "Checkout",
                        action = "ShippingMethod"
                    });
                }
            }
            if (customerNote == null)
                customerNote = "";
            var gcCount = _workContext.CurrentCustomer.ShoppingCartItems
                    .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart && sci.Product.AdminComment == "Gift Card")
                    .LimitPerStore(_storeContext.CurrentStore.Id)
                    .Count();

            IList<ShoppingCartItem> cart = new List<ShoppingCartItem>();

            if (gcCount != 0)
            {
                cart = _workContext.CurrentCustomer.ShoppingCartItems
                   .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart && sci.Product.AdminComment == "Gift Card")
                   .LimitPerStore(_storeContext.CurrentStore.Id)
                   .ToList();
            }
            else
            {
                cart = _workContext.CurrentCustomer.ShoppingCartItems
                        .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                        .LimitPerStore(_storeContext.CurrentStore.Id)
                        .ToList();
            }

            //validation
            //var cart = _workContext.CurrentCustomer.ShoppingCartItems
            //    .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
            //    .LimitPerStore(_storeContext.CurrentStore.Id)
            //    .ToList();

            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if (_orderSettings.OnePageCheckoutEnabled)
                return RedirectToRoute("CheckoutOnePage");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            //model
            var model = PrepareConfirmOrderModel(cart);
            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                        return RedirectToRoute("CheckoutPaymentInfo");

                    processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
                processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
                    SystemCustomerAttributeNames.SelectedPaymentMethod,
                    _genericAttributeService, _storeContext.CurrentStore.Id);

                if (deliveryDate == null)
                { processPaymentRequest.EstimateDeliveryDate = DateTime.UtcNow; }
                else
                { processPaymentRequest.EstimateDeliveryDate = Convert.ToDateTime(deliveryDate); }
                processPaymentRequest.CustomerNote = customerNote.ToString();
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest
                    {
                        Order = placeOrderResult.PlacedOrder
                    };
                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                    {
                        //redirection or POST has been done in PostProcessPayment
                        return Content("Redirected");
                    }

                    //if (deliveryDate == null)
                    //    deliveryDate = DateTime.Today.ToLongDateString();

                    var shippingOptions = _workContext.CurrentCustomer.GetAttribute<List<ShippingOption>>(SystemCustomerAttributeNames.OfferedShippingOptions, _storeContext.CurrentStore.Id);

                    //handle selected pickup date and location
                    if (pickupDate != null && pickupDate != "")
                    {
                        DateTime pickup = Convert.ToDateTime(pickupDate);
                        _shippingService.SetPickupDateAndLocation(placeOrderResult.PlacedOrder.Id, pickup,
                            Convert.ToInt32(pickupLocation));
                    }

                    ////handle selected delivery date
                    //if (deliveryDate != null && deliveryDate != "")
                    //{
                    //    DateTime delivery = Convert.ToDateTime(deliveryDate);
                    //    _shippingService.SetDeliveryDate(placeOrderResult.PlacedOrder.Id, delivery);
                    //}

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

                foreach (var error in placeOrderResult.Errors)
                    model.Warnings.Add(error);
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var customer = _customerService.GetCustomerById(postProcessPaymentRequest.Order.CustomerId);
            var post = new RemotePost();

            var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;


            post.FormName = "YandexKassaPaymentForm";
            post.Url = GetYandexKassaUrl();
            post.Method = "POST";

            post.Add("shopId", _yandexKassaSettings.ShopId.ToString());
            post.Add("scid", _yandexKassaSettings.Scid.ToString());
            post.Add("sum", String.Format(CultureInfo.InvariantCulture, "{0:0.00}", postProcessPaymentRequest.Order.OrderTotal));
            post.Add("customerNumber", postProcessPaymentRequest.Order.BillingAddress.Email);
            post.Add("orderNumber", postProcessPaymentRequest.Order.Id.ToString());
            post.Add("shopSuccessURL", String.Format("{0}Plugins/PaymentYandexKassa/Return", _webHelper.GetStoreLocation(false)));
            post.Add("shopFailURL", String.Format("{0}Plugins/PaymentYandexKassa/Return", _webHelper.GetStoreLocation(false)) );
            post.Add("cps_email", customer.Email);
            post.Add("cps_phone", customer.BillingAddress.PhoneNumber);
            post.Add("paymentType", postProcessPaymentRequest.Order.SubscriptionTransactionId);
            post.Add("custName", postProcessPaymentRequest.Order.BillingAddress.LastName + postProcessPaymentRequest.Order.BillingAddress.FirstName);
            post.Add("custAddr", customer.BillingAddress.Address1);
            post.Add("custEMail", postProcessPaymentRequest.Order.BillingAddress.Email);
            post.Add("orderDetails", "without");

            post.Post();

        }
Exemplo n.º 14
0
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var builder = new StringBuilder();
            string merchant = _robokassaSettings.Login;
            string merchantpass = _robokassaSettings.Password1;
            string desc = _robokassaSettings.PaymentDescription;
            string signature = String.Format("{0}:{1}:{2}:{3}", merchant, postProcessPaymentRequest.Order.OrderTotal.ToString().Replace(",","."), postProcessPaymentRequest.Order.Id, merchantpass);
            string currency = "rub";
            string culture = "ru";

            builder.Append(_robokassaSettings.ApiURL);
            builder.AppendFormat("?MrchLogin={0}", merchant);
            builder.AppendFormat("&OutSum={0}", postProcessPaymentRequest.Order.OrderTotal.ToString().Replace(",", "."));
            builder.AppendFormat("&InvId={0}", postProcessPaymentRequest.Order.Id);
            builder.AppendFormat("&Desc={0}", HttpUtility.UrlEncode(desc));
            builder.AppendFormat("&SignatureValue={0}", MD5Helper.GetMD5Hash(signature));
            builder.AppendFormat("&sIncCurrLabel={0}", currency);
            builder.AppendFormat("&Email={0}", postProcessPaymentRequest.Order.BillingAddress.Email);
            builder.AppendFormat("&sCulture={0}", culture);

            _httpContext.Response.Redirect(builder.ToString());
        }
		//Customization Propeers info (changed by ravi)
		public ActionResult OpcCompleteRedirectionPayment1()
		{
			try
			{

				var Orginalcart = _workContext.CurrentCustomer.ShoppingCartItems
			 .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
			 .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
			 .ToList();



				if (Orginalcart.Count == 0)
					throw new Exception("Your cart is empty");



				//place order
				var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
				if (processPaymentRequest == null)
				{
					//Check whether payment workflow is required
					if (IsPaymentWorkflowRequired(Orginalcart))
					{
						throw new Exception("Payment information is not entered");
					}
					else
						processPaymentRequest = new ProcessPaymentRequest();
				}




				processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
				processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;

				processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
					 SystemCustomerAttributeNames.SelectedPaymentMethod,
					 _genericAttributeService, _storeContext.CurrentStore.Id);

				TempOrder tempOrderObj = new TempOrder();
				tempOrderObj.TempOrderGuid = Guid.NewGuid();
				this.Session["orderGuid"] = tempOrderObj.TempOrderGuid;
				_tempOrderService.InsertTempOrder(tempOrderObj);
				this.Session["orderobj"] = processPaymentRequest;
				var placeOrderResult = _payPalOrderProcessingService.PaypalOrderDetails(processPaymentRequest);
				TempData["OrderCancelValue"] = 1;


				//_shoppingCartService.AddToCart(, )





				var customer = _workContext.CurrentCustomer;
				var paymentMethodSystemName = processPaymentRequest.PaymentMethodSystemName;/*customer.GetAttribute<string>(
                   SystemCustomerAttributeNames.SelectedPaymentMethod,
                   _genericAttributeService, _storeContext.CurrentStore.Id);   */

				var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(paymentMethodSystemName);
				Guid ogid = processPaymentRequest.OrderGuid;


				//int oid = processPaymentRequest.InitialOrderId;


				//Order odObject = _orderService.GetOrderByGuid(ogid);

				IList<ShoppingCartItem> cart = null;
				cart = Orginalcart.ToList();

				/*cart = _workContext.CurrentCustomer.ShoppingCartItems
						 .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
						 .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
						 .ToList();        */



				/*  var postProcessPaymentRequest = new PostProcessPaymentRequest()
				  {
						Order = odObject//new Order { PaymentStatus = PaymentStatus.Pending, PaymentMethodSystemName = paymentMethodSystemName }
				  };     */

				var postProcessPaymentRequest = new PostProcessPaymentRequest();
				Order or = new Order();
				or = placeOrderResult.PlacedOrder;
				or.PaymentMethodSystemName = paymentMethodSystemName;
				or.PaymentStatus = PaymentStatus.Pending;
				or.OrderDiscount = placeOrderResult.PlacedOrder.OrderDiscount;
				or.OrderGuid = tempOrderObj.TempOrderGuid;
				or.Id = _tempOrderService.GetTempOrderByGuid(tempOrderObj.TempOrderGuid).Id;
				postProcessPaymentRequest.Order = or;
				//postProcessPaymentRequest.Cart = Orginalcart;
				// _orderProcessingService.ReOrder(or);




				_paymentService.PostProcessPayment(postProcessPaymentRequest);

				if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
				{
					//redirection or POST has been done in PostProcessPayment
					return Content("Redirected");
				}
				else
				{
					//if no redirection has been done (to a third-party payment page)
					//theoretically it's not possible
					return RedirectToRoute("CheckoutCompleted", new { orderId = 2 });
				}
			}
			catch (Exception exc)
			{
				_logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
				return Content(exc.Message);
			}
		}
Exemplo n.º 16
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //string gateway = "https://www.alipay.com/cooperate/gateway.do?";
            string service = "create_direct_pay_by_user";

            string seller_email = _aliPayPaymentSettings.SellerEmail;
            string sign_type = "MD5";
            string key = _aliPayPaymentSettings.Key;
            string partner = _aliPayPaymentSettings.Partner;

            string input_charset = "utf-8";

            string show_url = "http://www.alipay.com/";

            string out_trade_no = postProcessPaymentRequest.Order.Id.ToString();
            string subject = _storeContext.CurrentStore.Name;
            string body = "Order from " + _storeContext.CurrentStore.Name;
            string total_fee = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);

            string notify_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Notify";
            string return_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAliPay/Return";
            string[] para ={
                               "service="+service,
                               "partner=" + partner,
                               "seller_email=" + seller_email,
                               "out_trade_no=" + out_trade_no,
                               "subject=" + subject,
                               "body=" + body,
                               "total_fee=" + total_fee,
                               "show_url=" + show_url,
                               "payment_type=1",
                               "notify_url=" + notify_url,
                               "return_url=" + return_url,
                               "_input_charset=" + input_charset
                           };

            string aliay_url = CreatUrl(
                para,
                input_charset,
                key
                );
            var post = new RemotePost();
            post.FormName = "alipaysubmit";
            post.Url = "https://www.alipay.com/cooperate/gateway.do?_input_charset=utf-8";
            post.Method = "POST";

            post.Add("service", service);
            post.Add("partner", partner);
            post.Add("seller_email", seller_email);
            post.Add("out_trade_no", out_trade_no);
            post.Add("subject", subject);
            post.Add("body", body);
            post.Add("total_fee", total_fee);
            post.Add("show_url", show_url);
            post.Add("return_url", return_url);
            post.Add("notify_url", notify_url);
            post.Add("payment_type", "1");
            post.Add("sign", aliay_url);
            post.Add("sign_type", sign_type);

            post.Post();
        }
Exemplo n.º 17
0
        public ActionResult RePostPayment(int orderId)
        {
            var order = _orderService.GetOrderById(orderId);
            if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
                return new HttpUnauthorizedResult();

            if (!_paymentService.CanRePostProcessPayment(order))
                return RedirectToRoute("OrderDetails", new { orderId = orderId });

            var postProcessPaymentRequest = new PostProcessPaymentRequest()
            {
                Order = order
            };
            _paymentService.PostProcessPayment(postProcessPaymentRequest);
            return RedirectToRoute("OrderDetails", new {orderId = orderId});
        }
 /// <summary>
 /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
 /// </summary>
 /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
 public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
     //nothing
 }
Exemplo n.º 19
0
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //֧������֧������ʾ��
            //�̻������ţ��˴���ϵͳʱ���3λ�������Ϊ�����ţ��̻�Ӧ�����Լ����������ȷ���ö��������̻�ϵͳ�е�ȫ��Ψһ
            string num = DateTime.Now.ToString("yyyyMMddHHmmss") + new Random().Next(999);
            string out_trade_no = postProcessPaymentRequest.Order.Id.ToString(); //���Dz��������������������
            //֧�����
            string total_fee = postProcessPaymentRequest.Order.OrderTotal.ToString("0.00", CultureInfo.InvariantCulture);
            //���Ҵ��룬����ң�RMB���۱ң�HKD����Ԫ��USD ����������յ�ҵ����Ҫ��ҵ����Ա��ϵ��ͨ��
            string currency_type = "RMB";
            //���������Ŀͻ���IP�������ߵ��Թ���IP��
            //string order_create_ip = Request.UserHostAddress;  //���������Ŀͻ���IP�������ߵ��Թ���IP�����ڷ�����֧����
            //string order_create_ip = "";
            //ǩ������
            string sign_type = "SHA256";
            //������ɺ���ת��URL�������������ص�ҳ��ת����ʱ֪ͨ���
            string return_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAjPay/Return";
            string notify_url = _webHelper.GetStoreLocation(false) + "Plugins/PaymentAjPay/Notify";
            ////ֱ�����в�������μ��ĵ���
            //string pay_id = "gonghang";
            //������ע������Ϣʹ��64λ�����ύ��������������֧����ɺ���֧�����ԭ������
            var sbItemName = new StringBuilder();
            foreach (var orderItem in postProcessPaymentRequest.Order.OrderItems)
            {
                sbItemName.Append(orderItem.Product.Name + " ");
            }

            string memo = sbItemName.ToString();
            string store_oi_type = "0";
            byte[] bytes = System.Text.Encoding.Default.GetBytes(memo);
            string base64_memo = Convert.ToBase64String(bytes);
            //=======================�����������===========================

            string key = "h0iy0osxkkaplpxkpscc52x7o2dr0597";
            string partner = "TEST";

            IList<string> paraList = new List<string>();

            paraList.Add("out_trade_no=" + out_trade_no);
            paraList.Add("total_fee=" + total_fee);
            paraList.Add("return_url=" + return_url);
            paraList.Add("currency_type=" + currency_type);
            //paraList.Add("order_create_ip=" + order_create_ip);
            paraList.Add("sign_type=" + sign_type);

            //��ѡ����
            //paraList.Add("pay_id=" + pay_id);	        		//ֱ�����в�����������ֱ��ת������������ʱ�IJ���
            paraList.Add("base64_memo=" + base64_memo);		//������ע��BASE64����
            paraList.Add("store_oi_type=" + store_oi_type);		//������ע��BASE64����

            paraList.Add("partner=" + partner);

            string aandj_url = CreatUrl(
                paraList.ToArray(),
                key
                );
            var post = new RemotePost();
            post.FormName = "aandjsubmit";
            post.Url = "http://testgateway.ajmcl.com/paygateway/payment";
            post.Method = "GET";

            post.Add("out_trade_no", out_trade_no);
            post.Add("total_fee", total_fee);
            post.Add("return_url", return_url);
            post.Add("currency_type", currency_type);
            //post.Add("order_create_ip", order_create_ip);
            post.Add("sign_type", sign_type);

            //��ѡ����
            //post.Add("pay_id", pay_id);	        		//ֱ�����в�����������ֱ��ת������������ʱ�IJ���
            post.Add("base64_memo", base64_memo);		//������ע��BASE64����
            post.Add("store_oi_type", store_oi_type);		//������ע��BASE64����

            post.Add("partner" , partner);

            post.Add("sign", aandj_url);

            post.Post();
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            var builder = new StringBuilder();
            builder.Append(GetPaypalUrl());
            var cmd =_paypalStandardPaymentSettings.PassProductNamesAndTotals
                ? "_cart"
                :  "_xclick";
            builder.AppendFormat("?cmd={0}&business={1}", cmd, HttpUtility.UrlEncode(_paypalStandardPaymentSettings.BusinessEmail));
            if (_paypalStandardPaymentSettings.PassProductNamesAndTotals)
            {
                builder.AppendFormat("&upload=1");

                //get the items in the cart
                decimal cartTotal = decimal.Zero;
                var cartItems = postProcessPaymentRequest.Order.OrderItems;
                int x = 1;
                foreach (var item in cartItems)
                {
                    var unitPriceExclTax = item.UnitPriceExclTax;
                    var priceExclTax = item.PriceExclTax;
                    //round
                    var unitPriceExclTaxRounded = Math.Round(unitPriceExclTax, 2);
                    builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(item.Product.Name));
                    builder.AppendFormat("&amount_" + x + "={0}", unitPriceExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", item.Quantity);
                    x++;
                    cartTotal += priceExclTax;
                }

                //the checkout attributes that have a dollar value and send them to Paypal as items to be paid for
                var attributeValues = _checkoutAttributeParser.ParseCheckoutAttributeValues(postProcessPaymentRequest.Order.CheckoutAttributesXml);
                foreach (var val in attributeValues)
                {
                    var attPrice = _taxService.GetCheckoutAttributePrice(val, false, postProcessPaymentRequest.Order.Customer);
                    //round
                    var attPriceRounded = Math.Round(attPrice, 2);
                    if (attPrice > decimal.Zero) //if it has a price
                    {
                        var attribute = val.CheckoutAttribute;
                        if (attribute != null)
                        {
                            var attName = attribute.Name; //set the name
                            builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode(attName)); //name
                            builder.AppendFormat("&amount_" + x + "={0}", attPriceRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                            builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity
                            x++;
                            cartTotal += attPrice;
                        }
                    }
                }

                //order totals

                //shipping
                var orderShippingExclTax = postProcessPaymentRequest.Order.OrderShippingExclTax;
                var orderShippingExclTaxRounded = Math.Round(orderShippingExclTax, 2);
                if (orderShippingExclTax > decimal.Zero)
                {
                    builder.AppendFormat("&item_name_" + x + "={0}", "Shipping fee");
                    builder.AppendFormat("&amount_" + x + "={0}", orderShippingExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", 1);
                    x++;
                    cartTotal += orderShippingExclTax;
                }

                //payment method additional fee
                var paymentMethodAdditionalFeeExclTax = postProcessPaymentRequest.Order.PaymentMethodAdditionalFeeExclTax;
                var paymentMethodAdditionalFeeExclTaxRounded = Math.Round(paymentMethodAdditionalFeeExclTax, 2);
                if (paymentMethodAdditionalFeeExclTax > decimal.Zero)
                {
                    builder.AppendFormat("&item_name_" + x + "={0}", "Payment method fee");
                    builder.AppendFormat("&amount_" + x + "={0}", paymentMethodAdditionalFeeExclTaxRounded.ToString("0.00", CultureInfo.InvariantCulture));
                    builder.AppendFormat("&quantity_" + x + "={0}", 1);
                    x++;
                    cartTotal += paymentMethodAdditionalFeeExclTax;
                }

                //tax
                var orderTax = postProcessPaymentRequest.Order.OrderTax;
                var orderTaxRounded = Math.Round(orderTax, 2);
                if (orderTax > decimal.Zero)
                {
                    //builder.AppendFormat("&tax_1={0}", orderTax.ToString("0.00", CultureInfo.InvariantCulture));

                    //add tax as item
                    builder.AppendFormat("&item_name_" + x + "={0}", HttpUtility.UrlEncode("Sales Tax")); //name
                    builder.AppendFormat("&amount_" + x + "={0}", orderTaxRounded.ToString("0.00", CultureInfo.InvariantCulture)); //amount
                    builder.AppendFormat("&quantity_" + x + "={0}", 1); //quantity

                    cartTotal += orderTax;
                    x++;
                }

                if (cartTotal > postProcessPaymentRequest.Order.OrderTotal)
                {
                    /* Take the difference between what the order total is and what it should be and use that as the "discount".
                     * The difference equals the amount of the gift card and/or reward points used.
                     */
                    decimal discountTotal = cartTotal - postProcessPaymentRequest.Order.OrderTotal;
                    discountTotal = Math.Round(discountTotal, 2);
                    //gift card or rewared point amount applied to cart in nopCommerce - shows in Paypal as "discount"
                    builder.AppendFormat("&discount_amount_cart={0}", discountTotal.ToString("0.00", CultureInfo.InvariantCulture));
                }
            }
            else
            {
                //pass order total
                builder.AppendFormat("&item_name=Order Number {0}", postProcessPaymentRequest.Order.Id);
                var orderTotal = Math.Round(postProcessPaymentRequest.Order.OrderTotal, 2);
                builder.AppendFormat("&amount={0}", orderTotal.ToString("0.00", CultureInfo.InvariantCulture));
            }

            builder.AppendFormat("&custom={0}", postProcessPaymentRequest.Order.OrderGuid);
            builder.AppendFormat("&charset={0}", "utf-8");
            builder.Append(string.Format("&no_note=1&currency_code={0}", HttpUtility.UrlEncode(_currencyService.GetCurrencyById(_currencySettings.PrimaryStoreCurrencyId).CurrencyCode)));
            builder.AppendFormat("&invoice={0}", postProcessPaymentRequest.Order.Id);
            builder.AppendFormat("&rm=2", new object[0]);
            if (postProcessPaymentRequest.Order.ShippingStatus != ShippingStatus.ShippingNotRequired)
                builder.AppendFormat("&no_shipping=2", new object[0]);
            else
                builder.AppendFormat("&no_shipping=1", new object[0]);

            string returnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/PDTHandler";
            string cancelReturnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/CancelOrder";
            builder.AppendFormat("&return={0}&cancel_return={1}", HttpUtility.UrlEncode(returnUrl), HttpUtility.UrlEncode(cancelReturnUrl));

            //Instant Payment Notification (server to server message)
            if (_paypalStandardPaymentSettings.EnableIpn)
            {
                string ipnUrl;
                if (String.IsNullOrWhiteSpace(_paypalStandardPaymentSettings.IpnUrl))
                    ipnUrl = _webHelper.GetStoreLocation(false) + "Plugins/PaymentPayPalStandard/IPNHandler";
                else
                    ipnUrl = _paypalStandardPaymentSettings.IpnUrl;
                builder.AppendFormat("&notify_url={0}", ipnUrl);
            }

            //address
            builder.AppendFormat("&address_override={0}", _paypalStandardPaymentSettings.AddressOverride ? "1" : "0");
            builder.AppendFormat("&first_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.FirstName));
            builder.AppendFormat("&last_name={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.LastName));
            builder.AppendFormat("&address1={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address1));
            builder.AppendFormat("&address2={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Address2));
            builder.AppendFormat("&city={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.City));
            //if (!String.IsNullOrEmpty(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber))
            //{
            //    //strip out all non-digit characters from phone number;
            //    string billingPhoneNumber = System.Text.RegularExpressions.Regex.Replace(postProcessPaymentRequest.Order.BillingAddress.PhoneNumber, @"\D", string.Empty);
            //    if (billingPhoneNumber.Length >= 10)
            //    {
            //        builder.AppendFormat("&night_phone_a={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(0, 3)));
            //        builder.AppendFormat("&night_phone_b={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(3, 3)));
            //        builder.AppendFormat("&night_phone_c={0}", HttpUtility.UrlEncode(billingPhoneNumber.Substring(6, 4)));
            //    }
            //}
            if (postProcessPaymentRequest.Order.BillingAddress.StateProvince != null)
                builder.AppendFormat("&state={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.StateProvince.Abbreviation));
            else
                builder.AppendFormat("&state={0}", "");
            if (postProcessPaymentRequest.Order.BillingAddress.Country != null)
                builder.AppendFormat("&country={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Country.TwoLetterIsoCode));
            else
                builder.AppendFormat("&country={0}", "");
            builder.AppendFormat("&zip={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.ZipPostalCode));
            builder.AppendFormat("&email={0}", HttpUtility.UrlEncode(postProcessPaymentRequest.Order.BillingAddress.Email));
            _httpContext.Response.Redirect(builder.ToString());
        }
Exemplo n.º 21
0
 /// <summary>
 /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
 /// </summary>
 /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
 public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
 {
 }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public virtual void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
            //already paid or order.OrderTotal == decimal.Zero
            if (postProcessPaymentRequest.Order.PaymentStatus == PaymentStatus.Paid)
                return;

            var paymentMethod = LoadPaymentMethodBySystemName(postProcessPaymentRequest.Order.PaymentMethodSystemName);
            if (paymentMethod == null)
                throw new NopException("Payment method couldn't be loaded");
            paymentMethod.PostProcessPayment(postProcessPaymentRequest);
        }
        public ActionResult RePostPayment(int orderId)
        {
            var order = _orderService.GetOrderById(orderId);
            if (order == null || order.Deleted || _workContext.CurrentCustomer.Id != order.CustomerId)
                return new HttpUnauthorizedResult();

            if (!_paymentService.CanRePostProcessPayment(order))
                return RedirectToRoute("OrderDetails", new { orderId = orderId });

            var postProcessPaymentRequest = new PostProcessPaymentRequest()
            {
                Order = order
            };
            _paymentService.PostProcessPayment(postProcessPaymentRequest);

            if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
            {
                //redirection or POST has been done in PostProcessPayment
                return Content("Redirected");
            }
            else
            {
                //if no redirection has been done (to a third-party payment page)
                //theoretically it's not possible
                return RedirectToRoute("OrderDetails", new { orderId = orderId });
            }
        }
Exemplo n.º 24
0
        public ActionResult OpcCompleteRedirectionPayment()
        {
            try
            {
                //validation
                if (!UseOnePageCheckout())
                    return RedirectToRoute("HomePage");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    return new HttpUnauthorizedResult();

                //get the order
                var order = _orderService.SearchOrders(_storeContext.CurrentStore.Id, 0, _workContext.CurrentCustomer.Id,
                    null, null, null, null, null, null, null, 0, 1)
                    .FirstOrDefault();
                if (order == null)
                    return RedirectToRoute("HomePage");

                var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
                if (paymentMethod == null)
                    return RedirectToRoute("HomePage");
                if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection)
                    return RedirectToRoute("HomePage");

                //ensure that order has been just placed
                if ((DateTime.UtcNow - order.CreatedOnUtc).TotalMinutes > 3)
                    return RedirectToRoute("HomePage");

                //Redirection will not work on one page checkout page because it's AJAX request.
                //That's why we process it here
                var postProcessPaymentRequest = new PostProcessPaymentRequest()
                {
                    Order = order
                };

                _paymentService.PostProcessPayment(postProcessPaymentRequest);

                if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                {
                    //redirection or POST has been done in PostProcessPayment
                    return Content("Redirected");
                }
                else
                {
                    //if no redirection has been done (to a third-party payment page)
                    //theoretically it's not possible
                    return RedirectToRoute("CheckoutCompleted", new { orderId = order.Id });
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Content(exc.Message);
            }
        }
Exemplo n.º 25
0
        public ActionResult OpcConfirmOrder()
        {
            try
            {
                //validation
                var cart = _workContext.CurrentCustomer.ShoppingCartItems
                    .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                    .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
                    .ToList();
                if (cart.Count == 0)
                    throw new Exception("Your cart is empty");

                if (!UseOnePageCheckout())
                    throw new Exception("One page checkout is disabled");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    throw new Exception("Anonymous checkout is not allowed");

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        throw new Exception("Payment information is not entered");
                    }
                    else
                        processPaymentRequest = new ProcessPaymentRequest();
                }

                processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
                    SystemCustomerAttributeNames.SelectedPaymentMethod,
                    _genericAttributeService, _storeContext.CurrentStore.Id);
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = placeOrderResult.PlacedOrder
                    };

                    var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(placeOrderResult.PlacedOrder.PaymentMethodSystemName);
                    if (paymentMethod != null)
                    {
                        if (paymentMethod.PaymentMethodType == PaymentMethodType.Redirection)
                        {
                            //Redirection will not work because it's AJAX request.
                            //That's why we don't process it here (we redirect a user to another page where he'll be redirected)

                            //redirect
                            return Json(new { redirect = string.Format("{0}checkout/OpcCompleteRedirectionPayment", _webHelper.GetStoreLocation()) });
                        }
                        else
                        {
                            _paymentService.PostProcessPayment(postProcessPaymentRequest);
                            //success
                            return Json(new { success = 1 });
                        }
                    }
                    else
                    {
                        //payment method could be null if order total is 0

                        //success
                        return Json(new { success = 1 });
                    }
                }
                else
                {
                    //error
                    var confirmOrderModel = new CheckoutConfirmModel();
                    foreach (var error in placeOrderResult.Errors)
                        confirmOrderModel.Warnings.Add(error);

                    return Json(new
                        {
                            update_section = new UpdateSectionJsonModel()
                            {
                                name = "confirm-order",
                                html = this.RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
                            },
                            goto_section = "confirm_order"
                        });
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Json(new { error = 1, message = exc.Message });
            }
        }
Exemplo n.º 26
0
        public ActionResult ConfirmOrder()
        {
            //validation
            var cart = _workContext.CurrentCustomer.ShoppingCartItems
                .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                .Where(sci => sci.StoreId == _storeContext.CurrentStore.Id)
                .ToList();
            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if (UseOnePageCheckout())
                return RedirectToRoute("CheckoutOnePage");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            //model
            var model = new CheckoutConfirmModel();
            try
            {
                var processPaymentRequest = _httpContext.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                        return RedirectToRoute("CheckoutPaymentInfo");
                    else
                        processPaymentRequest = new ProcessPaymentRequest();
                }

                //prevent 2 orders being placed within an X seconds time frame
                if (!IsMinimumOrderPlacementIntervalValid(_workContext.CurrentCustomer))
                    throw new Exception(_localizationService.GetResource("Checkout.MinOrderPlacementInterval"));

                //place order
                processPaymentRequest.StoreId = _storeContext.CurrentStore.Id;
                processPaymentRequest.CustomerId = _workContext.CurrentCustomer.Id;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.GetAttribute<string>(
                    SystemCustomerAttributeNames.SelectedPaymentMethod,
                    _genericAttributeService, _storeContext.CurrentStore.Id);
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    _httpContext.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = placeOrderResult.PlacedOrder
                    };
                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    if (_webHelper.IsRequestBeingRedirected || _webHelper.IsPostBeingDone)
                    {
                        //redirection or POST has been done in PostProcessPayment
                        return Content("Redirected");
                    }
                    else
                    {
                        return RedirectToRoute("CheckoutCompleted", new { orderId = placeOrderResult.PlacedOrder.Id });
                    }
                }
                else
                {
                    foreach (var error in placeOrderResult.Errors)
                        model.Warnings.Add(error);
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
Exemplo n.º 27
0
        public ActionResult OpcConfirmOrder()
        {
            try
            {
                //validation
                var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
                if (cart.Count == 0)
                    throw new Exception("Your cart is empty");

                if (!_orderSettings.OnePageCheckoutEnabled)
                    throw new Exception("One page checkout is disabled");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    throw new Exception("Anonymous checkout is not allowed");

                //place order
                var processPaymentRequest = this.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                    {
                        throw new Exception("Payment information is not entered");
                    }
                    else
                        processPaymentRequest = new ProcessPaymentRequest();
                }

                processPaymentRequest.Customer = _workContext.CurrentCustomer;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.SelectedPaymentMethodSystemName;
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    this.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = placeOrderResult.PlacedOrder
                    };

                    var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(placeOrderResult.PlacedOrder.PaymentMethodSystemName);
                    if (paymentMethod == null)
                        throw new Exception("Payment method is not available"); //actually it's impossible
                    if (paymentMethod.PaymentMethodType == PaymentMethodType.Redirection)
                    {
                        //Redirection will not work because it's AJAX request.
                        //That's why we don't process it here (we redirect a user to another page where he'll be redirected)

                        //redirect
                        return Json(new { redirect = string.Format("{0}checkout/OpcCompleteRedirectionPayment", _webHelper.GetStoreLocation()) });
                    }
                    else
                    {
                        _paymentService.PostProcessPayment(postProcessPaymentRequest);
                        //success
                        return Json(new { success = 1 });
                    }
                }
                else
                {
                    //error
                    var confirmOrderModel = new CheckoutConfirmModel();
                    foreach (var error in placeOrderResult.Errors)
                        confirmOrderModel.Warnings.Add(error);

                    return Json(new
                        {
                            update_section = new UpdateSectionJsonModel()
                            {
                                name = "confirm-order",
                                html = RenderPartialViewToString("OpcConfirmOrder", confirmOrderModel)
                            },
                            goto_section = "confirm_order"
                        });
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Json(new { error = 1, message = exc.Message });
            }
        }
Exemplo n.º 28
0
        public ActionResult OpcCompleteRedirectionPayment()
        {
            try
            {
                //validation
                if (!_orderSettings.OnePageCheckoutEnabled)
                    return RedirectToAction("Index", "Home");

                if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                    return new HttpUnauthorizedResult();

                //get the order
                var orders = _orderService.GetOrdersByCustomerId(_workContext.CurrentCustomer.Id);
                if (orders.Count == 0)
                    return RedirectToAction("Index", "Home");

                var order = orders[0];
                var paymentMethod = _paymentService.LoadPaymentMethodBySystemName(order.PaymentMethodSystemName);
                if (paymentMethod == null)
                    return RedirectToAction("Index", "Home");
                if (paymentMethod.PaymentMethodType != PaymentMethodType.Redirection)
                    return RedirectToAction("Index", "Home");

                //ensure that order has been just placed
                if ((DateTime.UtcNow - order.CreatedOnUtc).TotalMinutes > 3)
                    return RedirectToAction("Index", "Home");

                //Redirection will not work on one page checkout page because it's AJAX request.
                //That's why we process it here
                var postProcessPaymentRequest = new PostProcessPaymentRequest()
                {
                    Order = order
                };
                _paymentService.PostProcessPayment(postProcessPaymentRequest);

                return RedirectToRoute("CheckoutCompleted");
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc, _workContext.CurrentCustomer);
                return Content(exc.Message);
            }
        }
Exemplo n.º 29
0
        public ActionResult ConfirmOrder()
        {
            //validation
            var cart = _workContext.CurrentCustomer.ShoppingCartItems.Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart).ToList();
            if (cart.Count == 0)
                return RedirectToRoute("ShoppingCart");

            if (_orderSettings.OnePageCheckoutEnabled)
                return RedirectToRoute("CheckoutOnePage");

            if ((_workContext.CurrentCustomer.IsGuest() && !_orderSettings.AnonymousCheckoutAllowed))
                return new HttpUnauthorizedResult();

            //model
            var model = new CheckoutConfirmModel();
            try
            {
                var processPaymentRequest = this.Session["OrderPaymentInfo"] as ProcessPaymentRequest;
                if (processPaymentRequest == null)
                {
                    //Check whether payment workflow is required
                    if (IsPaymentWorkflowRequired(cart))
                        return RedirectToRoute("CheckoutPaymentInfo");
                    else
                        processPaymentRequest = new ProcessPaymentRequest();
                }

                processPaymentRequest.Customer = _workContext.CurrentCustomer;
                processPaymentRequest.PaymentMethodSystemName = _workContext.CurrentCustomer.SelectedPaymentMethodSystemName;
                var placeOrderResult = _orderProcessingService.PlaceOrder(processPaymentRequest);
                if (placeOrderResult.Success)
                {
                    this.Session["OrderPaymentInfo"] = null;
                    var postProcessPaymentRequest = new PostProcessPaymentRequest()
                    {
                        Order = placeOrderResult.PlacedOrder
                    };
                    _paymentService.PostProcessPayment(postProcessPaymentRequest);

                    return RedirectToRoute("CheckoutCompleted");
                }
                else
                {
                    foreach (var error in placeOrderResult.Errors)
                        model.Warnings.Add(error);
                }
            }
            catch (Exception exc)
            {
                _logger.Warning(exc.Message, exc);
                model.Warnings.Add(exc.Message);
            }

            //If we got this far, something failed, redisplay form
            return View(model);
        }
        /// <summary>
        /// Post process payment (used by payment gateways that require redirecting to a third-party URL)
        /// </summary>
        /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param>
        public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest)
        {
			//string amount = postProcessPaymentRequest.Order.OrderTotal.ToString ("#.##");
			//amount.ToString ();
            var remotePostHelper = new RemotePost();
            var remotePostHelperData = new Dictionary<string, string>();
            
            remotePostHelper.FormName = "PaytmForm";
			remotePostHelper.Url = _PaytmPaymentSettings.PaymentUrl;
            remotePostHelperData.Add("MID", _PaytmPaymentSettings.MerchantId.ToString());
			remotePostHelperData.Add("WEBSITE", _PaytmPaymentSettings.Website.ToString());
			remotePostHelperData.Add("CHANNEL_ID", "WEB");
			remotePostHelperData.Add("INDUSTRY_TYPE_ID", _PaytmPaymentSettings.IndustryTypeId.ToString());
			remotePostHelperData.Add("TXN_AMOUNT", postProcessPaymentRequest.Order.OrderTotal.ToString ("#.##"));
            remotePostHelperData.Add("ORDER_ID", postProcessPaymentRequest.Order.Id.ToString());
			remotePostHelperData.Add("EMAIL", postProcessPaymentRequest.Order.BillingAddress.Email);
            remotePostHelperData.Add("MOBILE_NO", postProcessPaymentRequest.Order.BillingAddress.PhoneNumber);
            remotePostHelperData.Add("CUST_ID", postProcessPaymentRequest.Order.BillingAddress.Email);
			remotePostHelperData.Add("CALLBACK_URL", _webHelper.GetStoreLocation(false) + "Plugins/PaymentPaytm/Return");

			//remotePostHelperData.Add("CALLBACK_URL", _PaytmPaymentSettings.CallBackUrl.ToString());
            
			Dictionary<string,string> parameters = new Dictionary<string,string> ();

            
            foreach (var item in remotePostHelperData)
            {
              parameters.Add(item.Key,item.Value);
			   remotePostHelper.Add(item.Key,item.Value);
            }


            try
            {
                string checksumHash = "";

				checksumHash = CheckSum.generateCheckSum(_PaytmPaymentSettings.MerchantKey,parameters);
				remotePostHelper.Add("CHECKSUMHASH", checksumHash);
               
                
                remotePostHelper.Post();
            }
            catch (Exception ep)
            {
                throw new Exception(ep.Message);
            }
        }