예제 #1
0
        public bool GetXmlResponse(string transactionCommand, out string response, out FirstPayXmlResponse xmlResponse)
        {
            Encoding encoding  = System.Text.Encoding.GetEncoding(1252);
            bool     returnVal = false;

            response    = null;
            xmlResponse = null;
            byte[] data = encoding.GetBytes(transactionCommand);

            // Prepare web request...
            try
            {
                string         AuthServer = AppLogic.AppConfig("1stPay.XmlURL");
                HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);
                myRequest.ContentLength = data.Length;
                myRequest.Method        = "POST";

                Stream newStream = myRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                // get the response
                HttpWebResponse myResponse;
                myResponse = (HttpWebResponse)myRequest.GetResponse();

                using (StreamReader sr = new StreamReader(myResponse.GetResponseStream(), encoding))
                {
                    response = sr.ReadToEnd();
                    // Close and clean up the StreamReader
                    sr.Close();
                }
                myResponse.Close();

                XmlDocument Doc = new XmlDocument();
                // Zap the DOCTYPE so we don't try to find a corresponding DTD.
                string t1      = "<!DOCTYPE Response SYSTEM";
                string t2      = ">";
                string doctype = t1 + CommonLogic.ExtractToken(response, t1, t2) + t2;
                Doc.LoadXml(response.Replace(doctype, ""));

                xmlResponse = new FirstPayXmlResponse(Doc);
                returnVal   = true;
            }
            catch { }
            return(returnVal);
        }
예제 #2
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires      = -1;
            Response.AddHeader("pragma", "no-cache");

            Response.Cache.SetAllowResponseInBrowserHistory(false);

            Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer;

            ThisCustomer.RequireCustomerRecord();

            int    CustomerID    = ThisCustomer.CustomerID;
            String Payload       = ThisCustomer.ThisCustomerSession["Cardinal.Payload"];
            String PaRes         = CommonLogic.FormCanBeDangerousContent("PaRes");
            String TransactionID = ThisCustomer.ThisCustomerSession["Cardinal.TransactionID"];
            int    OrderNumber   = ThisCustomer.ThisCustomerSession.SessionUSInt("Cardinal.OrderNumber");

            String ReturnURL = String.Empty;

            if (ShoppingCart.CartIsEmpty(CustomerID, CartTypeEnum.ShoppingCart))
            {
                ReturnURL = "ShoppingCart.aspx";
            }

            ErrorMessage err;

            if (ReturnURL.Length == 0)
            {
                if (OrderNumber == 0)
                {
                    err       = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspcs.cs.1", 1, Localization.GetDefaultLocale())));
                    ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
                }
            }

            if (ReturnURL.Length == 0)
            {
                if (Payload.Length == 0 || TransactionID.Length == 0)
                {
                    err       = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspcs.cs.1", 1, Localization.GetDefaultLocale())));
                    ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
                }
            }

            String PAResStatus           = String.Empty;
            String SignatureVerification = String.Empty;
            String ErrorNo   = String.Empty;
            String ErrorDesc = String.Empty;

            if (ReturnURL.Length == 0)
            {
                String CardinalAuthenticateResult = String.Empty;
                String AuthResult = Cardinal.PreChargeAuthenticate(OrderNumber, PaRes, TransactionID, out PAResStatus, out SignatureVerification, out ErrorNo, out ErrorDesc, out CardinalAuthenticateResult);
                ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"] = CardinalAuthenticateResult;

                //=====================================================================================
                // Determine if the Authentication was Successful or Error
                //
                // Please consult the documentation regarding the handling of each response scenario.
                //
                // If the Authentication results (PAResStatus) is a Y or A, and the SignatureVerification is Y, then
                // the Payer Authentication was successful. The Authorization Message should be processed,
                // and the User taken to a Order Confirmation location.
                //
                // If the Authentication results were not successful (PAResStatus = N), or
                // the ErrorNo was NOT //0// then the Consumer should be redirected, and prompted for another
                // form of payment.
                //
                // If the Authentication results were not successful (PAResStatus = U) and the ErrorNo = //0//
                // then authorization message should be processed. In this case the merchant will retain
                // liability for this transaction if it is sent to authorization.
                //
                // Note that it is also important that you account for cases when your flow logic can account
                // for error cases, and the flow can be broken after //N// number of attempts
                //=====================================================================================

                // handle success cases:
                if (((PAResStatus == "Y" || PAResStatus == "A") && SignatureVerification == "Y") || (PAResStatus == "U" && ErrorNo == "0"))
                {
                    ShoppingCart cart = new ShoppingCart(1, ThisCustomer, CartTypeEnum.ShoppingCart, 0, false);

                    // GET CAVV from authenticate call result:
                    String CAVV = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Cavv>", "</Cavv>");
                    String ECI  = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<EciFlag>", "</EciFlag>");
                    String XID  = CommonLogic.ExtractToken(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Xid>", "</Xid>");

                    Address UseBillingAddress = new Address();
                    UseBillingAddress.LoadByCustomer(ThisCustomer.CustomerID, ThisCustomer.PrimaryBillingAddressID, AddressTypes.Billing);

                    String status = Gateway.MakeOrder(String.Empty, AppLogic.TransactionMode(), cart, OrderNumber, CAVV, ECI, XID, String.Empty);

                    if (status != AppLogic.ro_OK)
                    {
                        err       = new ErrorMessage(status);
                        ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
                    }
                    else
                    {
                        // store cardinal call results for posterity:
                        DB.ExecuteSQL("update orders set CardinalLookupResult=" + DB.SQuote(ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"]) + ", CardinalAuthenticateResult=" + DB.SQuote(ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"]) + " where OrderNumber=" + OrderNumber.ToString());
                        ReturnURL = "orderconfirmation.aspx?ordernumber=" + OrderNumber.ToString() + "&paymentmethod=Credit+Card";
                    }
                }

                // handle failure:
                if (PAResStatus == "N" || ErrorNo != "0")
                {
                    err       = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspx.3", 1, Localization.GetDefaultLocale())));
                    ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
                }


                // handle failure:
                if (SignatureVerification == "N" || ErrorNo != "0")
                {
                    err       = new ErrorMessage(Server.HtmlEncode(AppLogic.GetString("cardinal_process.aspx.4", 1, Localization.GetDefaultLocale())));
                    ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
                }
            }

            if (ReturnURL.Length == 0)
            {
                err       = new ErrorMessage(Server.HtmlEncode(String.Format(AppLogic.GetString("cardinal_process.aspx.5", 1, Localization.GetDefaultLocale()), ErrorDesc)));
                ReturnURL = "checkoutpayment.aspx?error=1&errormsg=" + err.MessageId;
            }
            ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"]       = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.AuthenticateResult"] = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.ACSUrl"]             = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.Payload"]            = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.TransactionID"]      = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.OrderNumber"]        = String.Empty;
            ThisCustomer.ThisCustomerSession["Cardinal.LookupResult"]       = String.Empty;

            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");
            Response.Write("<html><head><title>Cardinal Process</title></head><body>");
            Response.Write("<script type=\"text/javascript\">\n");
            Response.Write("top.location='" + ReturnURL + "';\n");
            Response.Write("</SCRIPT>\n");
            Response.Write("<div align=\"center\">" + String.Format(AppLogic.GetString("cardinal_process.aspx.6", 1, Localization.GetDefaultLocale()), ReturnURL) + "</div>");
            Response.Write("</body></html>");
        }
예제 #3
0
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<Request>");
            transactionCommand.Append("<AC>");
            transactionCommand.Append("<CommonData>");
            transactionCommand.Append("<CommonMandatory AuthOverrideInd=\"N\" LangInd=\"00\" CardHolderAttendanceInd=\"01\" HcsTcsInd=\"T\" TxCatg=\"7\" MessageType=\"" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "A", "AC") + "\" Version=\"2\" TzCode=\"" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TZCODE") + "\">");
            transactionCommand.Append("<AccountNum AccountTypeInd=\"91\">" + UseBillingAddress.CardNumber + "</AccountNum>");
            transactionCommand.Append("<POSDetails POSEntryMode=\"01\"/>");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_ID") + "</MerchantID>");
            transactionCommand.Append("<TerminalID TermEntCapInd=\"05\" CATInfoInd=\"06\" TermLocInd=\"01\" CardPresentInd=\"N\" POSConditionCode=\"59\" AttendedTermDataInd=\"01\">" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TERMINAL_ID") + "</TerminalID>");
            transactionCommand.Append("<BIN>" + AppLogic.AppConfig("PAYMENTECH_BIN") + "</BIN>");
            transactionCommand.Append("<OrderID>" + OrderNumber.ToString().PadRight(16, '0') + "</OrderID>");
            transactionCommand.Append("<AmountDetails>");
            transactionCommand.Append("<Amount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(",", "").Replace(".", "").PadLeft(12, '0') + "</Amount>");
            transactionCommand.Append("</AmountDetails>");
            transactionCommand.Append("<TxTypeCommon TxTypeID=\"G\"/>");
            transactionCommand.Append("<Currency CurrencyCode=\"" + Localization.StoreCurrencyNumericCode() + "\" CurrencyExponent=\"" + CommonLogic.IIF(Localization.StoreCurrencyNumericCode() == "392", "0", "2") + "\"/>"); // 392 is Japanese Yen
            transactionCommand.Append("<CardPresence>");
            transactionCommand.Append("<CardNP>");
            transactionCommand.Append("<Exp>" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2) + "</Exp>");
            transactionCommand.Append("</CardNP>");
            transactionCommand.Append("</CardPresence>");
            transactionCommand.Append("<TxDateTime/>");
            transactionCommand.Append("</CommonMandatory>");
            transactionCommand.Append("<CommonOptional>");
            transactionCommand.Append("<Comments>" + XmlCommon.XmlEncode("CustomerID: " + CustomerID.ToString()) + "</Comments>");
            if (CardExtraCode.Trim().Length != 0)
            {
                // The handling of CardSecVal does not match the documentation per request from Paymentech.
                // From Paymentech... November 21, 2006 (Reported under bug 213)
                // "The field is CardSecInd and the value is null. There is an error in the wording
                // of the interface specification. There are 4 choices for this field 1, 2, 9, and null.
                // The 1 says value deliberately bypassed or not provided but it really should say value
                // is present. The 1 is sent for VI and DI only it should be null for AX and MC. So it
                // is only an issue for the VI transaction. If you have the gateway message templates
                // the visa/discover credit card ecommerce template shows the correct formatting."
                transactionCommand.Append(CommonLogic.IIF(UseBillingAddress.CardType.Equals("VISA", StringComparison.InvariantCultureIgnoreCase) || UseBillingAddress.CardType.Equals("DISCOVER", StringComparison.InvariantCultureIgnoreCase), "<CardSecVal CardSecInd=\"1\">" + CardExtraCode + "</CardSecVal>", "<CardSecVal CardSecInd=\"\">" + CardExtraCode + "</CardSecVal>"));
            }

            transactionCommand.Append("<ECommerceData ECSecurityInd=\"07\">");
            transactionCommand.Append("<ECOrderNum>" + OrderNumber.ToString().PadRight(16, '0') + "</ECOrderNum>");
            transactionCommand.Append("</ECommerceData>");
            transactionCommand.Append("</CommonOptional>");
            transactionCommand.Append("</CommonData>");

            string xmlName = (UseBillingAddress.FirstName + " " + UseBillingAddress.LastName).Trim();



            transactionCommand.Append("<Auth>");
            transactionCommand.Append("<AuthMandatory FormatInd=\"H\"/>");
            transactionCommand.Append("<AuthOptional>");

            if (AppLogic.AppConfigBool("PAYMENTECH_Verify_Addresses") || AppLogic.AppConfig("PAYMENTECH_Verify_Addresses").Equals("full", StringComparison.InvariantCultureIgnoreCase))
            {
                transactionCommand.Append("<AVSextended>");
                transactionCommand.Append("<AVSname>" + XmlCommon.XmlEncodeMaxLength(xmlName, 30) + "</AVSname>");                            // max 30 chars
                transactionCommand.Append("<AVSaddress1>" + XmlCommon.XmlEncodeMaxLength(UseBillingAddress.Address1, 30) + "</AVSaddress1>"); // max 30 chars
                transactionCommand.Append("<AVSaddress2>" + XmlCommon.XmlEncodeMaxLength(UseBillingAddress.Address2, 30) + "</AVSaddress2>"); // max 30 chars
                transactionCommand.Append("<AVScity>" + XmlCommon.XmlEncodeMaxLength(UseBillingAddress.City, 20) + "</AVScity>");             // max 20 chars
                transactionCommand.Append("<AVSstate>" + XmlCommon.XmlEncode(UseBillingAddress.State.Replace("--", "")) + "</AVSstate>");
                transactionCommand.Append("<AVSzip>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</AVSzip>");
                transactionCommand.Append("<AVScountryCode>" + AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country) + "</AVScountryCode>");
                transactionCommand.Append("</AVSextended>");
            }
            else
            {
                if (AppLogic.AppConfig("PAYMENTECH_Verify_Addresses").Equals("zip", StringComparison.InvariantCultureIgnoreCase))
                {
                    transactionCommand.Append("<AVSextended>");
                    transactionCommand.Append("<AVSzip>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</AVSzip>");
                    transactionCommand.Append("<AVScountryCode>" + AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country) + "</AVScountryCode>");
                    transactionCommand.Append("</AVSextended>");
                }
            }

            if (CAVV.Trim().Length != 0)
            {
                if (UseBillingAddress.CardType.Equals("VISA", StringComparison.InvariantCultureIgnoreCase) && AppLogic.AppConfigBool("Paymentech.UseVerifiedByVisa"))
                {
                    transactionCommand.Append("<VerifiedByVisa>");
                    transactionCommand.Append("<CAVV>" + CAVV + "</CAVV>");
                    transactionCommand.Append("<XID>" + XID + "</XID>");
                    transactionCommand.Append("</VerifiedByVisa>");
                }
                else if (UseBillingAddress.CardType.Equals("MASTERCARD", StringComparison.InvariantCultureIgnoreCase))
                {
                    transactionCommand.Append("<MCSecureCode><AAV>" + CAVV + "</AAV></MCSecureCode>");
                }
            }

            transactionCommand.Append("</AuthOptional>");
            transactionCommand.Append("</Auth>");

            transactionCommand.Append("<Cap>");
            transactionCommand.Append("<CapMandatory>");
            transactionCommand.Append("<EntryDataSrc>02</EntryDataSrc>");
            transactionCommand.Append("</CapMandatory>");
            transactionCommand.Append("<CapOptional/>");
            transactionCommand.Append("</Cap>");
            transactionCommand.Append("</AC>");
            transactionCommand.Append("</Request>");

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("PAYMENTECH_LIVE_SERVER"), AppLogic.AppConfig("PAYMENTECH_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.ContentType   = "application/PTI34";
            myRequest.ContentLength = data.Length;
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.Method = "POST";
            string temp      = myRequest.ToString();
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response
            TransactionResponse = rawResponseString;

            XmlDocument Doc = new XmlDocument();
            // Zap the DOCTYPE so we don't try to find a corresponding DTD.
            String t1      = "<!DOCTYPE Response SYSTEM";
            String t2      = ">";
            String doctype = t1 + CommonLogic.ExtractToken(rawResponseString, t1, t2) + t2;

            Doc.LoadXml(rawResponseString.Replace(doctype, ""));

            XmlNode Node = Doc.SelectSingleNode("Response/ACResponse/CommonDataResponse/CommonMandatoryResponse");

            String replyCode    = String.Empty;
            String responseCode = String.Empty;
            String approvalCode = String.Empty;
            String AVSCode      = String.Empty;
            String CVCode       = String.Empty;
            String authResponse = String.Empty;
            String TransID      = String.Empty;

            if (Node != null)
            {
                replyCode    = XmlCommon.XmlField(Node, "ApprovalStatus");
                responseCode = XmlCommon.XmlField(Node, "ResponseCodes/RespCode");
                approvalCode = XmlCommon.XmlField(Node, "ResponseCodes/AuthCode");
                AVSCode      = XmlCommon.XmlField(Node, "ResponseCodes/AVSRespCode");
                CVCode       = XmlCommon.XmlField(Node, "ResponseCodes/CVV2RespCode");
                authResponse = XmlCommon.XmlField(Node, "StatusMsg");
                TransID      = XmlCommon.XmlField(Node, "TxRefNum");
            }
            else
            {
                Node = Doc.SelectSingleNode("Response/QuickResponse");
                if (Node != null)
                {
                    authResponse = XmlCommon.XmlField(Node, "ProcStatus")
                                   + " - " + XmlCommon.XmlField(Node, "StatusMsg");
                }
            }

            AuthorizationCode    = approvalCode;
            AuthorizationResult  = rawResponseString;
            AuthorizationTransID = TransID;
            AVSResult            = AVSCode;
            if (CVCode.Length > 0)
            {
                AVSResult += ", CV Result: " + CVCode;
            }
            TransactionCommandOut = transactionCommand.ToString();

            if (replyCode == "1")
            {
                result = AppLogic.ro_OK;
            }
            else if (replyCode == "0")
            {
                result = "DECLINED";
                if (authResponse.Length > 0)
                {
                    result += ". " + authResponse;
                }
            }
            else if (authResponse.Length > 0)
            {
                result = "Error: " + authResponse;
            }
            else
            {
                result = "System Error: " + rawResponseString;
            }

            return(result);
        }
예제 #4
0
        public override String CaptureOrder(Order o)
        {
            String result = AppLogic.ro_OK;

            bool useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";

            String  TransID     = o.AuthorizationPNREF;
            Decimal TotalAmount = o.OrderBalance;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(5000);

            transactionCommand.Append("<Request>");
            transactionCommand.Append("<AC>");
            transactionCommand.Append("<CommonData>");
            transactionCommand.Append("<CommonMandatory MessageType=\"C\">");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_ID") + "</MerchantID>");
            transactionCommand.Append("<TerminalID TermEntCapInd=\"05\" CATInfoInd=\"06\" TermLocInd=\"01\" CardPresentInd=\"N\" POSConditionCode=\"59\" AttendedTermDataInd=\"01\">" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TERMINAL_ID") + "</TerminalID>");
            transactionCommand.Append("<BIN>" + AppLogic.AppConfig("PAYMENTECH_BIN") + "</BIN>");
            transactionCommand.Append("<OrderID>" + o.OrderNumber.ToString().PadRight(16, '0') + "</OrderID>");
            transactionCommand.Append("<AmountDetails>");
            transactionCommand.Append("<Amount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount).Replace(",", "").Replace(".", "").PadLeft(12, '0') + "</Amount>");
            transactionCommand.Append("</AmountDetails>");
            transactionCommand.Append("</CommonMandatory>");
            transactionCommand.Append("<CommonOptional>");
            transactionCommand.Append("<TxRefNum>" + TransID + "</TxRefNum>");
            transactionCommand.Append("</CommonOptional>");
            transactionCommand.Append("</CommonData>");
            transactionCommand.Append("</AC>");
            transactionCommand.Append("</Request>");

            o.CaptureTXCommand = transactionCommand.ToString();

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("PAYMENTECH_LIVE_SERVER"), AppLogic.AppConfig("PAYMENTECH_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.ContentType   = "application/PTI34";
            myRequest.ContentLength = data.Length;
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.Method = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            XmlDocument Doc = new XmlDocument();
            // Zap the DOCTYPE so we don't try to find a corresponding DTD.
            String t1      = "<!DOCTYPE Response SYSTEM";
            String t2      = ">";
            String doctype = t1 + CommonLogic.ExtractToken(rawResponseString, t1, t2) + t2;

            Doc.LoadXml(rawResponseString.Replace(doctype, ""));

            XmlNode Node = Doc.SelectSingleNode("Response/ACResponse");

            String replyCode    = String.Empty;
            String responseCode = String.Empty;
            String authResponse = String.Empty;

            if (Node != null)
            {
                replyCode    = XmlCommon.XmlField(Node, "CommonDataResponse/CommonMandatoryResponse/ProcStatus");
                authResponse = XmlCommon.XmlField(Node, "CommonDataResponse/CommonMandatoryResponse/StatusMsg");
                responseCode = XmlCommon.XmlAttribute(Node.SelectSingleNode("CapResponse/CapMandatoryResponse"), "CapStatus");
            }
            else
            {
                Node = Doc.SelectSingleNode("Response/QuickResponse");
                if (Node != null)
                {
                    authResponse = XmlCommon.XmlField(Node, "ProcStatus")
                                   + " - " + XmlCommon.XmlField(Node, "StatusMsg");
                }
            }

            if (rawResponseString.Contains("<AccountNum>"))
            {
                rawResponseString = rawResponseString.Replace(CommonLogic.ExtractToken(rawResponseString, "<AccountNum>", "</AccountNum>"), "****");
            }
            o.CaptureTXResult = rawResponseString;

            if (replyCode == "0" && responseCode == "1")
            {
                result = AppLogic.ro_OK;
            }
            else if (replyCode.Length > 0)
            {
                result = "Transaction was not marked for capture. " + replyCode + " - " + authResponse;
            }
            else if (authResponse.Length > 0)
            {
                result = "Error: " + authResponse;
            }
            else
            {
                result = "System Error: " + rawResponseString;
            }


            return(result.Trim());
        }
예제 #5
0
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override String RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, Address UseBillingAddress)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());

            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            String  CardNumber          = String.Empty;
            String  CardExpM            = String.Empty;
            String  CardExpY            = String.Empty;
            String  ApprvCode           = String.Empty;
            decimal TotalAmount         = 0;
            decimal RefundTotal         = 0;
            int     OrdNo = CommonLogic.IIF(NewOrderNumber == 0, OriginalOrderNumber, NewOrderNumber);

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID    = DB.RSField(rs, "AuthorizationPNREF");
                        CardNumber = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNumber.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNumber = DB.RSField(rs, "CardNumber");
                        }
                        CardExpM    = DB.RSField(rs, "CardExpirationMonth");
                        CardExpY    = DB.RSField(rs, "CardExpirationYear").Substring(2, 2);
                        ApprvCode   = DB.RSField(rs, "AuthorizationCode");
                        TotalAmount = DB.RSFieldDecimal(rs, "OrderTotal");
                        //For full refunds a value of zero is passed, so use the order total
                        RefundTotal = CommonLogic.IIF(RefundAmount > 0, RefundAmount, TotalAmount);
                    }
                }
            }

            if (CardNumber == AppLogic.ro_CCNotStoredString || CardNumber.Length == 0)
            {
                return("Failed. The credit card number is required and is not stored for this purchase.");
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(5000);

            transactionCommand.Append("<Request>");
            transactionCommand.Append("<Refund POSEntryMode=\"01\" AccountTypeInd=\"91\" TermEntCapInd=\"05\" CATInfoInd=\"06\" TermLocInd=\"01\" CardHolderAttendanceInd=\"01\" CardPresentInd=\"N\" POSConditionCode=\"59\" AttendedTermDataInd=\"01\" FormatInd=\"N\" HcsTcsInd=\"T\" TxCatg=\"7\" MessageType=\"FR\" Version=\"2\" TzCode=\"" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TZCODE") + "\">");
            transactionCommand.Append("<TxRefIdx />");
            transactionCommand.Append("<Comments>" + XmlCommon.XmlEncode(RefundReason) + "</Comments>");
            transactionCommand.Append("<AccountNum AccountTypeInd=\"91\">" + CardNumber + "</AccountNum>");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_ID") + "</MerchantID>");
            transactionCommand.Append("<TerminalID TermEntCapInd=\"05\" CATInfoInd=\"06\" TermLocInd=\"01\" CardPresentInd=\"N\" POSConditionCode=\"59\" AttendedTermDataInd=\"01\">" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TERMINAL_ID") + "</TerminalID>");
            transactionCommand.Append("<BIN>" + AppLogic.AppConfig("PAYMENTECH_BIN") + "</BIN>");
            transactionCommand.Append("<OrderID>" + OrdNo.ToString().PadRight(16, '0') + "</OrderID>");
            transactionCommand.Append("<Amount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(CommonLogic.IIF(RefundTotal > TotalAmount, TotalAmount, RefundTotal)).Replace(",", "").Replace(".", "").PadLeft(12, '0') + "</Amount>");
            transactionCommand.Append("<Currency CurrencyCode=\"" + Localization.StoreCurrencyNumericCode() + "\" CurrencyExponent=\"" + CommonLogic.IIF(Localization.StoreCurrencyNumericCode() == "392", "0", "2") + "\"/>");
            transactionCommand.Append("<TxDateTime>" + DateTime.Now.ToString("hhmmssMMyyyy") + "</TxDateTime>");
            transactionCommand.Append("<CardPresence>");
            transactionCommand.Append("<CardNP>");
            transactionCommand.Append("<Exp>" + CardExpM + CardExpY + "</Exp>");
            transactionCommand.Append("</CardNP>");
            transactionCommand.Append("</CardPresence>");
            transactionCommand.Append("<POScardID>4</POScardID>");
            transactionCommand.Append("<EntryDataSrc>2</EntryDataSrc>");
            transactionCommand.Append("</Refund>");
            transactionCommand.Append("</Request>");

            String CardToken            = String.Format("<AccountNum AccountTypeInd=\"91\">{0}</AccountNum>", CardNumber);
            String CardTokenReplacement = String.Format("<AccountNum AccountTypeInd=\"91\">{0}</AccountNum>", "x".PadLeft(CardNumber.Length, 'x'));

            DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(transactionCommand.ToString().Replace(CardToken, CardTokenReplacement)) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("PAYMENTECH_LIVE_SERVER"), AppLogic.AppConfig("PAYMENTECH_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "application/PTI34";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response
            rawResponseString = rawResponseString.Replace(CardNumber, String.Empty);

            XmlDocument Doc = new XmlDocument();
            // Zap the DOCTYPE so we don't try to find a corresponding DTD.
            String t1      = "<!DOCTYPE Response SYSTEM";
            String t2      = ">";
            String doctype = t1 + CommonLogic.ExtractToken(rawResponseString, t1, t2) + t2;

            Doc.LoadXml(rawResponseString.Replace(doctype, ""));

            XmlNode Node = Doc.SelectSingleNode("Response/RefundResponse");

            String replyCode    = String.Empty;
            String responseCode = String.Empty;
            String authResponse = String.Empty;

            if (Node != null)
            {
                replyCode    = XmlCommon.XmlField(Node, "ProcStatus");
                authResponse = replyCode + " - " + XmlCommon.XmlField(Node, "StatusMsg");
            }
            else
            {
                Node = Doc.SelectSingleNode("Response/QuickResponse");
                if (Node != null)
                {
                    authResponse = XmlCommon.XmlField(Node, "ProcStatus")
                                   + " - " + XmlCommon.XmlField(Node, "StatusMsg");
                }
            }

            DB.ExecuteSQL("update orders set RefundTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            if (replyCode == "0")
            {
                result = AppLogic.ro_OK;
            }
            else if (authResponse.Length > 0)
            {
                result = "Error: " + authResponse;
            }
            else
            {
                result = "System Error: " + rawResponseString;
            }

            return(result);
        }
예제 #6
0
        public override String VoidOrder(int OrderNumber)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set VoidTXCommand=NULL, VoidTXResult=NULL where OrderNumber=" + OrderNumber.ToString());
            bool   useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String TransID             = String.Empty;
            String TxRefIdx            = String.Empty;

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID = DB.RSField(rs, "AuthorizationPNREF");

                        // For captured orders we need to look up the TxRefIdx from the original CaptureTXResult.
                        if (DB.RSFieldDateTime(rs, "CapturedOn") > System.DateTime.MinValue)
                        {
                            String captureResult = DB.RSField(rs, "CaptureTXResult");
                            // If we were running in AUTH CAPTURE mode then CaptureTXResult will be empty and our
                            // value will be in AuthorizationResult.
                            if (String.IsNullOrEmpty(captureResult))
                            {
                                captureResult = DB.RSField(rs, "AuthorizationResult");
                            }
                            XmlDocument Doc2 = new XmlDocument();
                            // Zap the DOCTYPE so we don't try to find a corresponding DTD.
                            String t21      = "<!DOCTYPE Response SYSTEM";
                            String t22      = ">";
                            String doctype2 = t21 + CommonLogic.ExtractToken(captureResult, t21, t22) + t22;
                            try
                            {
                                Doc2.LoadXml(captureResult.Replace(doctype2, ""));
                                XmlNode Node2 = Doc2.SelectSingleNode("Response/ACResponse/CommonDataResponse/CommonMandatoryResponse");
                                if (Node2 != null)
                                {
                                    TxRefIdx = XmlCommon.XmlField(Node2, "TxRefIdx");
                                }
                            }
                            catch { }
                        }
                    }
                }
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(5000);

            transactionCommand.Append("<Request>");
            transactionCommand.Append("<Void MessageType=\"V\">");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_ID") + "</MerchantID>");
            transactionCommand.Append("<TerminalID>" + AppLogic.AppConfig("PAYMENTECH_MERCHANT_TERMINAL_ID") + "</TerminalID>");
            transactionCommand.Append("<BIN>" + AppLogic.AppConfig("PAYMENTECH_BIN") + "</BIN>");
            transactionCommand.Append("<TxRefNum>" + TransID + "</TxRefNum>");
            if (TxRefIdx.Length > 0)
            {
                transactionCommand.Append("<TxRefIdx>" + TxRefIdx + "</TxRefIdx>");
            }
            else
            {
                transactionCommand.Append("<TxRefIdx />");
            }
            transactionCommand.Append("</Void>");
            transactionCommand.Append("</Request>");

            DB.ExecuteSQL("update orders set VoidTXCommand=" + DB.SQuote(transactionCommand.ToString()) + " where OrderNumber=" + OrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("PAYMENTECH_LIVE_SERVER"), AppLogic.AppConfig("PAYMENTECH_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "application/PTI34";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response
            XmlDocument Doc = new XmlDocument();
            // Zap the DOCTYPE so we don't try to find a corresponding DTD.
            String t1      = "<!DOCTYPE Response SYSTEM";
            String t2      = ">";
            String doctype = t1 + CommonLogic.ExtractToken(rawResponseString, t1, t2) + t2;

            Doc.LoadXml(rawResponseString.Replace(doctype, ""));

            XmlNode Node = Doc.SelectSingleNode("Response/VoidResponse");

            String replyCode    = String.Empty;
            String responseCode = String.Empty;
            String authResponse = String.Empty;

            if (Node != null)
            {
                replyCode    = XmlCommon.XmlField(Node, "ProcStatus");
                authResponse = replyCode + " - " + XmlCommon.XmlField(Node, "StatusMsg");
            }
            else
            {
                Node = Doc.SelectSingleNode("Response/QuickResponse");
                if (Node != null)
                {
                    authResponse = XmlCommon.XmlField(Node, "ProcStatus")
                                   + " - " + XmlCommon.XmlField(Node, "StatusMsg");
                }
            }

            if (rawResponseString.Contains("<AccountNum>"))
            {
                rawResponseString = rawResponseString.Replace(CommonLogic.ExtractToken(rawResponseString, "<AccountNum>", "</AccountNum>"), "****");
            }

            DB.ExecuteSQL("update orders set VoidTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OrderNumber.ToString());

            if (replyCode == "0")
            {
                result = AppLogic.ro_OK;
            }
            else if (authResponse.Length > 0)
            {
                result = "Error: " + authResponse;
            }
            else
            {
                result = "System Error: " + rawResponseString;
            }

            return(result);
        }
        protected void Page_Load(object sender, System.EventArgs e)
        {
            Response.CacheControl = "private";
            Response.Expires      = 0;
            Response.AddHeader("pragma", "no-cache");

            Customer ThisCustomer = ((AspDotNetStorefrontPrincipal)Context.User).ThisCustomer;

            int    GalleryID = CommonLogic.QueryStringUSInt("GalleryID");
            String Dir       = AppLogic.GetGalleryDir(GalleryID);
            String SFP       = CommonLogic.SafeMapPath("images/spacer.gif").Replace("images\\spacer.gif", "");

            if (!SFP.EndsWith("\\"))
            {
                SFP = SFP + "\\";
            }

            String tPath        = SFP + "images\\gallery\\" + Dir + "\\";
            int    NumSlides    = AppLogic.GetNumSlides(tPath);
            int    SlideIdx     = CommonLogic.QueryStringUSInt("SlideIDX");
            String ThisSlide    = tPath + "slide" + SlideIdx.ToString().PadLeft(2, '0') + "_lg.jpg";
            String ThisSlideRel = "images/gallery/" + Dir + "/slide" + SlideIdx.ToString().PadLeft(2, '0') + "_lg.jpg";
            bool   InShow       = CommonLogic.QueryStringBool("show");
            bool   ShowGallery  = (SlideIdx == 0);

            if (ShowGallery)
            {
                InShow = false; // can't do slide show in a gallery view
            }

            String GalleryName = CommonLogic.ExtractToken(CommonLogic.ReadFile(tPath + "gallery.xml", true), "<Name>", "</Name>");

            Response.Write("<html>\n");
            Response.Write("<head>\n");
            Response.Write("<title>" + AppLogic.AppConfig("StoreName") + " Gallery - " + GalleryName + "</title>\n");
            Response.Write("<script type=\"text/javascript\">\n");
            Response.Write("if ((screen.width > 800) && (screen.height > 600))\n");
            Response.Write("{\n");
            Response.Write("	var isNav4, isIE4;\n");
            Response.Write("	if (parseInt(navigator.appVersion.charAt(0)) >= 4)\n");
            Response.Write("	{\n");
            Response.Write("		isNav4 = (navigator.appName == \"Netscape\") ? 1 : 0;\n");
            Response.Write("		isIE4 = (navigator.appName.indexOf(\"Microsoft\") != -1) ? 1 : 0;\n");
            Response.Write("		isWin = (navigator.platform == \"Win32\") ? 1 : 0;\n");
            Response.Write("	}\n");
            Response.Write("\n");
            Response.Write("function fitWindowSize()\n");
            Response.Write("{\n");
            Response.Write("	if (isNav4)\n");
            Response.Write("	{\n");
            Response.Write("		if (isWin)\n");
            Response.Write("		{\n");
            Response.Write("			setWidth = (document.layers[0].document.images[0].width)+33;\n");
            Response.Write("			setHeight = (document.layers[0].document.images[0].height)+90;\n");
            Response.Write("		}\n");
            Response.Write("		else\n");
            Response.Write("		{\n");
            Response.Write("			setWidth = (document.layers[0].document.images[0].width)+33;\n");
            Response.Write("			setHeight = (document.layers[0].document.images[0].height)+90;\n");
            Response.Write("		}\n");
            Response.Write("		if (setWidth < 440)\n");
            Response.Write("		{\n");
            Response.Write("			setWidth = 440;\n");
            Response.Write("		}\n");
            Response.Write("		window.innerWidth = setWidth;\n");
            Response.Write("		window.innerHeight = setHeight;\n");
            Response.Write("	}\n");
            Response.Write("	if (isIE4)\n");
            Response.Write("	{\n");
            Response.Write("		if (isWin)\n");
            Response.Write("		{\n");
            Response.Write("			window.resizeTo(800, 800);\n");
            Response.Write("			width = (800 - (document.body.clientWidth -  document.images[6].width) +20);\n");
            Response.Write("			height = (800 - (document.body.clientHeight -  document.images[6].height) +90);\n");
            Response.Write("		}\n");
            Response.Write("		else\n");
            Response.Write("		{\n");
            Response.Write("			window.resizeTo(800, 800);\n");
            Response.Write("			width = (800 - (document.body.clientWidth -  document.images[6].width) + 25);\n");
            Response.Write("			height = (800 - (document.body.clientHeight -  document.images[6].height) + 105);\n");
            Response.Write("		}\n");
            Response.Write("		if (width < 440)\n");
            Response.Write("		{\n");
            Response.Write("			width = 440;\n");
            Response.Write("		}\n");
            Response.Write("		window.resizeTo(width, height);\n");
            Response.Write("	}\n");
            Response.Write("}\n");
            Response.Write("\n");
            Response.Write("}\n");
            Response.Write("\n");
            Response.Write("var timer1 = null;\n");
            Response.Write("var inShow = " + CommonLogic.IIF(InShow, "1", "0") + ";\n");
            Response.Write("function toggleShow()\n");
            Response.Write("{\n");
            Response.Write("	if(inShow == 1)\n");
            Response.Write("	{\n");
            Response.Write("		clearTimeout(timer1);\n");
            Response.Write("		inShow = 0;\n");
            Response.Write("	}\n");
            Response.Write("	else\n");
            Response.Write("	{\n");
            Response.Write("		setTimeout('go()',"+ (AppLogic.AppConfigUSInt("SlideShowInterval") * 1000).ToString() + ");\n");
            Response.Write("		inShow = 0;\n");
            Response.Write("	}\n");
            Response.Write("}\n");
            Response.Write("function go()\n");
            Response.Write("{\n");
            Response.Write("	location.href='showgallery.aspx?show=true&galleryid="+ GalleryID.ToString() + "&slideidx=" + CommonLogic.IIF(SlideIdx == NumSlides, 1, (SlideIdx + 1)).ToString() + "';\n");
            Response.Write("}\n");
            Response.Write("\n");
            Response.Write("</script>\n");
            Response.Write("\n");
            Response.Write("<style type=\"text/css\">\n");
            Response.Write(".picnr { font-family: Arial, Helvetica, sans-serif; font-size: 10px; color: #000000; text-decoration: none; font-weight: bold; }\n");
            Response.Write("</style>\n");
            Response.Write("\n");
            Response.Write("</head>\n");
            if (AppLogic.AppConfigBool("ResizeSlideWindow"))
            {
                Response.Write("<BODY BGCOLOR=\"#000000\" onload=\"fitWindowSize();\">\n");
            }
            else
            {
                Response.Write("<BODY BGCOLOR=\"#000000\">\n");
            }
            if (InShow)
            {
                Response.Write("<script type=\"text/javascript\">\n");
                Response.Write("timer1 = setTimeout('go()'," + (AppLogic.AppConfigUSInt("SlideShowInterval") * 1000).ToString() + ");\n");
                Response.Write("</script>\n");
            }

            Response.Write("<center>\n");
            Response.Write("<form name=\"form\">\n");
            Response.Write("<TABLE WIDTH=\"100%\" BORDER=0 CELLPADDING=0 CELLSPACING=0  height=19>\n");
            Response.Write("<TR>\n");
            Response.Write("<TD width=\"162\" height=19><a href=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "\"><IMG SRC=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_top_01.gif") + "\" border=\"0\" WIDTH=162 HEIGHT=19></TD>\n");
            Response.Write("<TD bgcolor=\"#000000\" width=\"100%\">&nbsp;</TD>\n");
            Response.Write("<TD width=\"15\" height=19><IMG SRC=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_top_03.gif") + "\" WIDTH=15 HEIGHT=19></TD>\n");
            Response.Write("<TD width=\"180\" bgcolor=\"#969696\" class=\"picnr\" align=\"right\" nowrap height=19>picture " + SlideIdx.ToString() + " of " + NumSlides.ToString() + "    &nbsp;&nbsp;&nbsp;&nbsp;I&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"javascript:window.close()\"><font class=\"picnr\">close window</font></a></TD>\n");
            Response.Write("<TD width=\"1\" bgcolor=\"#969696\" height=19>&nbsp; </TD>\n");
            Response.Write("<TD width=\"28\" height=19><a href=\"javascript:window.close()\"><IMG SRC=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_top_06.gif") + "\" border=\"0\" WIDTH=28 HEIGHT=19></a></TD>\n");
            Response.Write("</TR>\n");
            Response.Write("</TABLE>\n");
            Response.Write("<TABLE WIDTH=\"100%\" BORDER=0 CELLPADDING=0 CELLSPACING=0>\n");
            Response.Write("<tr>\n");
            Response.Write("<td width=\"86\">\n");
            Response.Write("<a href=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "&slideidx=" + CommonLogic.IIF(SlideIdx == 1 || SlideIdx == 0, NumSlides, (SlideIdx - 1)).ToString() + "\">\n");
            Response.Write("<img src=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_bot_01.gif") + "\" border=\"0\" width=86 height=36></a>");
            Response.Write("</td>\n");
            Response.Write("<td width=\"94\">\n");
            Response.Write("<a href=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "&slideidx=" + CommonLogic.IIF(SlideIdx == NumSlides, 1, (SlideIdx + 1)).ToString() + "\">\n");
            Response.Write("<img src=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_bot_02.gif") + "\" border=\"0\" width=94 height=36></a>");
            Response.Write("</td>\n");
            Response.Write("<td height=\"36\" align=\"center\" background=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_bot_03.gif") + "\" width=\"100%\"> \n");
            Response.Write("<select name=\"url\" onchange=\"javascript:location.href=form.url.options[form.url.selectedIndex].value\">\n");
            Response.Write("<option value=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "\"" + CommonLogic.IIF(SlideIdx == 0, " selected ", "") + ">Gallery</option>\n");
            for (int i = 1; i <= NumSlides; i++)
            {
                Response.Write("<option value=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "&slideidx=" + i.ToString() + "\"" + CommonLogic.IIF(SlideIdx == i, " selected ", "").ToString() + ">" + i.ToString() + "</option>\n");
            }
            Response.Write("</select>\n");
            Response.Write("</td>\n");
            Response.Write("<td width=\"181\"><a href=\"#\" onclick=\"toggleShow();\">\n");
            Response.Write("<img name=\"slideshow\" src=\"" + AppLogic.LocateImageURL("images/gallery/pictorial_bot_04.gif") + "\" border=\"0\"></a></td>\n");
            Response.Write("</tr>\n");
            Response.Write("</table>\n");
            Response.Write("</form>\n");
            Response.Write("</center>\n");
            Response.Write("<div style=\"position:absolute; left:10px; top:72px\">\n");
            if (ShowGallery)
            {
                for (int i = 1; i <= NumSlides; i++)
                {
                    Response.Write("<a href=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "&slideidx=" + i.ToString() + "\">");
                    Response.Write("<img src=\"" + "images/gallery/" + Dir + "/slide" + i.ToString().PadLeft(2, '0') + ".jpg\" border=\"0\">");
                    Response.Write("</a>&nbsp;");
                }
            }
            else
            {
                Response.Write("<a href=\"showgallery.aspx?galleryid=" + GalleryID.ToString() + "&slideidx=" + CommonLogic.IIF(SlideIdx == NumSlides, 1, (SlideIdx + 1)).ToString() + "\">\n");
                Response.Write("<img src=\"" + ThisSlideRel + "\" border=\"0\">");
                Response.Write("</a>\n");
            }
            Response.Write("</div>\n");
            Response.Write("</BODY>\n");
            Response.Write("</HTML>\n");
        }
예제 #8
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override String RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, Address UseBillingAddress)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());

            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            String  CardNum             = String.Empty;
            String  CardExpM            = String.Empty;
            String  CardExpY            = String.Empty;
            String  ApprvCode           = String.Empty;
            String  BillingLastName     = String.Empty;
            String  BillingFirstName    = String.Empty;
            String  BillingAddress1     = String.Empty;
            String  BillingCity         = String.Empty;
            String  BillingState        = String.Empty;
            String  BillingZip          = String.Empty;
            String  BillingPhone        = String.Empty;
            String  BillingEmail        = String.Empty;
            decimal TotalAmount         = 0;

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID = DB.RSField(rs, "AuthorizationPNREF");
                        CardNum = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNum = "";
                        }
                        if (String.IsNullOrEmpty(CardNum))
                        {
                            return("JetPay requires that you store credit card numbers to refund orders. To store credit card numbers set the StoreCCInDB app config.You will not be able to refund orders taken before storing card numbers.");
                        }
                        CardExpM         = DB.RSField(rs, "CardExpirationMonth");
                        CardExpY         = DB.RSField(rs, "CardExpirationYear").Substring(2, 2);
                        ApprvCode        = DB.RSField(rs, "AuthorizationCode");
                        TotalAmount      = DB.RSFieldDecimal(rs, "OrderTotal");
                        BillingLastName  = DB.RSField(rs, "BillingLastName");
                        BillingFirstName = DB.RSField(rs, "BillingFirstName");
                        BillingAddress1  = DB.RSField(rs, "BillingAddress1");
                        BillingCity      = DB.RSField(rs, "BillingCity");
                        BillingState     = DB.RSField(rs, "BillingState");
                        BillingZip       = DB.RSField(rs, "BillingZip");
                        BillingPhone     = DB.RSField(rs, "BillingPhone");
                        BillingEmail     = DB.RSField(rs, "Email");
                    }
                }
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>CREDIT</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + NewOrderNumber.ToString().PadLeft(18, '0') + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");

            transactionCommand.Append("<CardExpMonth>" + CardExpM + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + CardExpY + "</CardExpYear>");
            transactionCommand.Append("<CardName>" + BillingFirstName + " " + BillingLastName + "</CardName>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(RefundAmount).Replace(",", "").Replace(".", "") + "</TotalAmount>");
            transactionCommand.Append("<BillingAddress>" + XmlCommon.XmlEncode(BillingAddress1) + "</BillingAddress>");
            transactionCommand.Append("<BillingCity>" + XmlCommon.XmlEncode(BillingCity) + "</BillingCity>");
            transactionCommand.Append("<BillingStateProv>" + BillingState + "</BillingStateProv>");
            transactionCommand.Append("<BillingPostalCode>" + BillingZip + "</BillingPostalCode>");

            transactionCommand.Append("<BillingPhone>" + BillingPhone + "</BillingPhone>");
            transactionCommand.Append("<Email>" + BillingEmail + "</Email>");
            transactionCommand.Append("<UDField1>" + XmlCommon.XmlEncode(RefundReason) + "</UDField1>");
            transactionCommand.Append("</JetPay>");

            String CardToken            = String.Format("<CardNum>{0}</CardNum>", CardNum);
            String CardTokenReplacement = String.Format("<CardNum>{0}</CardNum>", AppLogic.SafeDisplayCardNumber(CardNum, "Orders", OriginalOrderNumber));

            DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(transactionCommand.ToString().Replace(CardToken, CardTokenReplacement)) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql       = String.Empty;
            String replyCode = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            //String responseCode = CommonLogic.ExtractToken(rawResponseString,"<RespCode>","</RespCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");
            String ErrMsg       = CommonLogic.ExtractToken(rawResponseString, "<ErrMsg>", "</ErrMsg>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");


            DB.ExecuteSQL("update orders set RefundTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OriginalOrderNumber.ToString());
            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }
예제 #9
0
        public override String CaptureOrder(Order o)
        {
            String result = AppLogic.ro_OK;

            bool useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";
            String  TransID    = o.AuthorizationPNREF;
            int     CustomerID = o.CustomerID;
            Decimal OrderTotal = o.OrderBalance;

            String Merchant_User_Name = GetIDepositAppConfig("USERNAME");

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("Transaction_Type=PRE_AUTH_COMPLETE");
            transactionCommand.Append("&Merchant_User_Name=" + Merchant_User_Name);
            transactionCommand.Append("&Charge_Amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&Transaction_Id=" + TransID);

            o.CaptureTXCommand = transactionCommand.ToString();

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Failed. Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    byte[] data = encoding.GetBytes(transactionCommand.ToString());

                    // Prepare web request...
                    String         AuthServer = GetIDepositAppConfig("URL");
                    HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);
                    myRequest.Method        = "POST";
                    myRequest.ContentType   = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = data.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    // Send the data.
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                    // get the response
                    WebResponse myResponse;
                    String      rawResponseString = String.Empty;
                    try
                    {
                        myResponse = myRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                        {
                            rawResponseString = sr.ReadToEnd();
                            // Close and clean up the StreamReader
                            sr.Close();
                        }
                        myResponse.Close();
                    }
                    catch
                    {
                        rawResponseString = "";
                    }

                    // rawResponseString now has gateway response
                    String authNum        = CommonLogic.ExtractToken(rawResponseString, "<AuthorizationNumber>", "</AuthorizationNumber>");
                    String transactionID  = CommonLogic.ExtractToken(rawResponseString, "<TransactionId>", "</TransactionId>");
                    String AVSStatus      = CommonLogic.ExtractToken(rawResponseString, "<AVSStatus>", "</AVSStatus>");
                    String CVStatus       = CommonLogic.ExtractToken(rawResponseString, "<CVStatus>", "</CVStatus>");
                    String returnCode     = CommonLogic.ExtractToken(rawResponseString, "<ReturnCode>", "</ReturnCode>");
                    String responseStatus = CommonLogic.ExtractToken(rawResponseString, "<Status>", "</Status>");
                    String statusMsg      = CommonLogic.ExtractToken(rawResponseString, "<StatusMessage>", "</StatusMessage>");

                    o.CaptureTXResult = rawResponseString;


                    if (returnCode == "1")
                    {
                        result = AppLogic.ro_OK;
                    }
                    else if (returnCode == "0")
                    {
                        result = "Failed. " + statusMsg;
                    }
                    else
                    {
                        result = "Failed. Error calling iDeposit.net gateway. " + statusMsg;
                    }
                }
                catch
                {
                    result = "Failed. NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
예제 #10
0
        // if RefundAmount == 0.0M, then then ENTIRE order amount will be refunded!
        public override String RefundOrder(int OriginalOrderNumber, int NewOrderNumber, decimal RefundAmount, String RefundReason, Address UseBillingAddress)
        {
            String result      = AppLogic.ro_OK;
            int    OrderNumber = 0;

            if (NewOrderNumber == 0)
            {
                OrderNumber = OriginalOrderNumber;
            }
            else
            {
                OrderNumber = NewOrderNumber;
            }

            DB.ExecuteSQL("update orders set RefundTXCommand=NULL, RefundTXResult=NULL where OrderNumber=" + OriginalOrderNumber.ToString());
            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            int     CustomerID          = 0;
            Decimal OrderTotal          = Decimal.Zero;
            Decimal RefundTotal         = Decimal.Zero;
            String  CardNumber          = String.Empty;
            String  CardExpM            = String.Empty;
            String  CardExpY            = String.Empty;

            using (SqlConnection dbconn = DB.dbConn())
            {
                dbconn.Open();
                using (IDataReader rs = DB.GetRS("select * from Orders  with (NOLOCK)  where OrderNumber=" + OriginalOrderNumber.ToString(), dbconn))
                {
                    if (rs.Read())
                    {
                        TransID    = DB.RSField(rs, "AuthorizationPNREF");
                        CustomerID = DB.RSFieldInt(rs, "CustomerID");
                        OrderTotal = DB.RSFieldDecimal(rs, "OrderTotal");
                        CardNumber = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNumber.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNumber = DB.RSField(rs, "CardNumber");
                        }
                        CardExpM = DB.RSField(rs, "CardExpirationMonth");
                        CardExpY = DB.RSField(rs, "CardExpirationYear").Substring(2, 2);
                        //For full refunds a value of zero is passed, so use the order total
                        RefundTotal = CommonLogic.IIF(RefundAmount > 0, RefundAmount, OrderTotal);
                    }
                }
            }

            if (CardNumber == AppLogic.ro_CCNotStoredString || CardNumber.Length == 0)
            {
                return("Failed. To process Refunds with iDeposit using the store front, you must store the credit card numbers in the database. See AppConfig variable StoreCCInDB.");
            }

            String Merchant_User_Name = GetIDepositAppConfig("USERNAME");
            String Merchant_Password  = GetIDepositAppConfig("PASSWORD");
            String Clerk_Id           = GetIDepositAppConfig("CLERKID");

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("Transaction_Type=RETURN");
            transactionCommand.Append("&Merchant_User_Name=" + Merchant_User_Name);
            transactionCommand.Append("&Merchant_Password="******"&Charge_Amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(RefundTotal));
            transactionCommand.Append("&Transaction_Id=" + TransID);
            transactionCommand.Append("&Credit_Card_Number=" + CardNumber);
            transactionCommand.Append("&Credit_Card_Exp_Date=" + CardExpM + CardExpY);
            transactionCommand.Append("&Tracking_Number=" + OrderNumber.ToString());
            transactionCommand.Append("&Clerk_Id=" + HttpContext.Current.Server.UrlEncode(Clerk_Id));
            transactionCommand.Append("&Station_Id=" + CommonLogic.CustomerIpAddress());
            transactionCommand.Append("&Comments=" + HttpContext.Current.Server.UrlEncode(AppLogic.AppConfig("StoreName") + " Order " + OrderNumber.ToString() + " Refund Reason: " + RefundReason));

            String PasswordToken            = "Merchant_Password="******"Merchant_Password="******"*".PadLeft(Merchant_Password.Length, '*');
            String CardToken            = String.Format("Credit_Card_Number={0}", CardNumber);
            String CardTokenReplacement = String.Format("Credit_Card_Number={0}", "x".PadLeft(CardNumber.Length, 'x'));

            DB.ExecuteSQL("update orders set RefundTXCommand=" + DB.SQuote(transactionCommand.ToString().Replace(CardToken, CardTokenReplacement).Replace(PasswordToken, PasswordTokenReplacement)) + " where OrderNumber=" + OriginalOrderNumber.ToString());

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Failed. Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    byte[] data = encoding.GetBytes(transactionCommand.ToString());

                    // Prepare web request...
                    String         AuthServer = GetIDepositAppConfig("URL");
                    HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);
                    myRequest.Method        = "POST";
                    myRequest.ContentType   = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = data.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    // Send the data.
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                    // get the response
                    WebResponse myResponse;
                    String      rawResponseString = String.Empty;
                    try
                    {
                        myResponse = myRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                        {
                            rawResponseString = sr.ReadToEnd();
                            // Close and clean up the StreamReader
                            sr.Close();
                        }
                        myResponse.Close();
                    }
                    catch
                    {
                        rawResponseString = "";
                    }

                    // rawResponseString now has gateway response
                    String authNum        = CommonLogic.ExtractToken(rawResponseString, "<AuthorizationNumber>", "</AuthorizationNumber>");
                    String transactionID  = CommonLogic.ExtractToken(rawResponseString, "<TransactionId>", "</TransactionId>");
                    String AVSStatus      = CommonLogic.ExtractToken(rawResponseString, "<AVSStatus>", "</AVSStatus>");
                    String CVStatus       = CommonLogic.ExtractToken(rawResponseString, "<CVStatus>", "</CVStatus>");
                    String returnCode     = CommonLogic.ExtractToken(rawResponseString, "<ReturnCode>", "</ReturnCode>");
                    String responseStatus = CommonLogic.ExtractToken(rawResponseString, "<Status>", "</Status>");
                    String statusMsg      = CommonLogic.ExtractToken(rawResponseString, "<StatusMessage>", "</StatusMessage>");

                    DB.ExecuteSQL("update orders set RefundTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OrderNumber.ToString());

                    if (returnCode == "1")
                    {
                        result = AppLogic.ro_OK;
                    }
                    else if (returnCode == "0")
                    {
                        result = "Failed. " + statusMsg;
                    }
                    else
                    {
                        result = "Failed. Error calling iDeposit.net gateway. " + statusMsg;
                    }
                }
                catch
                {
                    result = "Failed. NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
예제 #11
0
        public override String VoidOrder(int OrderNumber)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set VoidTXCommand=NULL, VoidTXResult=NULL where OrderNumber=" + OrderNumber.ToString());
            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            int     CustomerID          = 0;
            Decimal OrderTotal          = Decimal.Zero;

            using (SqlConnection dbconn = DB.dbConn())
            {
                dbconn.Open();
                using (IDataReader rs = DB.GetRS("select AuthorizationPNREF,CustomerID,OrderTotal from Orders  with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), dbconn))
                {
                    if (rs.Read())
                    {
                        TransID    = DB.RSField(rs, "AuthorizationPNREF");
                        CustomerID = DB.RSFieldInt(rs, "CustomerID");
                        OrderTotal = DB.RSFieldDecimal(rs, "OrderTotal");
                    }
                }
            }

            String Merchant_User_Name = GetIDepositAppConfig("USERNAME");

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("Transaction_Type=VOID");
            transactionCommand.Append("&Merchant_User_Name=" + Merchant_User_Name);
            transactionCommand.Append("&Charge_Amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&Transaction_Id=" + TransID);

            DB.ExecuteSQL("update orders set VoidTXCommand=" + DB.SQuote(transactionCommand.ToString()) + " where OrderNumber=" + OrderNumber.ToString());

            if (TransID.Length == 0 || TransID == "0")
            {
                result = "Failed. Invalid or Empty Transaction ID";
            }
            else
            {
                try
                {
                    byte[] data = encoding.GetBytes(transactionCommand.ToString());

                    // Prepare web request...
                    String         AuthServer = GetIDepositAppConfig("URL");
                    HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);
                    myRequest.Method        = "POST";
                    myRequest.ContentType   = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = data.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    // Send the data.
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                    // get the response
                    WebResponse myResponse;
                    String      rawResponseString = String.Empty;
                    try
                    {
                        myResponse = myRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                        {
                            rawResponseString = sr.ReadToEnd();
                            // Close and clean up the StreamReader
                            sr.Close();
                        }
                        myResponse.Close();
                    }
                    catch
                    {
                        rawResponseString = "";
                    }

                    // rawResponseString now has gateway response
                    String authNum        = CommonLogic.ExtractToken(rawResponseString, "<AuthorizationNumber>", "</AuthorizationNumber>");
                    String transactionID  = CommonLogic.ExtractToken(rawResponseString, "<TransactionId>", "</TransactionId>");
                    String AVSStatus      = CommonLogic.ExtractToken(rawResponseString, "<AVSStatus>", "</AVSStatus>");
                    String CVStatus       = CommonLogic.ExtractToken(rawResponseString, "<CVStatus>", "</CVStatus>");
                    String returnCode     = CommonLogic.ExtractToken(rawResponseString, "<ReturnCode>", "</ReturnCode>");
                    String responseStatus = CommonLogic.ExtractToken(rawResponseString, "<Status>", "</Status>");
                    String statusMsg      = CommonLogic.ExtractToken(rawResponseString, "<StatusMessage>", "</StatusMessage>");

                    DB.ExecuteSQL("update orders set VoidTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OrderNumber.ToString());

                    if (returnCode == "1")
                    {
                        result = AppLogic.ro_OK;
                    }
                    else if (returnCode == "0")
                    {
                        result = "Failed. " + statusMsg;
                    }
                    else
                    {
                        result = "Failed. Error calling iDeposit.net gateway. " + statusMsg;
                    }
                }
                catch
                {
                    result = "Failed. NO RESPONSE FROM GATEWAY!";
                }
            }
            return(result);
        }
예제 #12
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTHONLY", "SALE") + "</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + OrderNumber.ToString().PadLeft(18, '0') + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + UseBillingAddress.CardNumber + "</CardNum>");
            transactionCommand.Append("<CVV2>" + CardExtraCode + "</CVV2>");
            transactionCommand.Append("<CardExpMonth>" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2) + "</CardExpYear>");
            transactionCommand.Append("<CardName>" + UseBillingAddress.FirstName + " " + UseBillingAddress.LastName + "</CardName>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(",", "").Replace(".", "") + "</TotalAmount>");
            transactionCommand.Append("<BillingAddress>" + XmlCommon.XmlEncode(UseBillingAddress.Address1) + "</BillingAddress>");
            transactionCommand.Append("<BillingCity>" + XmlCommon.XmlEncode(UseBillingAddress.City) + "</BillingCity>");
            transactionCommand.Append("<BillingStateProv>" + XmlCommon.XmlEncode(UseBillingAddress.State) + "</BillingStateProv>");
            transactionCommand.Append("<BillingPostalCode>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</BillingPostalCode>");
            //transactionCommand.Append("<BillingCountry>" + UseBillingAddress.Country + "</BillingCountry>");
            transactionCommand.Append("<BillingPhone>" + XmlCommon.XmlEncode(UseBillingAddress.Phone) + "</BillingPhone>");
            transactionCommand.Append("<Email>" + XmlCommon.XmlEncode(UseBillingAddress.EMail) + "</Email>");
            transactionCommand.Append("</JetPay>");

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response
            TransactionResponse = rawResponseString;

            String sql       = String.Empty;
            String replyCode = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            //String responseCode = CommonLogic.ExtractToken(rawResponseString,"<RespCode>","</RespCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");
            String ErrMsg       = CommonLogic.ExtractToken(rawResponseString, "<ErrMsg>", "</ErrMsg>");
            String TransID      = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");

            int idx = authResponse.IndexOf(">");

            if (idx != -1)
            {
                // pick only text out:
                authResponse = authResponse.Substring(idx + 1, authResponse.Length - idx - 1);
            }

            AuthorizationCode     = approvalCode;
            AuthorizationResult   = rawResponseString;
            AuthorizationTransID  = TransID;
            AVSResult             = String.Empty;
            TransactionCommandOut = transactionCommand.ToString();
            TransactionResponse   = String.Empty;

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                if (ErrMsg.Trim().Length > 0)
                {
                    result = "System Error: " + authResponse + ErrMsg;  //you'll only get one of these messages back
                }
                else
                {
                    result = "DECLINED: " + authResponse;
                }
            }
            return(result);
        }
예제 #13
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String CaptureOrder(Order o)
        {
            String result = AppLogic.ro_OK;

            bool useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");

            o.CaptureTXCommand = "";
            o.CaptureTXResult  = "";
            String TransID = o.AuthorizationPNREF;

            String CardNum = Security.UnmungeString(o.CardNumber, o.OrdersCCSaltField);

            if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
            {
                CardNum = o.CardNumber;
            }
            String  CardExpM    = o.CardExpirationMonth;
            String  CardExpY    = o.CardExpirationYear.Substring(2, 2);
            String  ApprvCode   = o.AuthorizationCode;
            decimal TotalAmount = o.OrderBalance;

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>CAPT</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + TransID + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");
            transactionCommand.Append("<CardExpMonth>" + CardExpM + "</CardExpMonth>");
            transactionCommand.Append("<CardExpYear>" + CardExpY + "</CardExpYear>");
            transactionCommand.Append("<Approval>" + ApprvCode + "</Approval>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount).Replace(".", "").Replace(",", "") + "</TotalAmount>");
            transactionCommand.Append("</JetPay>");

            o.CaptureTXCommand = transactionCommand.ToString();

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql          = String.Empty;
            String replyCode    = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");

            o.CaptureTXResult = rawResponseString;

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }
예제 #14
0
파일: Cybersource.cs 프로젝트: giagiigi/WE
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, AspDotNetStorefrontCore.Address UseBillingAddress, String CardExtraCode, AspDotNetStorefrontCore.Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            AVSResult             = "N/A";
            AuthorizationResult   = "N/A";
            AuthorizationCode     = "N/A";
            AuthorizationTransID  = "N/A";
            TransactionCommandOut = "N/A";
            TransactionResponse   = String.Empty;

            String signedPARes = String.Empty;
            String result      = AppLogic.ro_OK;

            CustomerSession cSession = new CustomerSession(CustomerID);

            if (cSession["3Dsecure.PaRes"].Length != 0)
            {
                signedPARes = cSession["3Dsecure.PaRes"];
                // After grabbing it, clear out the session PaRes so it won't be re-used ever again.
                cSession["3Dsecure.PaRes"] = String.Empty;
            }

            Configuration conf = new Configuration();

            conf.KeysDirectory = AppLogic.AppConfig("CYBERSOURCE.keysDirectory");
            conf.KeyFilename   = AppLogic.AppConfig("CYBERSOURCE.keyFilename");
            conf.MerchantID    = AppLogic.AppConfig("CYBERSOURCE.merchantID");
            conf.ServerURL     = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("CYBERSOURCE.LiveURL"), AppLogic.AppConfig("CYBERSOURCE.TestURL"));
            if (AppLogic.AppConfigBool("CYBERSOURCE.UsePIT"))
            {
                conf.ServerURL = AppLogic.AppConfig("CYBERSOURCE.PITURL");
            }


            RequestMessage request = new RequestMessage();

            request.clientApplication        = "AspDotNetStorefront";
            request.clientApplicationVersion = AppLogic.AppConfig("StoreVersion");
            request.clientApplicationUser    = CustomerID.ToString();

            request.merchantReferenceCode = "Order # " + OrderNumber.ToString() + " " + Localization.ToNativeDateTimeString(System.DateTime.Now);

            int  CardTypeID  = DB.GetSqlN("select CardTypeID N from CreditCardType where CardType = " + DB.SQuote(UseBillingAddress.CardType));
            bool Try3DSecure = CommonLogic.IntegerIsInIntegerList(CardTypeID, AppLogic.AppConfig("3DSECURE.CreditCardTypeIDs"));

            if (Try3DSecure)
            {
                if (signedPARes == String.Empty)
                {
                    request.payerAuthEnrollService     = new PayerAuthEnrollService();
                    request.payerAuthEnrollService.run = "true";
                    if (AppLogic.AppConfig("CYBERSOURCE.paCountryCode") != "")
                    {
                        request.payerAuthEnrollService.countryCode = AppLogic.AppConfig("CYBERSOURCE.paCountryCode");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantName") != "")
                    {
                        request.payerAuthEnrollService.merchantName = AppLogic.AppConfig("CYBERSOURCE.paMerchantName");
                    }
                    if (AppLogic.AppConfig("CYBERSOURCE.paMerchantURL") != "")
                    {
                        request.payerAuthEnrollService.merchantURL = AppLogic.AppConfig("CYBERSOURCE.paMerchantURL");
                    }
                    request.payerAuthEnrollService.httpAccept    = CommonLogic.ServerVariables("HTTP_ACCEPT");
                    request.payerAuthEnrollService.httpUserAgent = CommonLogic.ServerVariables("HTTP_USER_AGENT");
                }
                else
                {
                    request.payerAuthValidateService             = new PayerAuthValidateService();
                    request.payerAuthValidateService.signedPARes = signedPARes;
                    request.payerAuthValidateService.run         = "true";
                }
            }

            request.ccAuthService     = new CCAuthService();
            request.ccAuthService.run = "true";

            if (CAVV.Trim().Length != 0)
            {     // only gets set as a result of 3D Secure processing
                if (GetCardTypeFieldValue(UseBillingAddress.CardType) == "002")
                { // for MasterCard
                    request.ccAuthService.xid  = XID;
                    request.ccAuthService.cavv = CAVV;
                }
            }

            request.merchantID = AppLogic.AppConfig("CYBERSOURCE.merchantID");

            if (TransactionMode == TransactionModeEnum.authcapture)
            {
                request.ccCaptureService     = new CCCaptureService();
                request.ccCaptureService.run = "true";
            }

            BillTo billTo = new BillTo();

            billTo.firstName   = UseBillingAddress.FirstName;
            billTo.lastName    = UseBillingAddress.LastName;
            billTo.company     = UseBillingAddress.Company;
            billTo.street1     = UseBillingAddress.Address1;
            billTo.street2     = UseBillingAddress.Address2;
            billTo.city        = UseBillingAddress.City;
            billTo.state       = UseBillingAddress.State;
            billTo.postalCode  = UseBillingAddress.Zip;
            billTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country);
            billTo.phoneNumber = UseBillingAddress.Phone.PadRight(6, '1');
            billTo.email       = CommonLogic.IIF(UseBillingAddress.EMail.Length > 2, UseBillingAddress.EMail, "*****@*****.**");
            billTo.ipAddress   = CommonLogic.CustomerIpAddress();
            request.billTo     = billTo;

            if (UseShippingAddress != null)
            {
                ShipTo ShipTo = new ShipTo();
                ShipTo.firstName   = UseShippingAddress.FirstName;
                ShipTo.lastName    = UseShippingAddress.LastName;
                ShipTo.company     = UseShippingAddress.Company;
                ShipTo.street1     = UseShippingAddress.Address1;
                ShipTo.street2     = UseShippingAddress.Address2;
                ShipTo.city        = UseShippingAddress.City;
                ShipTo.state       = UseShippingAddress.State;
                ShipTo.postalCode  = UseShippingAddress.Zip;
                ShipTo.country     = AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country);
                ShipTo.phoneNumber = UseShippingAddress.Phone.PadRight(6, '1');
                ShipTo.email       = CommonLogic.IIF(UseShippingAddress.EMail.Length > 2, UseShippingAddress.EMail, "*****@*****.**");
                request.shipTo     = ShipTo;
            }

            Card card = new Card();

            card.accountNumber = UseBillingAddress.CardNumber;
            if (CardExtraCode.Trim().Length != 0)
            {
                card.cvIndicator = "1";
                card.cvNumber    = CardExtraCode;
            }
            else
            {
                card.cvIndicator = "0";
            }

            if (!String.IsNullOrEmpty(UseBillingAddress.CardStartDate) && UseBillingAddress.CardStartDate != "00")
            {
                card.startMonth = UseBillingAddress.CardStartDate.Substring(0, 2);
                card.startYear  = UseBillingAddress.CardStartDate.Substring(4, 2);
            }

            if (UseBillingAddress.CardIssueNumber.Length != 0)
            {
                card.issueNumber = UseBillingAddress.CardIssueNumber;
            }
            card.expirationMonth = UseBillingAddress.CardExpirationMonth;
            card.expirationYear  = UseBillingAddress.CardExpirationYear;

            if (Try3DSecure)
            {
                card.cardType = GetCardTypeFieldValue(UseBillingAddress.CardType);
                if (card.cardType == "000")
                {
                    return(" Error in configuration. Card type " + UseBillingAddress.CardType + " is not recognized by the gateway.");
                }
            }

            request.card = card;

            request.item = new Item[1];
            Item the_item = new Item();

            the_item.id        = "0";
            the_item.unitPrice = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
            request.item[0]    = the_item;

            PurchaseTotals ptotal = new PurchaseTotals();

            ptotal.currency         = Localization.StoreCurrency();                                         // Currency REQUIRED
            ptotal.grandTotalAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal); // Not needed - can use instead of item price, I think it's better..
            request.purchaseTotals  = ptotal;                                                               // Neccessary

            result = "ERROR: ";


            try
            {
                ReplyMessage reply = SoapClient.RunTransaction(conf, request);

                if (Try3DSecure && request.payerAuthEnrollService != null)
                {
                    if (request.payerAuthEnrollService.run == "true")
                    { // we have some data that needs stored
                        string LookupResult = String.Empty;
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.paReq != null &&
                            reply.payerAuthEnrollReply.paReq.Length > 0)
                        { // will be null if card not enrolled
                            // the paReq comes back encoded, Streamline requires it to be decoded.
                            string sPAReq = CommonLogic.UnzipBase64DataToString(reply.payerAuthEnrollReply.paReq);
                            LookupResult += "paReq=" + XmlCommon.PrettyPrintXml(sPAReq) + System.Environment.NewLine;
                        }
                        if (reply.payerAuthEnrollReply != null &&
                            reply.payerAuthEnrollReply.proofXML != null)
                        {
                            /****************************************************************
                            *  Store the complete proofXML whenever it is                  *
                            *  returned. If you ever need to show proof of                 *
                            *  enrollment checking, you will need to parse the string      *
                            *  for the information required by the card association.       *
                            ****************************************************************/
                            LookupResult += "proofXML data =";
                            LookupResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(reply.payerAuthEnrollReply.proofXML);
                        }
                        if (LookupResult != String.Empty)
                        { // encode it to store in the session, it will be decoded before being saved to the database
                            byte[] str = Encoding.UTF8.GetBytes(LookupResult);
                            cSession["3DSecure.LookupResult"] = Convert.ToBase64String(str);
                        }
                    }
                }

                if (reply.decision == "REJECT" && reply.reasonCode == "475")
                { // card enrolled, must perform 3D Secure processing (reasonCode == 475)
                    cSession["3DSecure.CustomerID"]  = CustomerID.ToString();
                    cSession["3DSecure.OrderNumber"] = OrderNumber.ToString();
                    cSession["3DSecure.MD"]          = OrderNumber.ToString();
                    cSession["3DSecure.ACSUrl"]      = reply.payerAuthEnrollReply.acsURL;
                    cSession["3DSecure.paReq"]       = reply.payerAuthEnrollReply.paReq;
                    cSession["3DSecure.XID"]         = reply.payerAuthEnrollReply.xid;
                    cSession.UpdateCustomerSession(null, null);
                    result = AppLogic.ro_3DSecure; // This is what triggers the 3D Secure IFRAME to be used.
                    return(result);
                }

                if (reply.decision == "ACCEPT" || reply.decision == "REVIEW")
                {
                    result = AppLogic.ro_OK;
                    if (AppLogic.TransactionModeIsAuthCapture())
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.ccCaptureReply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    else
                    {
                        AVSResult            = reply.ccAuthReply.avsCode;
                        AuthorizationResult  = reply.reasonCode;
                        AuthorizationCode    = reply.ccAuthReply.authorizationCode;
                        AuthorizationTransID = reply.requestID;
                    }
                    if (signedPARes.Length > 0)
                    {
                        if (reply.payerAuthValidateReply != null)
                        {
                            if (reply.payerAuthValidateReply.ucafAuthenticationData != null)
                            { // MasterCard SecureCode
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.ucafAuthenticationData;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.ucafCollectionIndicator;
                            }
                            else
                            { // Visa VBV
                                AuthorizationResult += System.Environment.NewLine + "CAVV: " + reply.payerAuthValidateReply.cavv;
                                AuthorizationResult += System.Environment.NewLine + "ECI: " + reply.payerAuthValidateReply.eci;
                            }
                        }
                        AuthorizationResult += System.Environment.NewLine + "signedPARes: ";
                        // Streamline requires saving the decoded PARes to the database
                        string sPARes = CommonLogic.UnzipBase64DataToString(signedPARes);

                        // zap the signature since it is long and we don't need it
                        String t1  = "<Signature ";
                        String t2  = "</Signature>";
                        String sig = t1 + CommonLogic.ExtractToken(sPARes, t1, t2) + t2;
                        AuthorizationResult += System.Environment.NewLine + XmlCommon.PrettyPrintXml(sPARes.Replace(sig, ""));
                    }
                }
                else
                {
                    result = "Your transaction was NOT approved, reason code: " + reply.reasonCode + ". ";
                    if (reply.reasonCode == "476" && reply.payerAuthValidateReply != null)
                    {
                        result += reply.payerAuthValidateReply.authenticationStatusMessage
                                  + ". Please try another payment method.";
                    }

                    else
                    {
                        result += GetReasonCodeDescription(reply.reasonCode);

                        if (reply.missingField != null)
                        {
                            foreach (string fieldname in reply.missingField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }

                        if (reply.invalidField != null)
                        {
                            foreach (string fieldname in reply.invalidField)
                            {
                                result += "[" + fieldname + "]";
                            }
                        }
                    }
                }
            }
            catch (SignException se)
            {
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option. "
                          + String.Format("Failed to sign the request with error code {0} and message {1}.", DB.SQuote(se.ErrorCode.ToString()), DB.SQuote(se.Message));
            }
            catch (SoapHeaderException she)
            {
                result += String.Format("A SOAP header exception was returned with fault code {0} and message {1}.", DB.SQuote(she.Code.ToString()), DB.SQuote(she.Message));
            }
            catch (SoapBodyException sbe)
            {
                result += String.Format("A SOAP body exception was returned with fault code {0} and message {1}.", DB.SQuote(sbe.Code.ToString()), DB.SQuote(sbe.Message));
            }
            catch (WebException we)
            {
                result += String.Format("Failed to get a response with status {0} and mmessage {1}", DB.SQuote(we.Status.ToString()), DB.SQuote(we.Message));
            }
            catch (Exception ex)
            {
                // See requirements at the top of this file.
                result += "Error calling Cybersource gateway. Please retry your order in a few minutes or select another checkout payment option.";
                result += " Error message: Make sure the required components for Cybersource are installed on the server. " + ex.Message;
                result += " <> " + ex.ToString();
            }
            return(result);
        }
예제 #15
0
        public override String ProcessCard(int OrderNumber, int CustomerID, Decimal OrderTotal, bool useLiveTransactions, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, Address UseShippingAddress, String CAVV, String ECI, String XID, out String AVSResult, out String AuthorizationResult, out String AuthorizationCode, out String AuthorizationTransID, out String TransactionCommandOut, out String TransactionResponse)
        {
            String result = AppLogic.ro_OK;

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;

            String Merchant_User_Name = GetIDepositAppConfig("USERNAME");
            String Clerk_Id           = GetIDepositAppConfig("CLERKID");


            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("Transaction_Type=" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "PRE_AUTH", "SALE"));

            transactionCommand.Append("&Merchant_User_Name=" + Merchant_User_Name);
            transactionCommand.Append("&Comments=" + HttpContext.Current.Server.UrlEncode(AppLogic.AppConfig("StoreName") + " Order " + OrderNumber.ToString()));
            transactionCommand.Append("&Charge_Amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&Credit_Card_Type=" + GetCardTypeFieldValue(UseBillingAddress.CardType));
            transactionCommand.Append("&Credit_Card_Number=" + UseBillingAddress.CardNumber);
            if (CardExtraCode.Length != 0)
            {
                transactionCommand.Append("&CV_Security_Code=" + CardExtraCode.Trim());
            }
            transactionCommand.Append("&Credit_Card_Exp_Date=" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2));
            transactionCommand.Append("&Tracking_Number=" + OrderNumber.ToString());
            transactionCommand.Append("&CardHolder_Name=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.CardName));
            transactionCommand.Append("&AVS_Street=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Address1));
            transactionCommand.Append("&AVS_Zip_Code=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Zip));
            transactionCommand.Append("&Clerk_Id=" + HttpContext.Current.Server.UrlEncode(Clerk_Id));
            transactionCommand.Append("&Station_Id=" + CommonLogic.CustomerIpAddress());


            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            try
            {
                String AuthServer        = GetIDepositAppConfig("URL");
                String rawResponseString = String.Empty;

                int  MaxTries       = AppLogic.AppConfigUSInt("GatewayRetries") + 1;
                int  CurrentTry     = 0;
                bool CallSuccessful = false;
                do
                {
                    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(AuthServer);
                    myRequest.Method        = "POST";
                    myRequest.ContentType   = "application/x-www-form-urlencoded";
                    myRequest.ContentLength = data.Length;
                    Stream newStream = myRequest.GetRequestStream();
                    // Send the data.
                    newStream.Write(data, 0, data.Length);
                    newStream.Close();
                    // get the response
                    WebResponse myResponse;

                    CurrentTry++;
                    try
                    {
                        myResponse = myRequest.GetResponse();
                        using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
                        {
                            rawResponseString = sr.ReadToEnd();
                            sr.Close();
                        }
                        myResponse.Close();
                        CallSuccessful = true;
                    }
                    catch
                    {
                        CallSuccessful = false;
                    }
                }while (!CallSuccessful && CurrentTry < MaxTries);


                // rawResponseString now has gateway response
                TransactionResponse = rawResponseString;

                String authNum        = CommonLogic.ExtractToken(rawResponseString, "<AuthorizationNumber>", "</AuthorizationNumber>");
                String transactionID  = CommonLogic.ExtractToken(rawResponseString, "<TransactionId>", "</TransactionId>");
                String AVSStatus      = CommonLogic.ExtractToken(rawResponseString, "<AVSStatus>", "</AVSStatus>");
                String CVStatus       = CommonLogic.ExtractToken(rawResponseString, "<CVStatus>", "</CVStatus>");
                String returnCode     = CommonLogic.ExtractToken(rawResponseString, "<ReturnCode>", "</ReturnCode>");
                String responseStatus = CommonLogic.ExtractToken(rawResponseString, "<Status>", "</Status>");
                String statusMsg      = CommonLogic.ExtractToken(rawResponseString, "<StatusMessage>", "</StatusMessage>");

                AuthorizationTransID = transactionID;
                AuthorizationCode    = authNum;
                AVSResult            = AVSStatus;
                if (CVStatus.Length > 0 && CardExtraCode.Length != 0)
                {
                    AVSResult += ", CV Result: " + CVStatus;
                }
                AuthorizationResult = responseStatus;

                TransactionCommandOut = transactionCommand.ToString();


                if (returnCode == "1")
                {
                    result = AppLogic.ro_OK;
                }
                else if (returnCode == "0")
                {
                    result = statusMsg;
                }
                else
                {
                    result = "Error calling iDeposit.net gateway. Please retry your order in a few minutes or select another checkout payment option.";
                }
            }
            catch
            {
                result = "Error calling iDeposit.net gateway. Please retry your order in a few minutes or select another checkout payment option.";
            }
            return(result);
        }
예제 #16
0
        string ProcessCardinalReturn(Customer customer)
        {
            var cart    = CachedShoppingCartProvider.Get(customer, CartTypeEnum.ShoppingCart, AppLogic.StoreID());
            var payload = customer.ThisCustomerSession["Cardinal.Payload"];
            var paRes   = CommonLogic.FormCanBeDangerousContent("PaRes")
                          .Replace(" ", "")
                          .Replace("\r", "")
                          .Replace("\n", "");
            var transactionId = customer.ThisCustomerSession["Cardinal.TransactionID"];
            var orderNumber   = customer.ThisCustomerSession.SessionUSInt("Cardinal.OrderNumber");

            if (orderNumber == 0 ||
                string.IsNullOrEmpty(payload) ||
                string.IsNullOrEmpty(transactionId))
            {
                NoticeProvider.PushNotice("Bank verification was incomplete or canceled. Please retry credit card entry", NoticeType.Failure);
                ClearThreeDSecureSessionInfo(customer);
                return(Url.Action(ActionNames.Index, ControllerNames.Checkout));
            }

            var cardinalAuthenticateResult = string.Empty;
            var paResStatus           = string.Empty;
            var signatureVerification = string.Empty;
            var errorNumber           = string.Empty;
            var errorDescription      = string.Empty;

            var AuthResult = Cardinal.PreChargeAuthenticate(orderNumber,
                                                            paRes,
                                                            transactionId,
                                                            out paResStatus,
                                                            out signatureVerification,
                                                            out errorNumber,
                                                            out errorDescription,
                                                            out cardinalAuthenticateResult);

            customer.ThisCustomerSession["Cardinal.AuthenticateResult"] = cardinalAuthenticateResult;

            if (((paResStatus == "Y" || paResStatus == "A") && signatureVerification == "Y") ||         //Great success
                (paResStatus == "U" && errorNumber == "0"))                     //Signature verification failed but Cardinal says to take it anyway
            {
                var cardExtraCode = CommonLogic.ExtractToken(customer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Cavv>", "</Cavv>");
                var eciFlag       = CommonLogic.ExtractToken(customer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<EciFlag>", "</EciFlag>");
                var XID           = CommonLogic.ExtractToken(customer.ThisCustomerSession["Cardinal.AuthenticateResult"], "<Xid>", "</Xid>");

                var billingAddress = new Address();
                billingAddress.LoadByCustomer(customer.CustomerID, customer.PrimaryBillingAddressID, AddressTypes.Billing);

                var status = Gateway.MakeOrder(string.Empty, AppLogic.TransactionMode(), cart, orderNumber, cardExtraCode, eciFlag, XID, string.Empty);

                if (status != AppLogic.ro_OK)
                {
                    NoticeProvider.PushNotice(status, NoticeType.Failure);
                    ClearThreeDSecureSessionInfo(customer);
                    return(Url.Action(ActionNames.Index, ControllerNames.Checkout));
                }

                DB.ExecuteSQL(string.Format("UPDATE Orders SET CardinalLookupResult = {0}, CardinalAuthenticateResult = {1} WHERE OrderNumber= {2}",
                                            DB.SQuote(customer.ThisCustomerSession["Cardinal.LookupResult"]),
                                            DB.SQuote(customer.ThisCustomerSession["Cardinal.AuthenticateResult"]),
                                            orderNumber));

                return(Url.Action(
                           ActionNames.Confirmation,
                           ControllerNames.CheckoutConfirmation,
                           new { @orderNumber = orderNumber }));
            }

            //If we made it this far, either something failed or Authorization or Signature Verification didn't pass on Cardinal's end
            NoticeProvider.PushNotice("We were unable to verify your credit card. Please retry your credit card or choose a different payment type.", NoticeType.Failure);
            ClearThreeDSecureSessionInfo(customer);
            return(Url.Action(ActionNames.Index, ControllerNames.Checkout));
        }
예제 #17
0
파일: JetPay.cs 프로젝트: lulzzz/BrandStore
        public override String VoidOrder(int OrderNumber)
        {
            String result = AppLogic.ro_OK;

            DB.ExecuteSQL("update orders set VoidTXCommand=NULL, VoidTXResult=NULL where OrderNumber=" + OrderNumber.ToString());
            bool    useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            String  TransID             = String.Empty;
            String  CardNum             = String.Empty;
            String  ApprvCode           = String.Empty;
            decimal TotalAmount         = 0;

            using (SqlConnection conn = DB.dbConn())
            {
                conn.Open();
                using (IDataReader rs = DB.GetRS("select * from orders   with (NOLOCK)  where OrderNumber=" + OrderNumber.ToString(), conn))
                {
                    if (rs.Read())
                    {
                        TransID     = DB.RSField(rs, "AuthorizationPNREF");
                        ApprvCode   = DB.RSField(rs, "AuthorizationCode");
                        TotalAmount = DB.RSFieldDecimal(rs, "OrderTotal");
                        CardNum     = Security.UnmungeString(DB.RSField(rs, "CardNumber"), rs[AppLogic.AppConfig("OrdersCCSaltField")].ToString());
                        if (CardNum.StartsWith(Security.ro_DecryptFailedPrefix, StringComparison.InvariantCultureIgnoreCase))
                        {
                            CardNum = DB.RSField(rs, "CardNumber");
                        }
                    }
                }
            }

            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<JetPay><TransactionType>VOID</TransactionType>\n");
            transactionCommand.Append("<MerchantID>" + AppLogic.AppConfig("JETPAY_MERCHANTID") + "</MerchantID>\n");
            transactionCommand.Append("<TransactionID>" + TransID + "</TransactionID>\n");
            transactionCommand.Append("<CardNum>" + CardNum + "</CardNum>");
            transactionCommand.Append("<Approval>" + ApprvCode + "</Approval>");
            transactionCommand.Append("<TotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(TotalAmount).Replace(".", "").Replace(",", "") + "</TotalAmount>");
            transactionCommand.Append("</JetPay>");

            DB.ExecuteSQL("update orders set VoidTXCommand=" + DB.SQuote(transactionCommand.ToString()) + " where OrderNumber=" + OrderNumber.ToString());

            byte[] data = encoding.GetBytes(transactionCommand.ToString());

            // Prepare web request...
            String         AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("JETPAY_LIVE_SERVER"), AppLogic.AppConfig("JETPAY_TEST_SERVER"));
            HttpWebRequest myRequest  = (HttpWebRequest)WebRequest.Create(AuthServer);

            myRequest.Headers.Add("MIME-Version", "1.0");
            myRequest.Headers.Add("Request-number", "1");
            myRequest.Headers.Add("Content-transfer-encoding", "text");
            myRequest.Headers.Add("Document-type", "Request");
            myRequest.ContentType   = "text/xml";
            myRequest.ContentLength = data.Length;
            myRequest.Method        = "POST";
            Stream newStream = myRequest.GetRequestStream();

            // Send the data.
            newStream.Write(data, 0, data.Length);
            newStream.Close();
            // get the response
            WebResponse myResponse;

            myResponse = myRequest.GetResponse();
            String rawResponseString = String.Empty;

            using (StreamReader sr = new StreamReader(myResponse.GetResponseStream()))
            {
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
            }
            myResponse.Close();

            // rawResponseString now has gateway response

            String sql          = String.Empty;
            String replyCode    = CommonLogic.ExtractToken(rawResponseString, "<ActionCode>", "</ActionCode>");
            String approvalCode = CommonLogic.ExtractToken(rawResponseString, "<Approval>", "</Approval>");
            String authResponse = CommonLogic.ExtractToken(rawResponseString, "<ResponseText>", "</ResponseText>");

            TransID = CommonLogic.ExtractToken(rawResponseString, "<TransactionID>", "</TransactionID>");


            DB.ExecuteSQL("update orders set VoidTXResult=" + DB.SQuote(rawResponseString) + " where OrderNumber=" + OrderNumber.ToString());

            if (Convert.ToInt32(replyCode) == 0)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
            }
            return(result);
        }