예제 #1
0
 public override string ProcessECheck(
     int orderNumber,
     int customerId,
     decimal orderTotal,
     bool useLiveTransactions,
     TransactionModeEnum transactionMode,
     Address useBillingAddress,
     Address useShippingAddress,
     out string avsResult,
     out string authorizationResult,
     out string authorizationCode,
     out string authorizationTransId,
     out string transactionCommandOut,
     out string transactionResponse)
 {
     return(AcceptJsProcessCardOrECheck(
                customerId,
                orderTotal,
                useLiveTransactions,
                transactionMode,
                out avsResult,
                out authorizationResult,
                out authorizationCode,
                out authorizationTransId,
                out transactionCommandOut,
                out transactionResponse));
 }
예제 #2
0
        public virtual 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)
        {
            AVSResult             = string.Empty;
            AuthorizationResult   = string.Empty;
            AuthorizationCode     = string.Empty;
            AuthorizationTransID  = string.Empty;
            TransactionCommandOut = string.Empty;
            TransactionResponse   = string.Empty;

            return(string.Empty);
        }
예제 #3
0
 public override string ProcessCard(
     int orderNumber,
     int customerId,
     decimal orderTotal,
     bool useLiveTransactions,
     TransactionModeEnum transactionMode,
     AspDotNetStorefrontCore.Address billingAddress,
     string cardExtraCode,
     AspDotNetStorefrontCore.Address shippingAddress,
     string cavv,
     string eci,
     string xid,
     out string avsResult,
     out string authorizationResult,
     out string authorizationCode,
     out string authorizationTransId,
     out string transactionCommandOut,
     out string transactionResponse)
 {
     return(AcceptJsProcessCardOrECheck(
                customerId,
                orderTotal,
                useLiveTransactions,
                transactionMode,
                out avsResult,
                out authorizationResult,
                out authorizationCode,
                out authorizationTransId,
                out transactionCommandOut,
                out transactionResponse));
 }
        /// <summary>
        /// Instantiates a new instance of the GatewayTransaction object
        /// </summary>
        /// <param name="gwToUse">The payment gateway you wish to use.
        /// This should be a cleaned value (no spaces or periods) and exactly match the name of the payment gateway class to call (case insensitive)</param>
        /// <param name="orderNumber">The order number to process</param>
        /// <param name="customerId">The customer id of the customer placing the order</param>
        /// <param name="orderTotal">The order total to process</param>
        /// <param name="billingAddress">The billing address associated with the order</param>
        /// <param name="shippingAddress">The shipping address associated with the order</param>
        /// <param name="cv2">The card CV2 code (card extra code)</param>
        /// <param name="eci">The ECI code (used for VBV/3D Secure transactions)</param>
        /// <param name="transactionId">The XID code (used for VBV/3D Secure transactions)</param>
        public GatewayTransaction(
            int orderNumber,
            int customerId,
            decimal orderTotal,
            Address billingAddress,
            Address shippingAddress,
            string cavv,
            string cv2,
            string eci,
            string transactionId,
            TransactionModeEnum transactionMode)
        {
            m_orderNumber         = orderNumber;
            m_customerID          = customerId;
            m_orderTotal          = orderTotal;
            m_useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            m_transactionMode     = transactionMode;
            m_billingAddress      = billingAddress;

            if (shippingAddress != null)
            {
                m_shippingAddress = shippingAddress;
            }
            else
            {
                m_shippingAddress = billingAddress;
            }

            m_cavv = cavv;
            m_cv2  = cv2;
            m_eci  = eci;
            m_xid  = transactionId;
        }
예제 #5
0
 public abstract 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);
예제 #6
0
        /// <summary>
        /// Instantiates a new instance of the GatewayTransaction object
        /// </summary>
        /// <param name="gwToUse">The payment gateway you wish to use.
        /// This should be a cleaned value (no spaces or periods) and exactly match the name of the payment gateway class to call (case insensitive)</param>
        /// <param name="ordNo">The order number to process</param>
        /// <param name="custID">The customer id of the customer placing the order</param>
        /// <param name="ordTotal">The order total to process</param>
        /// <param name="billAddr">The billing address associated with the order</param>
        /// <param name="shipAddr">The shipping address associated with the order</param>
        /// <param name="cv2">The card CV2 code (card extra code)</param>
        /// <param name="ec">The ECI code (used for VBV/3D Secure transactions)</param>
        /// <param name="xi">The XID code (used for VBV/3D Secure transactions)</param>
        public GatewayTransaction(int ordNo, int custID, decimal ordTotal, Address billAddr, Address shipAddr, string cavv, string cv2, string ec, string xi)
        {
            m_orderNumber         = ordNo;
            m_customerID          = custID;
            m_orderTotal          = ordTotal;
            m_useLiveTransactions = AppLogic.AppConfigBool("UseLiveTransactions");
            m_transactionMode     = (TransactionModeEnum)Enum.Parse(typeof(TransactionModeEnum), AppLogic.AppConfig("TransactionMode").ToLowerInvariant().Replace(" ", ""));
            m_billingAddress      = billAddr;

            if (shipAddr != null)
            {
                m_shippingAddress = shipAddr;
            }
            else
            {
                m_shippingAddress = billAddr;
            }

            m_cavv = cavv;
            m_cv2  = cv2;
            m_eci  = ec;
            m_xid  = xi;
        }
예제 #7
0
        public virtual string ProcessECheck(
            int orderNumber,
            int customerId,
            decimal orderTotal,
            bool useLiveTransactions,
            TransactionModeEnum transactionMode,
            Address useBillingAddress,
            Address useShippingAddress,
            out string avsResult,
            out string authorizationResult,
            out string authorizationCode,
            out string authorizationTransId,
            out string transactionCommandOut,
            out string transactionResponse)
        {
            avsResult             = string.Empty;
            authorizationResult   = string.Empty;
            authorizationCode     = string.Empty;
            authorizationTransId  = string.Empty;
            transactionCommandOut = string.Empty;
            transactionResponse   = string.Empty;

            return(string.Empty);
        }
예제 #8
0
        private string ProcessOrderThroughGateway(int OrderNumber, int CustomerID, Decimal OrderTotal, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, ref String AuthorizationResult, ref String AuthorizationCode, ref String AuthorizationTransID, ref String TransactionCommandOut, ref String TransactionResponse, Customer customer, GatewayMoneybookers.IPaymentType paymentType, string customerIpAddress, string cardType)
        {
            GatewayMoneybookers.PaymentRequestBuilder requestBuilder = new GatewayMoneybookers.PaymentRequestBuilder();
            var paymentRequest = requestBuilder.BuildCreditCardPaymentRequest(
                paymentType,
                OrderNumber,
                null,
                CustomerID,
                customer.EMail,
                UseBillingAddress.FirstName,
                UseBillingAddress.LastName,
                UseBillingAddress.Address1,
                UseBillingAddress.City,
                CommonLogic.IIF(String.IsNullOrEmpty(UseBillingAddress.State), null, UseBillingAddress.State),
                UseBillingAddress.Zip,
                UseBillingAddress.Country,
                customerIpAddress,
                OrderTotal,
                cardType,
                UseBillingAddress.CardNumber,
                UseBillingAddress.CardExpirationMonth.PadLeft(2, '0'),
                UseBillingAddress.CardExpirationYear,
                CommonLogic.IIF(String.IsNullOrEmpty(UseBillingAddress.CardIssueNumber), null, UseBillingAddress.CardIssueNumber),
                CardExtraCode);

            GatewayMoneybookers.PaymentXmlTransformer <GatewayMoneybookers.CreditCardPaymentMethod> paymentTransformer = new GatewayMoneybookers.PaymentXmlTransformer <GatewayMoneybookers.CreditCardPaymentMethod>();
            GatewayMoneybookers.CreditCardPaymentMethodXmlTransformer paymentMethodTransformer = new GatewayMoneybookers.CreditCardPaymentMethodXmlTransformer();
            var paymentRequestData = paymentTransformer.TransformRequest(paymentRequest, paymentMethodTransformer);

            // Submit request and get response
            string paymentResponseData = null;
            string result      = String.Empty;
            int    maxAttempts = AppLogic.AppConfigUSInt("GatewayRetries") + 1;

            for (int attemptCount = 0; attemptCount < maxAttempts; attemptCount++)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(RequestUri);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

                try
                {
                    using (var requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter requestWriter = new StreamWriter(requestStream))
                        {
                            requestWriter.Write("load={0}", Uri.EscapeDataString(paymentRequestData));
                            requestWriter.Close();
                        }

                        requestStream.Close();
                    }

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            paymentResponseData = responseReader.ReadToEnd();
                            responseReader.Close();
                        }

                        responseStream.Close();
                    }

                    break;
                }
#if DEBUG
                catch (WebException exception)
                {
                    using (var responseStream = exception.Response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            result = String.Format("Error calling Moneybookers payment gateway. {0}{1}", exception.Message, responseReader.ReadToEnd());
                            responseReader.Close();
                        }
                        responseStream.Close();
                    }
                }
#endif
                catch (Exception exception)
                {
                    result = String.Format("Error calling Moneybookers payment gateway. {0}", exception.Message);
                }
            }

            // Process response
            if (paymentResponseData != null)
            {
                GatewayMoneybookers.PaymentResponse paymentResponse = paymentTransformer.TransformResponse(paymentResponseData);
                AuthorizationCode    = paymentResponse.ProcessingCode;
                AuthorizationResult  = paymentResponse.Return;
                AuthorizationTransID = CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTH=", "CAPTURE=") + paymentResponse.TransactionUniqueId;

                TransactionCommandOut = paymentRequestData;
                TransactionResponse   = paymentResponseData;

                if (paymentResponse.Result.ToUpperInvariant() == "ACK")
                {
                    if (paymentResponse.ResponseMode == GatewayMoneybookers.ResponseMode.Async)
                    {
                        string redirectUrl = paymentResponse.RedirectUrl;

                        string parameterKeys = String.Join(";", paymentResponse.RedirectParameters.Keys.Select(s => "Moneybookers_3DSecure_Parameter_" + s).ToArray());

                        CustomerSession customerSession = new CustomerSession(CustomerID);
                        customerSession["Moneybookers_3DSecure_OrderNumber"]   = OrderNumber.ToString();
                        customerSession["Moneybookers_3DSecure_RedirectUrl"]   = paymentResponse.RedirectUrl;
                        customerSession["Moneybookers_3DSecure_ParameterKeys"] = parameterKeys;

                        foreach (var kvp in paymentResponse.RedirectParameters)
                        {
                            customerSession["Moneybookers_3DSecure_Parameter_" + kvp.Key] = kvp.Value;
                        }

                        result = AppLogic.ro_3DSecure;
                    }
                    else
                    {
                        result = AppLogic.ro_OK;
                    }
                }
                else
                {
                    result = String.Format("{0} - {1} - {2} - {3}", paymentResponse.Result, paymentResponse.Status, paymentResponse.Reason, paymentResponse.Return);
                    if (result.Length == 0)
                    {
                        result = "Unspecified Error";
                    }
                }
            }

            return(result);
        }
예제 #9
0
        private string ProcessOrderThrough3DSecure(int OrderNumber, int CustomerID, Decimal OrderTotal, TransactionModeEnum TransactionMode, Address UseBillingAddress, String CardExtraCode, ref String AuthorizationResult, ref String AuthorizationCode, ref String AuthorizationTransID, ref String TransactionCommandOut, ref String TransactionResponse, Customer customer, GatewayMoneybookers.IPaymentType paymentType, string customerIpAddress, string cardType, CustomerSession customerSession)
        {
            string originalResponseData  = customerSession["Moneybookers_3DSecure_Response"];
            var    paymentXmlTransformer = new GatewayMoneybookers.PaymentXmlTransformer <GatewayMoneybookers.CreditCardPaymentMethod>();
            var    paymentResponse       = paymentXmlTransformer.TransformResponse(originalResponseData);

            AuthorizationCode    = paymentResponse.ProcessingCode;
            AuthorizationResult  = paymentResponse.Return;
            AuthorizationTransID = CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTH=", "CAPTURE=") + paymentResponse.TransactionUniqueId;

            TransactionResponse = originalResponseData;

            // Check for timeout
            if (paymentResponse.ReturnCode == "100.380.501")
            {
                return("3D Secure payment verification timed out.");
            }

            // Verify 3D secure response
            string verificationRequestUri = ThreeDSecureRequestUri + customerSession["Moneybookers_3DSecure_VerificationPath"];

            // Submit request and get response
            string responseData = null;
            string result       = String.Empty;
            int    maxAttempts  = AppLogic.AppConfigUSInt("GatewayRetries") + 1;

            for (int attemptCount = 0; attemptCount < maxAttempts; attemptCount++)
            {
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(verificationRequestUri);
                request.Method      = "POST";
                request.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";

                try
                {
                    using (var requestStream = request.GetRequestStream())
                    {
                        using (StreamWriter requestWriter = new StreamWriter(requestStream))
                        {
                            requestWriter.Write("response={0}", Uri.EscapeDataString(originalResponseData));
                            requestWriter.Close();
                        }

                        requestStream.Close();
                    }

                    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                    using (var responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            responseData = responseReader.ReadToEnd();
                            responseReader.Close();
                        }

                        responseStream.Close();
                    }

                    break;
                }
#if DEBUG
                catch (WebException exception)
                {
                    using (var responseStream = exception.Response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            result = String.Format("Error calling Skrill (Moneybookers) payment gateway. {0}{1}", exception.Message, responseReader.ReadToEnd());
                            responseReader.Close();
                        }
                        responseStream.Close();
                    }
                }
#endif
                catch (Exception exception)
                {
                    result = String.Format("Error calling Skrill (Moneybookers) payment gateway. {0}", exception.Message);
                }
            }

            // Process response
            if (String.IsNullOrEmpty(responseData))
            {
                result = "Empty response from 3D Secure validation call.";
            }
            else if (responseData == "VERIFIED")
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = "Payment method was not validated. Please try submitting your payment again";
            }

            return(result);
        }
예제 #10
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 AVSAddr = String.Empty;
            String AVSZip  = String.Empty;

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

            // Generate payment request
            Customer customer = new Customer(CustomerID, true);

            GatewayMoneybookers.IPaymentType paymentType;
            if (TransactionMode == TransactionModeEnum.auth)
            {
                paymentType = GatewayMoneybookers.PaymentType.Preauthorisation;
            }
            else
            {
                paymentType = GatewayMoneybookers.PaymentType.Debit;
            }

            string customerIpAddress = CommonLogic.CustomerIpAddress();

            if (customerIpAddress == "::1")
            {
                customerIpAddress = "127.0.0.1";
            }
            else if (customerIpAddress.Contains(":"))
            {
                throw new Exception("The Skrill (Moneybookers) payment gateway does not support IPv6.");
            }

            string cardType = UseBillingAddress.CardType;

            if (cardType.ToUpper() == "MASTERCARD")
            {
                cardType = "MASTER";
            }

            string          result;
            CustomerSession customerSession = new CustomerSession(CustomerID);

            if (customerSession.SessionUSInt("Moneybookers_3DSecure_OrderNumber") == OrderNumber)
            {
                result = ProcessOrderThrough3DSecure(OrderNumber, CustomerID, OrderTotal, TransactionMode, UseBillingAddress, CardExtraCode, ref AuthorizationResult, ref AuthorizationCode, ref AuthorizationTransID, ref TransactionCommandOut, ref TransactionResponse, customer, paymentType, customerIpAddress, cardType, customerSession);
            }
            else
            {
                result = ProcessOrderThroughGateway(OrderNumber, CustomerID, OrderTotal, TransactionMode, UseBillingAddress, CardExtraCode, ref AuthorizationResult, ref AuthorizationCode, ref AuthorizationTransID, ref TransactionCommandOut, ref TransactionResponse, customer, paymentType, customerIpAddress, cardType);
            }

            return(result);
        }
예제 #11
0
파일: Micropay.cs 프로젝트: giagiigi/WE
 public override string ProcessCard(int orderNumber, int customerId, decimal orderTotal, bool useLiveTransactions, TransactionModeEnum transactionMode, Address billingAddress, string cardExtraCode, Address shippingAddress, string cavv, string eci, string xid, out string avsResult, out string authorizationResult, out string authorizationCode, out string authorizationTransactionId, out string transactionCommand, out string transactionResponse)
 {
     return
         (avsResult =
              authorizationResult =
                  authorizationCode =
                      authorizationTransactionId =
                          transactionCommand =
                              transactionResponse = string.Empty);
 }
예제 #12
0
파일: USAePay.cs 프로젝트: giagiigi/WE
        /// <summary>
        /// Processes the card.
        /// </summary>
        /// <param name="OrderNumber">The order number.</param>
        /// <param name="CustomerID">The customer ID.</param>
        /// <param name="OrderTotal">The order total.</param>
        /// <param name="useLiveTransactions">if set to <c>true</c> [use live transactions].</param>
        /// <param name="TransactionMode">The transaction mode.</param>
        /// <param name="UseBillingAddress">The use billing address.</param>
        /// <param name="CardExtraCode">The card extra code.</param>
        /// <param name="UseShippingAddress">The use shipping address.</param>
        /// <param name="CAVV">The CAVV.</param>
        /// <param name="ECI">The ECI.</param>
        /// <param name="XID">The XID.</param>
        /// <param name="AVSResult">The AVS result.</param>
        /// <param name="AuthorizationResult">The authorization result.</param>
        /// <param name="AuthorizationCode">The authorization code.</param>
        /// <param name="AuthorizationTransID">The authorization trans ID.</param>
        /// <param name="TransactionCommandOut">The transaction command sent to the gateway</param>
        /// <param name="TransactionResponse">The transaction response.</param>
        /// <returns>Status</returns>
        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 = AuthorizationResult = AuthorizationTransID = AVSResult = TransactionCommandOut = TransactionResponse = String.Empty;

            //set service configuration
            GatewayUSAePay.USAePaySOAP.ueSoapServerPortType client = GetServiceClient(UseSandBox);


            var token = GetSecurityToken();

            var tran = GetProcessCardTransactionRequestObject(OrderTotal, OrderNumber, UseBillingAddress, CardExtraCode, CAVV, ECI, XID, UseShippingAddress);

            var response = new GatewayUSAePay.USAePaySOAP.TransactionResponse();

            if (TransactionMode == TransactionModeEnum.auth)
            {
                try
                {
                    response = client.runAuthOnly(token, tran);
                    if (response.ResultCode == "A")
                    {
                        result = AppLogic.ro_OK;
                    }
                    else if (response.ResultCode == "D")
                    {
                        result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.Declined"), response.Error);
                    }
                    else
                    {
                        result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.TransactionError"), response.Error);
                    }
                }
                catch (Exception ex)
                {
                    result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.ConnectionError"), ex.Message);
                }
            }
            else if (TransactionMode == TransactionModeEnum.authcapture)
            {
                try
                {
                    response = client.runSale(token, tran);
                    if (response.ResultCode == "A")
                    {
                        result = AppLogic.ro_OK;
                    }
                    else if (response.ResultCode == "D")
                    {
                        result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.Declined"), response.Error);
                    }
                    else
                    {
                        result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.TransactionError"), response.Error);
                    }
                }
                catch (Exception ex)
                {
                    result = string.Format("{0}: {1}", AppLogic.AppConfig("USAePay.ConnectionError"), ex.Message);
                }
            }

            AVSResult             = response.AvsResult ?? String.Empty;
            AuthorizationResult   = response.CardCodeResult ?? String.Empty;
            AuthorizationCode     = response.AuthCode ?? String.Empty;
            AuthorizationTransID  = response.RefNum ?? String.Empty;
            TransactionCommandOut = response.Error ?? String.Empty;            //Approved, etc
            TransactionResponse   = response.Result ?? String.Empty;

            return(result);
        }
예제 #13
0
        public 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, Boolean IsVaultTransaction, Customer ThisCustomer)
        {
            if (IsVaultTransaction && ThisCustomer == null)
            {
                throw new ArgumentException("Customer Object required for vault transactions.");
            }

            String result = AppLogic.ro_OK;

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

            GatewayClient client = SecureNetController.GetGatewayClient();

            TRANSACTION oT = SecureNetController.GetTransactionWithDefaults();

            if (IsVaultTransaction)
            {
                //vault info
                oT.CUSTOMERID = ThisCustomer.CustomerID.ToString();
                oT.PAYMENTID  = AppLogic.GetSelectedSecureNetVault(ThisCustomer);
            }
            else
            {
                //Credit Card Info
                oT.CARD            = new CARD();
                oT.CARD.CARDCODE   = CardExtraCode;
                oT.CARD.CARDNUMBER = UseBillingAddress.CardNumber;
                oT.CARD.EXPDATE    = UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2); //MMYY
            }


            //Billing Address Info
            oT.CUSTOMER_BILL           = new CUSTOMER_BILL();
            oT.CUSTOMER_BILL.ADDRESS   = UseBillingAddress.Address1;
            oT.CUSTOMER_BILL.CITY      = UseBillingAddress.City;
            oT.CUSTOMER_BILL.ZIP       = UseBillingAddress.Zip;
            oT.CUSTOMER_BILL.STATE     = UseBillingAddress.State;
            oT.CUSTOMER_BILL.COMPANY   = UseBillingAddress.Company;
            oT.CUSTOMER_BILL.COUNTRY   = UseBillingAddress.Country;
            oT.CUSTOMER_BILL.EMAIL     = UseBillingAddress.EMail;
            oT.CUSTOMER_BILL.FIRSTNAME = UseBillingAddress.FirstName;
            oT.CUSTOMER_BILL.LASTNAME  = UseBillingAddress.LastName;
            oT.CUSTOMER_BILL.PHONE     = UseBillingAddress.Phone;

            //Shipping Address Info
            if (UseShippingAddress != null)
            {
                oT.CUSTOMER_SHIP           = new CUSTOMER_SHIP();
                oT.CUSTOMER_SHIP.ADDRESS   = UseShippingAddress.Address1;
                oT.CUSTOMER_SHIP.CITY      = UseShippingAddress.City;
                oT.CUSTOMER_SHIP.ZIP       = UseShippingAddress.Zip;
                oT.CUSTOMER_SHIP.STATE     = UseShippingAddress.State;
                oT.CUSTOMER_SHIP.COMPANY   = UseShippingAddress.Company;
                oT.CUSTOMER_SHIP.COUNTRY   = UseShippingAddress.Country;
                oT.CUSTOMER_SHIP.FIRSTNAME = UseShippingAddress.FirstName;
                oT.CUSTOMER_SHIP.LASTNAME  = UseShippingAddress.LastName;
            }

            //todo - look into adding cartitems

            //Transaction Information
            oT.AMOUNT      = OrderTotal;
            oT.CODE        = CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), SecureNetController.GetTypeCodeString(SecureNetTransactionTypeCode.AUTH_ONLY), SecureNetController.GetTypeCodeString(SecureNetTransactionTypeCode.AUTH_CAPTURE));
            oT.METHOD      = SecureNetMethod.CC.ToString();
            oT.ORDERID     = OrderNumber.ToString();
            oT.CUSTOMERIP  = CommonLogic.CustomerIpAddress();
            oT.INVOICENUM  = OrderNumber.ToString();
            oT.INVOICEDESC = AppLogic.AppConfig("StoreName");

            //pasing unused integers as zeros as defined in the securenet docs
            oT.TOTAL_INSTALLMENTCOUNT  = 0;
            oT.OVERRIDE_FROM           = 0;
            oT.INSTALLMENT_SEQUENCENUM = 0;
            oT.RETAIL_LANENUM          = 0;
            oT.CASHBACK_AMOUNT         = 0;

            if (IsVaultTransaction)
            {
                oT.TRANSACTION_SERVICE = 1;
            }
            else
            {
                oT.TRANSACTION_SERVICE = 0;
            }

            //MPI for 3D Secure
            oT.MPI = new MPI();

            if (!String.IsNullOrEmpty(ECI))
            {
                oT.MPI.AUTHINDICATOR = ECI;
            }

            if (!String.IsNullOrEmpty(CAVV))
            {
                oT.MPI.AUTHVALUE = CAVV;
            }

            GATEWAYRESPONSE oG = client.ProcessTransaction(oT);

            if (oG.TRANSACTIONRESPONSE.RESPONSE_CODE == "1")
            {
                AuthorizationTransID = oG.TRANSACTIONRESPONSE.TRANSACTIONID.ToString();
                AuthorizationCode    = "Response Code: " + oG.TRANSACTIONRESPONSE.RESPONSE_CODE + ", Reason Code: " + oG.TRANSACTIONRESPONSE.RESPONSE_REASON_CODE;

                if (!String.IsNullOrEmpty(oG.TRANSACTIONRESPONSE.AVS_RESULT_CODE))
                {
                    AVSResult = oG.TRANSACTIONRESPONSE.AVS_RESULT_CODE;
                }

                if (!String.IsNullOrEmpty(oG.TRANSACTIONRESPONSE.CARD_CODE_RESPONSE_CODE))
                {
                    if (AVSResult.Length > 0)
                    {
                        AVSResult += ", ";
                    }
                    AVSResult += "ExtraCode: " + oG.TRANSACTIONRESPONSE.CARD_CODE_RESPONSE_CODE;
                }

                //if (!String.IsNullOrEmpty(oTr.CAVV_Response_Code))
                if (!String.IsNullOrEmpty(oG.TRANSACTIONRESPONSE.CAVV_RESPONSE_CODE))
                {
                    if (AVSResult.Length > 0)
                    {
                        AVSResult += ", ";
                    }
                    AVSResult += "CAVV: " + oG.TRANSACTIONRESPONSE.CAVV_RESPONSE_CODE;
                }

                AuthorizationResult = oG.TRANSACTIONRESPONSE.RESPONSE_REASON_TEXT + ", Approval Code: " + oG.TRANSACTIONRESPONSE.AUTHCODE;
                result = AppLogic.ro_OK;
            }
            else
            {
                AuthorizationResult = "Error: [" + oG.TRANSACTIONRESPONSE.RESPONSE_CODE + "] " + oG.TRANSACTIONRESPONSE.RESPONSE_REASON_TEXT;
                result = oG.TRANSACTIONRESPONSE.RESPONSE_REASON_TEXT;
            }

            TransactionCommandOut = this.GetXMLSerializedObject(oT);
            TransactionResponse   = this.GetXMLSerializedObject(oG);

            if (!IsVaultTransaction && AppLogic.SecureNetVaultIsEnabled() && result == AppLogic.ro_OK)
            {
                if (ThisCustomer == null)
                {
                    ThisCustomer = new Customer(CustomerID);
                }
                if (ThisCustomer.SecureNetVaultMasterShouldWeStoreCreditCardInfo)
                {
                    try
                    {
                        SecureNetVault vault = new SecureNetVault(ThisCustomer);
                        vault.AddCreditCardToCustomerVault(UseBillingAddress.CardName, UseBillingAddress.CardNumber, CardExtraCode, UseBillingAddress.CardType, UseBillingAddress.CardExpirationMonth, UseBillingAddress.CardExpirationYear);
                    }
                    catch { }
                }
            }

            if (IsVaultTransaction && result == AppLogic.ro_OK)
            {
                AppLogic.ClearSelectedSecureNetVaultInSession(ThisCustomer);
            }

            return(result);
        }
예제 #14
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)
        {
            // With SkipJack configured for Automatic Settlement the storefront should
            //   have AppConfig TransationMode set to AUTH CAPTURE.
            // With SkipJack configured for Manual Settlement the storefront should
            //   have AppConfig TransationMode set to AUTH.

            bool          HasEmail           = false;
            String        result             = AppLogic.ro_OK;
            ASCIIEncoding encoding           = new ASCIIEncoding();
            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("sjname=" + HttpContext.Current.Server.UrlEncode((UseBillingAddress.FirstName + " " + UseBillingAddress.LastName).Trim()));
            if (UseBillingAddress.EMail.Length != 0)
            {
                HasEmail = true;
                transactionCommand.Append("&Email=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.EMail));
            }
            else if (UseShippingAddress.EMail.Length != 0)
            {
                HasEmail = true;
                transactionCommand.Append("&Email=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.EMail));
            }
            else if (HasEmail == false)
            {
                string Email = AppLogic.SkipJackEmail(CustomerID);
                transactionCommand.Append("&Email=" + HttpContext.Current.Server.UrlEncode(Email));
            }

            transactionCommand.Append("&Streetaddress=" + HttpContext.Current.Server.UrlEncode((UseBillingAddress.Address1 + " " + UseBillingAddress.Address2).Trim()));
            transactionCommand.Append("&City=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.City));
            transactionCommand.Append("&State=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.State));
            transactionCommand.Append("&ZipCode=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Zip));
            transactionCommand.Append("&Ordernumber=" + OrderNumber.ToString());
            transactionCommand.Append("&Accountnumber=" + UseBillingAddress.CardNumber);
            transactionCommand.Append("&Month=" + UseBillingAddress.CardExpirationMonth);
            transactionCommand.Append("&Year=" + UseBillingAddress.CardExpirationYear);
            if (CardExtraCode.Length != 0)
            {
                transactionCommand.Append("&CVV2=" + CardExtraCode);
            }

            // The Skipjack.SerialNumber for the ASPDotNetStoreFront needs to be added to the AppConfig table in the db
            if (useLiveTransactions)
            {
                transactionCommand.Append("&SerialNumber=" + AppLogic.AppConfig("Skipjack.LiveSerialNumber"));
            }
            else
            {
                transactionCommand.Append("&SerialNumber=" + AppLogic.AppConfig("Skipjack.TestSerialNumber"));
            }
            if (AppLogic.AppConfig("Skipjack.DeveloperSerialNumber").Length != 0)
            {
                transactionCommand.Append("&DeveloperSerialNumber=" + AppLogic.AppConfig("Skipjack.DeveloperSerialNumber"));
            }
            transactionCommand.Append("&TransactionAmount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&OrderString=" + HttpContext.Current.Server.UrlEncode((OrderNumber.ToString() + "~" + AppLogic.AppConfig("StoreName") + "Order~" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal) + "~1~N~||")));
            transactionCommand.Append("&Country=" + AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country));

            if (UseShippingAddress != null)
            {
                if (String.IsNullOrEmpty(UseShippingAddress.Phone))
                {
                    transactionCommand.Append("&ShipToPhone=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Phone));
                }
                else
                {
                    transactionCommand.Append("&ShipToPhone=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Phone));
                }
                transactionCommand.Append("&StreetAddress=" + HttpContext.Current.Server.UrlEncode((UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim()));
                transactionCommand.Append("&ShipToStreetAddress=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Address1));
                transactionCommand.Append("&ShipToCity=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.City));
                transactionCommand.Append("&ShipToState=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.State));
                transactionCommand.Append("&ShipToZipcode=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Zip));
            }
            else
            {
                transactionCommand.Append("&ShipToPhone=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Phone));
                transactionCommand.Append("&StreetAddress=" + HttpContext.Current.Server.UrlEncode((UseBillingAddress.FirstName + " " + UseBillingAddress.LastName).Trim()));
                transactionCommand.Append("&ShipToStreetAddress=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Address1));
                transactionCommand.Append("&ShipToCity=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.City));
                transactionCommand.Append("&ShipToState=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.State));
                transactionCommand.Append("&ShipToZipcode=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Zip));
            }

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

            // Prepare web request...
            Boolean TransactionCleared = false;

            AVSResult = String.Empty;
            String ResponseString = String.Empty;

            AuthorizationCode    = String.Empty;
            AuthorizationResult  = String.Empty;
            AuthorizationTransID = String.Empty;
            String AuthorizationDeclinedMsg = String.Empty;

            TransactionCommandOut = string.Empty;
            TransactionResponse   = String.Empty;
            String AuthServer = String.Empty;

            try
            {
                if (useLiveTransactions)
                {
                    AuthServer = AppLogic.AppConfig("Skipjack.LiveServer");
                }
                else
                {
                    AuthServer = AppLogic.AppConfig("Skipjack.TestServer");
                }

                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;
                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();

                ResponseString = rawResponseString.ToString();
                if (AppLogic.AppConfigBool("SkipJack.InsertAdvanceFormComma"))
                {
                    ResponseString = ResponseString.Replace(Environment.NewLine, "," + Environment.NewLine);                     // stick a comma at the end of the title row to throw off indexes FOR PARSER TESTING ONLY
                }
                AuthorizationDeclinedMsg = AuthorizationDeclinedMsg + ResponseString;

                Dictionary <String, String> response = ParseResponse(ResponseString);

                bool   WasApproved = false;
                String ReturnCode  = String.Empty;

                foreach (KeyValuePair <String, String> kvp in response)
                {
                    switch (kvp.Key)
                    {
                    case "szIsApproved":
                        if (kvp.Value == "1")
                        {
                            WasApproved = true;
                        }
                        else
                        {
                            WasApproved = false;
                        }
                        break;

                    case "AUTHCODE":
                        AuthorizationCode = kvp.Value;
                        break;

                    case "szReturnCode":
                        ReturnCode = kvp.Value;
                        if (kvp.Value == "1")
                        {
                            TransactionCleared = true;
                        }
                        else
                        {
                            TransactionCleared = false;
                        }
                        break;

                    case "szAVSResponseCode":
                        AVSResult = kvp.Value;
                        break;

                    case "szAVSResponseMessage":
                        AuthorizationResult = kvp.Value;
                        break;

                    case "szAuthorizationDeclinedMessage":
                        AuthorizationDeclinedMsg = kvp.Value;
                        break;

                    case "szTransactionFileName":
                        AuthorizationTransID = kvp.Value;
                        break;
                    }
                }

                TransactionCommandOut = transactionCommand.ToString();
                TransactionResponse   = rawResponseString;

                if (!TransactionCleared)
                {
                    result = "Transaction Failed with code " + ReturnCode + ": " + GetReturnCodeMessage(ReturnCode);
                }
                else
                {
                    if (WasApproved)
                    {
                        result = AppLogic.ro_OK;
                    }
                    else
                    {
                        result = "Error: " + AuthorizationDeclinedMsg;
                    }
                }
            }
            catch
            {
                result = "Error calling SkipJack gateway. Please retry your order in a few minutes or select another checkout payment option.";
            }
            TransactionResponse += Environment.NewLine + result;

            return(result);
        }
예제 #15
0
파일: Manual.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;

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

            if (AppLogic.AppConfigBool("ValidateCreditCardNumbers"))
            {
                CardType cardType = CardType.ParseFromNumber(UseBillingAddress.CardNumber.ToString());
                if (cardType == null)
                {
                    return(AppLogic.GetString("checkoutcard_process.aspx.3", Customer.Current.LocaleSetting));
                }

                CreditCardValidator validator = new CreditCardValidator(UseBillingAddress.CardNumber.ToString(), cardType);

                bool isValidCC = validator.Validate();
                if (!isValidCC)
                {
                    return(AppLogic.GetString("checkoutcard_process.aspx.3", Customer.Current.LocaleSetting));
                }

                bool isValidCCExpiration = validator.CheckCCExpiration(Convert.ToInt32(UseBillingAddress.CardExpirationMonth), Convert.ToInt32(UseBillingAddress.CardExpirationYear));
                if (!isValidCCExpiration)
                {
                    return(AppLogic.GetString("checkoutcard_process.aspx.6", Customer.Current.LocaleSetting));
                }

                bool isValidCVV = AppLogic.AppConfigBool("CardExtraCodeIsOptional") || validator.ValidateCVV(UseBillingAddress.CardNumber.ToString(), CardExtraCode);
                if (!isValidCVV)
                {
                    return(AppLogic.GetString("checkoutcard_process.aspx.7", Customer.Current.LocaleSetting));
                }
            }

            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("x_type=" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTH_ONLY", "AUTH_CAPTURE"));

            transactionCommand.Append("&x_test_request=" + CommonLogic.IIF(useLiveTransactions, "FALSE", "TRUE"));
            transactionCommand.Append("&x_description=" + HttpContext.Current.Server.UrlEncode(AppLogic.AppConfig("StoreName") + " Order " + OrderNumber.ToString()));

            transactionCommand.Append("&x_amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&x_card_num=" + UseBillingAddress.CardNumber);
            if (CardExtraCode.Length != 0)
            {
                transactionCommand.Append("&x_card_code=" + CardExtraCode.Trim());
            }

            transactionCommand.Append("&x_exp_date=" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + "/" + UseBillingAddress.CardExpirationYear);
            transactionCommand.Append("&x_phone=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Phone));
            transactionCommand.Append("&x_fax=");
            transactionCommand.Append("&x_customer_tax_id=");
            transactionCommand.Append("&x_cust_id=" + CustomerID.ToString());
            transactionCommand.Append("&x_invoice_num=" + OrderNumber.ToString());
            transactionCommand.Append("&x_email=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.EMail));
            transactionCommand.Append("&x_customer_ip=" + CommonLogic.CustomerIpAddress());

            transactionCommand.Append("&x_first_name=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.FirstName));
            transactionCommand.Append("&x_last_name=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.LastName));
            transactionCommand.Append("&x_company=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Company));
            transactionCommand.Append("&x_address=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Address1));
            transactionCommand.Append("&x_city=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.City));
            transactionCommand.Append("&x_state=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.State));
            transactionCommand.Append("&x_zip=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Zip));
            transactionCommand.Append("&x_country=" + HttpContext.Current.Server.UrlEncode(UseBillingAddress.Country));

            if (UseShippingAddress != null)
            {
                transactionCommand.Append("&x_ship_to_first_name=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.FirstName));
                transactionCommand.Append("&x_ship_to_last_name=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.LastName));
                transactionCommand.Append("&x_ship_to_company=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Company));
                transactionCommand.Append("&x_ship_to_address=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Address1));
                transactionCommand.Append("&x_ship_to_city=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.City));
                transactionCommand.Append("&x_ship_to_state=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.State));
                transactionCommand.Append("&x_ship_to_zip=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Zip));
                transactionCommand.Append("&x_ship_to_country=" + HttpContext.Current.Server.UrlEncode(UseShippingAddress.Country));
            }

            transactionCommand.Append("&x_customer_ip=" + CommonLogic.CustomerIpAddress());

            if (CAVV.Length != 0 || ECI.Length != 0)
            {
                transactionCommand.Append("&x_authentication_indicator=" + ECI);
                transactionCommand.Append("&x_cardholder_authentication_value=" + CAVV);
            }

            String rawResponseString = "MANUAL GATEWAY SAID OK";

            AuthorizationCode     = "0";
            AuthorizationResult   = rawResponseString;
            AuthorizationTransID  = CommonLogic.GetNewGUID();
            AVSResult             = AppLogic.ro_OK;
            TransactionCommandOut = transactionCommand.ToString();
            TransactionResponse   = String.Empty;

            return(result);
        }
예제 #16
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 EMail = UseBillingAddress.EMail;

            StringBuilder transactionCommand = new StringBuilder(4096);

            transactionCommand.Append("<ewaygateway>");
            transactionCommand.Append("<ewayCustomerID>" + CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("eWay.Live.CustomerID"), AppLogic.AppConfig("eWay.Test.CustomerID")) + "</ewayCustomerID>");
            transactionCommand.Append("<ewayTotalAmount>" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(".", "") + "</ewayTotalAmount>"); // must go in cents
            transactionCommand.Append("<ewayCustomerFirstName>" + XmlCommon.XmlEncode(UseBillingAddress.FirstName) + "</ewayCustomerFirstName>");
            transactionCommand.Append("<ewayCustomerLastName>" + XmlCommon.XmlEncode(UseBillingAddress.LastName) + " </ewayCustomerLastName>");
            transactionCommand.Append("<ewayCustomerEmail>" + XmlCommon.XmlEncode(EMail) + "</ewayCustomerEmail>");
            transactionCommand.Append("<ewayCustomerAddress>" + XmlCommon.XmlEncode(UseBillingAddress.Address1) + "</ewayCustomerAddress>");
            transactionCommand.Append("<ewayCustomerPostcode>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</ewayCustomerPostcode>");
            transactionCommand.Append("<ewayCustomerInvoiceDescription>" + XmlCommon.XmlEncode(AppLogic.AppConfig("StoreName") + " Order #" + OrderNumber.ToString()) + "</ewayCustomerInvoiceDescription>");
            transactionCommand.Append("<ewayCustomerInvoiceRef>" + OrderNumber.ToString() + "</ewayCustomerInvoiceRef>");
            transactionCommand.Append("<ewayCardHoldersName>" + XmlCommon.XmlEncode(UseBillingAddress.CardName) + "</ewayCardHoldersName>");
            transactionCommand.Append("<ewayCardNumber>" + UseBillingAddress.CardNumber + "</ewayCardNumber>");
            transactionCommand.Append("<ewayCardExpiryMonth>" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + "</ewayCardExpiryMonth>");
            transactionCommand.Append("<ewayCardExpiryYear>" + UseBillingAddress.CardExpirationYear.Substring(2, 2) + "</ewayCardExpiryYear>");
            transactionCommand.Append("<ewayTrxnNumber>" + OrderNumber.ToString() + "</ewayTrxnNumber>");
            transactionCommand.Append("<ewayCVN>" + CardExtraCode.Trim() + "</ewayCVN>");
            transactionCommand.Append("<ewayOption1></ewayOption1>");
            transactionCommand.Append("<ewayOption2></ewayOption2>");
            transactionCommand.Append("<ewayOption3></ewayOption3>");
            transactionCommand.Append("</ewaygateway>");

            TransactionCommandOut = transactionCommand.ToString();

            ASCIIEncoding encoding = new ASCIIEncoding();

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

            // Prepare web request...
            String AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("eWay.Live.URL"), AppLogic.AppConfig("eWay.Test.URL"));

            if (CardExtraCode.Trim().Length == 0)
            {
                AuthServer = AuthServer.Replace("_cvn", "");
            }

            WebResponse myResponse;
            String      rawResponseString = String.Empty;

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(AuthServer);
                myRequest.ContentType   = "text/xml;charset=\"utf-8\"";
                myRequest.Accept        = "text/xml";
                myRequest.Method        = "POST";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                // get the response
                myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream());
                rawResponseString = sr.ReadToEnd();
                sr.Close();
                myResponse.Close();
            }
            catch
            {
                result = "NO RESPONSE FROM EWAY GATEWAY!";
            }

            // rawResponseString now has gateway response
            TransactionResponse = rawResponseString;

            XmlDocument Doc = new XmlDocument();

            Doc.LoadXml(rawResponseString);
            XmlNode Node = Doc.SelectSingleNode("ewayResponse");

            if (Node != null)
            {
                AuthorizationTransID = XmlCommon.XmlField(Node, "ewayTrxnReference");
                AuthorizationCode    = XmlCommon.XmlField(Node, "ewayAuthCode");
                AVSResult            = "Not Available";
                AuthorizationResult  = XmlCommon.XmlField(Node, "ewayTrxnStatus");
                TransactionResponse  = XmlCommon.XmlField(Node, "ewayTrxnError");
                if (AuthorizationResult.ToLower() == "true")
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    result = TransactionResponse;
                }
            }
            else
            {
                result = "Error calling eWay Gatway, No Xml Document Returned";
            }

            return(result);
        }
예제 #17
0
        // processes card in real time:
        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 = "VERISIGN COM COMPONENTS NOT INSTALLED ON SERVER OR STOREFRONT NOT COMPILED WITH VERISIGN CODE TURNED ON";

            AuthorizationCode     = String.Empty;
            AuthorizationResult   = String.Empty;
            AuthorizationTransID  = String.Empty;
            AVSResult             = String.Empty;
            TransactionCommandOut = String.Empty;
            TransactionResponse   = String.Empty;
#if VERISIGN
            PFProCOMLib.PNComClass vsnGate = new PFProCOMLib.PNComClass();
            int TO = AppLogic.AppConfigUSInt("Verisign_Timeout");
            if (TO == 0)
            {
                TO = 60;
            }
            vsnGate.TimeOut = TO.ToString();

            StringBuilder transactionCommand = new StringBuilder(4096);
            String        rawResponseString;
            String        replyCode    = String.Empty;
            String        responseCode = String.Empty;
            String        authResponse = String.Empty;
            String        approvalCode = String.Empty;
            String        orderTotalString;

            if (!useLiveTransactions)
            {
                OrderTotal = 1.0M;
            }
            orderTotalString = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);

            transactionCommand.Append("TRXTYPE=" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "A", "S") + "&TENDER=C&ZIP=" + UseBillingAddress.Zip + "&COMMENT1=Order " + OrderNumber + "&COMMENT2=CustomerID " + CustomerID.ToString());
            transactionCommand.Append("&PWD=" + AppLogic.AppConfig("Verisign_PWD"));
            transactionCommand.Append("&USER="******"Verisign_USER"));
            transactionCommand.Append("&VENDOR=" + AppLogic.AppConfig("Verisign_VENDOR"));
            transactionCommand.Append("&PARTNER=" + AppLogic.AppConfig("Verisign_PARTNER"));

            //set the amount
            transactionCommand.Append("&AMT=" + orderTotalString);

            transactionCommand.Append("&ACCT=" + UseBillingAddress.CardNumber);
            //set the expiration date form the HTML form
            transactionCommand.Append("&EXPDATE=" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + UseBillingAddress.CardExpirationYear.Substring(2, 2));

            //set the CSC code:
            if (CardExtraCode.Trim().Length != 0)
            {
                transactionCommand.Append("&CSC2MATCH=" + CardExtraCode);
                transactionCommand.Append("&CVV2=" + CardExtraCode);
            }

            if (UseShippingAddress != null)
            {
                transactionCommand.Append("&SHIPTOSTREET=" + UseShippingAddress.Address1.Replace("&", "").Replace("=", ""));
                transactionCommand.Append("&SHIPTOCITY=" + UseShippingAddress.City.Replace("&", "").Replace("=", ""));
                transactionCommand.Append("&SHIPTOSTATE=" + UseShippingAddress.State.Replace("&", "").Replace("=", ""));
                transactionCommand.Append("&SHIPTOZIP=" + UseShippingAddress.Zip.Replace("&", "").Replace("=", ""));
                transactionCommand.Append("&SHIPTOCOUNTRY=" + UseShippingAddress.Country.Replace("&", "").Replace("=", ""));             //Verisign documentation says it's SHIPTOCOUNTRY but support says it's COUNTRYCODE which is the one that worked for me
                transactionCommand.Append("&COUNTRYCODE=" + UseShippingAddress.Country.Replace("&", "").Replace("=", ""));               //Verisign documentation says it's SHIPTOCOUNTRY but support says it's COUNTRYCODE which is the one that worked for me
            }

            transactionCommand.Append("&STREET=" + UseBillingAddress.Address1.Replace("&", "").Replace("=", ""));
            transactionCommand.Append("&CITY=" + UseBillingAddress.City.Replace("&", "").Replace("=", ""));
            transactionCommand.Append("&STATE=" + UseBillingAddress.State.Replace("&", "").Replace("=", ""));
            transactionCommand.Append("&ZIP=" + UseBillingAddress.Zip.Replace("&", "").Replace("=", ""));
            transactionCommand.Append("&COUNTRY=" + UseBillingAddress.Country.Replace("&", "").Replace("=", ""));
            transactionCommand.Append("&CUSTIP=" + CommonLogic.CustomerIpAddress().Replace("&", "").Replace("=", ""));           //cart.ThisCustomer.LastIPAddress);
            transactionCommand.Append("&EMAIL=" + UseBillingAddress.EMail.Replace("&", "").Replace("=", ""));

            if (CAVV.Length != 0)
            {
                transactionCommand.Append("&CAVV[" + CAVV.Length.ToString() + "]=" + CAVV);
                transactionCommand.Append("&ECI=" + ECI);
                //transactionCommand.Append("&XID=" + XID);
            }

            int Ctx1;
            if (AppLogic.AppConfigBool("UseLiveTransactions"))
            {
                Ctx1 = vsnGate.CreateContext("payflow.verisign.com", 443, 30, String.Empty, 0, String.Empty, String.Empty);
            }
            else
            {
                Ctx1 = vsnGate.CreateContext("test-payflow.verisign.com", 443, 30, String.Empty, 0, String.Empty, String.Empty);
            }
            String curString = vsnGate.SubmitTransaction(Ctx1, transactionCommand.ToString(), transactionCommand.Length);
            rawResponseString = curString;
            vsnGate.DestroyContext(Ctx1);

            bool   AVSOK   = true;
            String AVSAddr = String.Empty;
            String AVSZip  = String.Empty;

            String[] statusArray = curString.Split('&');
            for (int i = statusArray.GetLowerBound(0); i <= statusArray.GetUpperBound(0); i++)
            {
                String[] lasKeyPair = statusArray[i].Split('=');
                switch (lasKeyPair[0].ToLowerInvariant())
                {
                case "result":
                    replyCode = lasKeyPair[1];
                    break;

                case "pnref":
                    responseCode = lasKeyPair[1];
                    break;

                case "respmsg":
                    authResponse = lasKeyPair[1];
                    break;

                case "authcode":
                    approvalCode = lasKeyPair[1];
                    break;

                case "avsaddr":
                    AVSAddr = lasKeyPair[1];
                    break;

                case "avszip":
                    AVSZip = lasKeyPair[1];
                    break;
                }
            }

            // ok, how to handle this? Bank doesn't decline based on AVS info, so we can't either...as the card has already been charged!

//			if(AppLogic.AppConfigBool("Verisign_Verify_Addresses"))
//			{
//				AVSOK = false;
//				if(AVSAddr == "Y" || AVSZip == "Y")
//				{
//					AVSOK = true;
//				}
//			}

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

            if (replyCode == "0" && AVSOK)
            {
                result = AppLogic.ro_OK;
            }
            else
            {
                result = authResponse;
                if (result.Length == 0)
                {
                    result = "Unspecified Error";
                }
                result = result.Replace("account", "card");
                result = result.Replace("Account", "Card");
                result = result.Replace("ACCOUNT", "CARD");
            }
#endif
            return(result);
        }
예제 #18
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)
        {
            var session = new CustomerSession(customerID);

            string result = AppLogic.ro_OK;

            authorizationCode                       =
                authorizationResult                 =
                    authorizationTransID            =
                        avsResult                   =
                            transactionCommandOut   =
                                transactionResponse = string.Empty;

            var threeDSecureEnabled = AppLogic.AppConfigBool("Braintree.3dSecureEnabled");

            //3dSecure is enabled and this customer hasn't yet been authed - send them to the 3dSecure form
            if (threeDSecureEnabled &&
                session[AppLogic.Braintree3dSecureKey].EqualsIgnoreCase("false") &&
                session[AppLogic.BraintreePaymentMethod].EqualsIgnoreCase("creditcard"))
            {
                session["3DSecure.OrderNumber"] = orderNumber.ToString();
                return(AppLogic.ro_3DSecure);
            }

            var nonce = session[AppLogic.BraintreeNonceKey];

            var gateway = CreateBraintreeGateway();

            var transactionRequest = new GWBraintree.TransactionRequest
            {
                OrderId            = orderNumber.ToString(),
                Amount             = Math.Round(orderTotal, 2),     //They only accept up to 2 decimal places
                PaymentMethodNonce = nonce,
                Options            = new GWBraintree.TransactionOptionsRequest
                {
                    SubmitForSettlement = AppLogic.TransactionModeIsAuthCapture(),
                    ThreeDSecure        = (threeDSecureEnabled && session[AppLogic.Braintree3dSecureKey] == "true")                 //Don't add this if the card wasn't enrolled
                                        ? new GWBraintree.TransactionOptionsThreeDSecureRequest()
                    {
                        Required = threeDSecureEnabled
                    }
                                        : null
                },
                //Add address info in case the merchant has turned on AVS settings in their Braintree account
                BillingAddress = new GWBraintree.AddressRequest
                {
                    FirstName       = useBillingAddress.FirstName,
                    LastName        = useBillingAddress.LastName,
                    StreetAddress   = useBillingAddress.Address1,
                    ExtendedAddress = useBillingAddress.Address2,
                    Locality        = useBillingAddress.City,
                    Region          = useBillingAddress.State,
                    PostalCode      = useBillingAddress.Zip,
                    CountryName     = useBillingAddress.Country
                },
                Channel = BN
            };

            var transactionResult = gateway.Transaction.Sale(transactionRequest);

            if (transactionResult.IsSuccess())
            {
                authorizationTransID = transactionResult.Target.Id;
                authorizationCode    = transactionResult.Target.ProcessorAuthorizationCode ?? string.Empty;
                authorizationResult  = transactionResult.Target.ProcessorResponseText ?? string.Empty;
                avsResult            = transactionResult.Target.AvsPostalCodeResponseCode ?? string.Empty;

                //We don't have any card details yet - fill some of that in with what Braintree gives us back.
                if (transactionResult.Target.PaymentInstrumentType == GWBraintree.PaymentInstrumentType.CREDIT_CARD)
                {
                    useBillingAddress.CardNumber          = transactionResult.Target.CreditCard.LastFour;
                    useBillingAddress.CardType            = transactionResult.Target.CreditCard.CardType.ToString().ToUpperInvariant();
                    useBillingAddress.CardExpirationMonth = transactionResult.Target.CreditCard.ExpirationMonth;
                    useBillingAddress.CardExpirationYear  = transactionResult.Target.CreditCard.ExpirationYear;
                    useBillingAddress.UpdateDB();
                }
            }
            else
            {
                result = transactionResult.Message;
            }

            return(result);
        }
예제 #19
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);
        }
예제 #20
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 X_Login = AppLogic.AppConfig("eProcessingNetwork_X_LOGIN");

            if (X_Login.Trim().Equals("REGISTRY", StringComparison.InvariantCultureIgnoreCase))
            {
                WindowsRegistry reg = new WindowsRegistry(AppLogic.AppConfig("EncryptKey.RegistryLocation"));
                X_Login = reg.Read("eProcessingNetwork_X_LOGIN");
                reg     = null;
            }

            String X_TranKey = AppLogic.AppConfig("eProcessingNetwork_X_TRAN_KEY");

            if (X_TranKey.Trim().Equals("REGISTRY", StringComparison.InvariantCultureIgnoreCase))
            {
                WindowsRegistry reg = new WindowsRegistry(AppLogic.AppConfig("EncryptKey.RegistryLocation"));
                X_TranKey = reg.Read("eProcessingNetwork_X_TRAN_KEY");
                reg       = null;
            }

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

            transactionCommand.Append("x_type=" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "AUTH_ONLY", "AUTH_CAPTURE"));

            transactionCommand.Append("&x_login="******"&x_tran_key=" + X_TranKey);
            transactionCommand.Append("&x_version=" + AppLogic.AppConfig("eProcessingNetwork_X_VERSION"));
            transactionCommand.Append("&x_test_request=" + CommonLogic.IIF(useLiveTransactions, "FALSE", "TRUE"));
            transactionCommand.Append("&x_merchant_email=" + Security.UrlEncode(AppLogic.AppConfig("eProcessingNetwork_X_Email")));
            transactionCommand.Append("&x_description=" + Security.UrlEncode(AppLogic.AppConfig("StoreName") + " Order " + OrderNumber.ToString()));

            transactionCommand.Append("&x_method=" + AppLogic.AppConfig("eProcessingNetwork_X_METHOD"));

            transactionCommand.Append("&x_delim_Data=" + AppLogic.AppConfig("eProcessingNetwork_X_DELIM_DATA"));
            transactionCommand.Append("&x_delim_Char=" + AppLogic.AppConfig("eProcessingNetwork_X_DELIM_CHAR"));
            transactionCommand.Append("&x_encap_char=" + AppLogic.AppConfig("eProcessingNetwork_X_ENCAP_CHAR"));
            transactionCommand.Append("&x_relay_response=" + AppLogic.AppConfig("eProcessingNetwork_X_RELAY_RESPONSE"));

            transactionCommand.Append("&x_email_customer=" + AppLogic.AppConfig("eProcessingNetwork_X_Email_CUSTOMER"));
            transactionCommand.Append("&x_recurring_billing=" + AppLogic.AppConfig("eProcessingNetwork_X_RECURRING_BILLING"));

            transactionCommand.Append("&x_amount=" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal));
            transactionCommand.Append("&x_card_num=" + UseBillingAddress.CardNumber);
            if (CardExtraCode.Length != 0)
            {
                transactionCommand.Append("&x_card_code=" + CardExtraCode.Trim());
            }

            transactionCommand.Append("&x_exp_date=" + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + "/" + UseBillingAddress.CardExpirationYear);
            transactionCommand.Append("&x_phone=" + Security.UrlEncode(UseBillingAddress.Phone));
            transactionCommand.Append("&x_fax=");
            transactionCommand.Append("&x_customer_tax_id=");
            transactionCommand.Append("&x_cust_id=" + CustomerID.ToString());
            transactionCommand.Append("&x_invoice_num=" + OrderNumber.ToString());
            transactionCommand.Append("&x_email=" + Security.UrlEncode(UseBillingAddress.EMail));
            transactionCommand.Append("&x_customer_ip=" + CommonLogic.CustomerIpAddress());

            transactionCommand.Append("&x_first_name=" + Security.UrlEncode(UseBillingAddress.FirstName));
            transactionCommand.Append("&x_last_name=" + Security.UrlEncode(UseBillingAddress.LastName));
            transactionCommand.Append("&x_company=" + Security.UrlEncode(UseBillingAddress.Company));
            transactionCommand.Append("&x_address=" + Security.UrlEncode(UseBillingAddress.Address1));
            transactionCommand.Append("&x_city=" + Security.UrlEncode(UseBillingAddress.City));
            transactionCommand.Append("&x_state=" + Security.UrlEncode(UseBillingAddress.State));
            transactionCommand.Append("&x_zip=" + Security.UrlEncode(UseBillingAddress.Zip));
            transactionCommand.Append("&x_country=" + Security.UrlEncode(UseBillingAddress.Country));

            if (UseShippingAddress != null)
            {
                transactionCommand.Append("&x_ship_to_first_name=" + Security.UrlEncode(UseShippingAddress.FirstName));
                transactionCommand.Append("&x_ship_to_last_name=" + Security.UrlEncode(UseShippingAddress.LastName));
                transactionCommand.Append("&x_ship_to_company=" + Security.UrlEncode(UseShippingAddress.Company));
                transactionCommand.Append("&x_ship_to_address=" + Security.UrlEncode(UseShippingAddress.Address1));
                transactionCommand.Append("&x_ship_to_city=" + Security.UrlEncode(UseShippingAddress.City));
                transactionCommand.Append("&x_ship_to_state=" + Security.UrlEncode(UseShippingAddress.State));
                transactionCommand.Append("&x_ship_to_zip=" + Security.UrlEncode(UseShippingAddress.Zip));
                transactionCommand.Append("&x_ship_to_country=" + Security.UrlEncode(UseShippingAddress.Country));
            }

            transactionCommand.Append("&x_customer_ip=" + CommonLogic.CustomerIpAddress());

            if (ECI.Length != 0)
            {
                transactionCommand.Append("&x_authentication_indicator=" + ECI);
                transactionCommand.Append("&x_cardholder_authentication_value=" + CAVV);
            }

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

            // Prepare web request...
            try
            {
                String AuthServer        = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("eProcessingNetwork_LIVE_SERVER"), AppLogic.AppConfig("eProcessingNetwork_TEST_SERVER"));
                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;
                        rawResponseString = "0|||Error Calling eProcessing Network Payment Gateway||||||||";
                    }
                }while (!CallSuccessful && CurrentTry < MaxTries);


                // rawResponseString now has gateway response
                TransactionResponse = rawResponseString;
                String[] statusArray = rawResponseString.Split(AppLogic.AppConfig("eProcessingNetwork_X_DELIM_CHAR").ToCharArray());
                // this seems to be a new item where auth.net is returing quotes around each parameter, so strip them out:
                for (int i = statusArray.GetLowerBound(0); i <= statusArray.GetUpperBound(0); i++)
                {
                    statusArray[i] = statusArray[i].Trim('\"');
                }

                String sql          = String.Empty;
                String replyCode    = statusArray[0].Replace(":", "");
                String responseCode = statusArray[2];
                String approvalCode = statusArray[4];
                String authResponse = statusArray[3];
                String TransID      = statusArray[6];

                AuthorizationCode     = statusArray[4];
                AuthorizationResult   = rawResponseString;
                AuthorizationTransID  = statusArray[6];
                AVSResult             = statusArray[5];
                TransactionCommandOut = transactionCommand.ToString().Replace(X_TranKey, "*".PadLeft(X_TranKey.Length));

                if (replyCode == "1")
                {
                    result = AppLogic.ro_OK;
                }
                else
                {
                    result = authResponse;
                    if (result.Length == 0)
                    {
                        result = "Unspecified Error";
                    }
                    else
                    {
                        result = result.Replace("account", "card");
                        result = result.Replace("Account", "Card");
                        result = result.Replace("ACCOUNT", "CARD");
                    }
                }
            }
            catch
            {
                result = "Error calling eProcessing Network gateway. Please retry your order in a few minutes or select another checkout payment option.";
            }
            return(result);
        }
예제 #21
0
        public override string ProcessCard(
            int orderNumber,
            int customerId,
            decimal orderTotal,
            bool useLiveTransactions,
            TransactionModeEnum transactionMode,
            AspDotNetStorefrontCore.Address billingAddress,
            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             = string.Empty;
            authorizationResult   = string.Empty;
            authorizationCode     = string.Empty;
            authorizationTransId  = string.Empty;
            transactionCommandOut = string.Empty;
            transactionResponse   = string.Empty;

            try
            {
                if (AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency") != "AUD" &&
                    AppConfigProvider.GetAppConfigValue("Localization.StoreCurrency") != "NZD")
                {
                    return("eWAY requires that the store currency be either AUD or NZD.");
                }

                var cardDetails = new CardDetails()
                {
                    Name        = $"{billingAddress.FirstName} {billingAddress.LastName}",
                    Number      = billingAddress.CardNumber,
                    ExpiryMonth = FormatExpiryMonth(billingAddress.CardExpirationMonth),
                    ExpiryYear  = FormatExpiryYear(billingAddress.CardExpirationYear),
                    CVN         = cardExtraCode
                };

                var address = new eWAY.Rapid.Models.Address()
                {
                    Street1    = billingAddress.Address1,
                    Street2    = billingAddress.Address2,
                    City       = billingAddress.City,
                    State      = billingAddress.State,
                    PostalCode = billingAddress.Zip,
                    Country    = AppLogic.GetCountryTwoLetterISOCode(billingAddress.Country),
                };

                var customer = new eWAY.Rapid.Models.Customer()
                {
                    FirstName   = billingAddress.FirstName,
                    LastName    = billingAddress.LastName,
                    Email       = billingAddress.EMail,
                    Phone       = billingAddress.Phone,
                    CardDetails = cardDetails,
                    Address     = address
                };

                var paymentDetails = new PaymentDetails()
                {
                    TotalAmount   = DecimalToFixedPoint(orderTotal),
                    InvoiceNumber = orderNumber.ToString(),
                    CurrencyCode  = Currency.GetDefaultCurrency()
                };

                var transaction = new Transaction()
                {
                    Customer        = customer,
                    PaymentDetails  = paymentDetails,
                    TransactionType = TransactionTypes.Purchase,
                    Capture         = transactionMode == TransactionModeEnum.authcapture
                                                ? true
                                                : false
                };

                transactionCommandOut = SanitizeTransaction(
                    XmlCommon.SerializeObject(transaction, transaction.GetType()),
                    new Dictionary <string, string>()
                {
                    { $">{billingAddress.CardNumber}</", $">{AppLogic.SafeDisplayCardNumber(billingAddress.CardNumber, "Orders", 0)}</" },
                    { $">{cardExtraCode}</", ">***</" },
                });

                var response = GetRapidClient()
                               .Create(PaymentMethod.Direct, transaction);

                if (response.TransactionStatus == null)
                {
                    return("Error calling payment gateway.");
                }

                transactionResponse = XmlCommon.SerializeObject(response, response.GetType());

                authorizationResult = response.TransactionStatus.ProcessingDetails?.ResponseMessage;

                if ((response.TransactionStatus.Status ?? false) == false)
                {
                    var errorCode = string.IsNullOrWhiteSpace(authorizationResult) &&
                                    response.Errors != null
                                                ? string.Join(" ", response.Errors)
                                                : authorizationResult;

                    return($"There was a problem processing the credit card transaction.  Error code: {errorCode}");
                }

                AVSResult            = response.TransactionStatus.VerificationResult?.CVN.ToString();
                authorizationCode    = response.TransactionStatus.ProcessingDetails.AuthorisationCode;
                authorizationTransId = response.TransactionStatus.TransactionID.ToString();
            }
            catch (Exception exception)
            {
                SysLog.LogException(exception, MessageTypeEnum.GeneralException, MessageSeverityEnum.Error);
                return("Error calling payment gateway.");
            }

            return(AppLogic.ro_OK);
        }
예제 #22
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)
        {
            Customer c       = null;
            Boolean  isVault = String.IsNullOrEmpty(UseBillingAddress.CardNumber);

            if (isVault)
            {
                c = new Customer(CustomerID);
            }
            return(this.ProcessCard(OrderNumber, CustomerID, OrderTotal, useLiveTransactions, TransactionMode, UseBillingAddress, CardExtraCode, UseShippingAddress, CAVV, ECI, XID, out AVSResult, out AuthorizationResult, out AuthorizationCode, out AuthorizationTransID, out TransactionCommandOut, out TransactionResponse, isVault, c));
        }
예제 #23
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 = "Error";

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

            String sOrderNumber = OrderNumber.ToString();

            if (AppLogic.AppConfigBool("eSelectPlus.randomizeOrderNumberForTesting") && !useLiveTransactions)
            {
                Random r = new Random();
                sOrderNumber = "r" + r.Next(0, 9999999);
            }

            String crypt   = AppLogic.AppConfig("eSelectPlus.crypt");
            String sAmount = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);

            if (sAmount.StartsWith("."))
            {
                sAmount = "0" + sAmount;
            }

            String          signedPARes = String.Empty;
            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;
            }

            String CardNumber  = UseBillingAddress.CardNumber.Trim();
            String expire_date = CommonLogic.IIF(UseBillingAddress.CardExpirationYear.PadLeft(2, '0').Length > 2, UseBillingAddress.CardExpirationYear.PadLeft(2, '0').Substring(2, 2), UseBillingAddress.CardExpirationYear.PadLeft(2, '0')) + UseBillingAddress.CardExpirationMonth.PadLeft(2, '0');

            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)
                {
                    // check for enrollment
                    string  reqXID = sOrderNumber.PadLeft(20, '0'); // must be 20 chars
                    esp.txn reqTxn = new esp.txn();
                    reqTxn.xid         = reqXID;
                    reqTxn.amount      = sAmount;
                    reqTxn.pan         = CardNumber;
                    reqTxn.expdate     = expire_date;
                    reqTxn.MD          = sOrderNumber;
                    reqTxn.merchantUrl = string.Format("{0}{1}",
                                                       AppLogic.GetStoreHTTPLocation(useSsl: true, includeScriptLocation: true, noVirtualNoSlash: true),
                                                       DependencyResolver.Current.GetService <UrlHelper>().Action(
                                                           actionName: ActionNames.ThreeDSecureReturn,
                                                           controllerName: ControllerNames.ThreeDSecure));

                    reqTxn.accept    = CommonLogic.ServerVariables("HTTP_ACCEPT");
                    reqTxn.userAgent = CommonLogic.ServerVariables("HTTP_USER_AGENT");

                    string resultMPI = sendRequestMPI(useLiveTransactions, reqTxn);

                    esp.MpiResponse respMPI = null;
                    if (resultMPI != null)
                    {
                        respMPI = DeserializeResponseMPI(resultMPI);
                    }

                    if (respMPI != null)
                    {
                        TransactionResponse = XmlCommon.PrettyPrintXml(resultMPI);
                        if (respMPI.message == "Y")
                        {
                            // enrolled, must authenticate
                            cSession["3DSecure.CustomerID"]  = CustomerID.ToString();
                            cSession["3DSecure.OrderNumber"] = sOrderNumber;
                            cSession["3DSecure.MD"]          = sOrderNumber;
                            cSession["3DSecure.ACSUrl"]      = respMPI.ACSUrl;
                            cSession["3DSecure.paReq"]       = respMPI.PaReq;
                            cSession["3DSecure.XID"]         = reqXID;
                            cSession.UpdateCustomerSession(null, null);
                            result = AppLogic.ro_3DSecure; // This is what triggers the 3D Secure IFRAME to be used.
                            return(result);
                        }
                        else if (respMPI.message == "N")
                        {
                            // not enrolled
                            crypt = "6";
                        }
                        else if (respMPI.message == "U")
                        {
                            // non-participating card type
                            crypt = "7";
                        }
                    }
                }
                else
                {
                    // this is round two for authenticated buyers
                    esp.acs reqACS = new esp.acs();
                    reqACS.MD    = sOrderNumber;
                    reqACS.PaRes = signedPARes;

                    string resultMPI = sendRequestMPI(useLiveTransactions, reqACS);

                    esp.MpiResponse respMPI = null;
                    if (resultMPI != null)
                    {
                        respMPI = DeserializeResponseMPI(resultMPI);
                    }

                    if (respMPI != null)
                    {
                        TransactionResponse = XmlCommon.PrettyPrintXml(resultMPI);
                        if (respMPI.message == "Y")
                        {
                            // fully authenticated
                            CAVV  = respMPI.cavv;
                            crypt = "5";
                        }
                        else if (respMPI.message == "A")
                        {
                            // attempted to verify
                            CAVV  = respMPI.cavv;
                            crypt = "6";
                        }
                        else if (respMPI.message == "N")
                        {
                            // failed to verify
                            return("Authentication failed. Please try again or choose a different payment method.");
                        }

                        if (CAVV.Length != 0)
                        {
                            // encode it to store in the session, it will be decoded before being saved to the database
                            byte[] str = Encoding.UTF8.GetBytes("MPI=" + respMPI.message + ", CAVV=" + CAVV);
                            cSession["3DSecure.LookupResult"] = Convert.ToBase64String(str);
                        }
                    }
                }
            }

            esp.billing bill = new AspDotNetStorefrontGateways.Processors.esp.billing();
            bill.first_name   = UseBillingAddress.FirstName;
            bill.last_name    = UseBillingAddress.LastName;
            bill.company_name = UseBillingAddress.Company;
            bill.address      = UseBillingAddress.Address1;
            bill.city         = UseBillingAddress.City;
            bill.province     = UseBillingAddress.State;
            bill.postal_code  = UseBillingAddress.Zip;
            bill.country      = UseBillingAddress.Country;
            bill.phone_number = UseBillingAddress.Phone;

            esp.shipping ship = null;
            if (UseShippingAddress != null)
            {
                ship              = new esp.shipping();
                ship.first_name   = UseShippingAddress.FirstName;
                ship.last_name    = UseShippingAddress.LastName;
                ship.company_name = UseShippingAddress.Company;
                ship.address      = UseShippingAddress.Address1;
                ship.city         = UseShippingAddress.City;
                ship.province     = UseShippingAddress.State;
                ship.postal_code  = UseShippingAddress.Zip;
                ship.country      = UseShippingAddress.Country;
                ship.phone_number = UseShippingAddress.Phone;
            }

            esp.cust_info cst = new esp.cust_info();
            cst.billing  = bill;
            cst.shipping = ship;
            cst.email    = UseBillingAddress.EMail;

            esp.avs_info avs = null;
            if (AppLogic.AppConfigBool("eSelectPlus.includeAVS"))
            {
                avs = new esp.avs_info();
                int iSpace = UseBillingAddress.Address1.IndexOf(" ");
                if (iSpace > 0)
                {
                    avs.avs_street_number = UseBillingAddress.Address1.Substring(0, iSpace);
                    avs.avs_street_name   = UseBillingAddress.Address1.Substring(iSpace + 1);
                }
                else
                {
                    avs.avs_street_name = UseBillingAddress.Address1;
                }
                avs.avs_zipcode = UseBillingAddress.Zip;
            }

            esp.cvd_info cvd = null;
            if (CardExtraCode.Trim().Length != 0)
            {
                cvd = new esp.cvd_info();
                cvd.cvd_indicator = "1";
                cvd.cvd_value     = CardExtraCode.Trim();
            }

            object oReqItem = null;



            if (TransactionMode == TransactionModeEnum.auth)
            {
                if (CAVV.Length != 0)
                {
                    esp.cavv_preauth cavvPreAuth = new esp.cavv_preauth();
                    cavvPreAuth.order_id  = sOrderNumber;
                    cavvPreAuth.cust_id   = CustomerID.ToString();
                    cavvPreAuth.amount    = sAmount;
                    cavvPreAuth.pan       = CardNumber;
                    cavvPreAuth.expdate   = expire_date;
                    cavvPreAuth.cavv      = CAVV;
                    cavvPreAuth.avs_info  = avs;
                    cavvPreAuth.cvd_info  = cvd;
                    cavvPreAuth.cust_info = cst;

                    oReqItem = cavvPreAuth;
                }
                else
                {
                    esp.preauth preAuthTxn = new esp.preauth();
                    preAuthTxn.order_id   = sOrderNumber;
                    preAuthTxn.cust_id    = CustomerID.ToString();
                    preAuthTxn.amount     = sAmount;
                    preAuthTxn.pan        = CardNumber;
                    preAuthTxn.expdate    = expire_date;
                    preAuthTxn.avs_info   = avs;
                    preAuthTxn.cvd_info   = cvd;
                    preAuthTxn.cust_info  = cst;
                    preAuthTxn.crypt_type = crypt;

                    oReqItem = preAuthTxn;
                }
            }
            else
            {
                if (CAVV.Length != 0)
                {
                    esp.cavv_purchase cavvPurchase = new esp.cavv_purchase();
                    cavvPurchase.order_id  = sOrderNumber;
                    cavvPurchase.cust_id   = CustomerID.ToString();
                    cavvPurchase.amount    = sAmount;
                    cavvPurchase.pan       = CardNumber;
                    cavvPurchase.expdate   = expire_date;
                    cavvPurchase.cavv      = CAVV;
                    cavvPurchase.avs_info  = avs;
                    cavvPurchase.cvd_info  = cvd;
                    cavvPurchase.cust_info = cst;

                    oReqItem = cavvPurchase;
                }
                else
                {
                    esp.purchaseTxn purchaseTxn = new esp.purchaseTxn();
                    purchaseTxn.order_id   = sOrderNumber;
                    purchaseTxn.cust_id    = CustomerID.ToString();
                    purchaseTxn.amount     = sAmount;
                    purchaseTxn.pan        = CardNumber;
                    purchaseTxn.expdate    = expire_date;
                    purchaseTxn.crypt_type = crypt;
                    purchaseTxn.avs_info   = avs;
                    purchaseTxn.cvd_info   = cvd;
                    purchaseTxn.cust_info  = cst;

                    oReqItem = purchaseTxn;
                }
            }

            try
            {
                string sResponse = sendRequest(useLiveTransactions, oReqItem);

                esp.response resp = null;
                if (sResponse != null)
                {
                    resp = DeserializeResponse(sResponse);

                    if (resp != null)
                    {
                        TransactionResponse = XmlCommon.PrettyPrintXml(sResponse);
                        esp.receipt respReceipt = (esp.receipt)resp.receipt[0];
                        result            = respReceipt.Message;
                        AuthorizationCode = respReceipt.AuthCode;
                        if (AuthorizationCode == null)
                        {
                            AuthorizationCode = String.Empty;
                        }
                        try
                        {
                            AuthorizationResult = (System.Int32.Parse(respReceipt.ResponseCode).ToString());
                            if (AuthorizationResult == null)
                            {
                                AuthorizationResult = String.Empty;
                            }
                        }
                        catch
                        {
                            AuthorizationResult = String.Empty;
                        }
                        AuthorizationTransID = respReceipt.TransID;
                        if (AuthorizationTransID == null || AuthorizationTransID == "null")
                        {
                            AuthorizationTransID = String.Empty;
                        }
                        AVSResult = respReceipt.AvsResultCode;
                        if (AVSResult == null || AVSResult == "null")
                        {
                            AVSResult = String.Empty;
                        }
                        if (respReceipt.CvdResultCode != null && respReceipt.CvdResultCode != "null")
                        {
                            AVSResult += ", CVD Result: " + respReceipt.CvdResultCode;
                        }
                        if (AuthorizationResult != String.Empty && System.Int32.Parse(AuthorizationResult) < 50)
                        {
                            result = AppLogic.ro_OK;

                            if (crypt != AppLogic.AppConfig("eSelectPlus.crypt"))
                            {
                                // we need to store the crypt if it is not the default value
                                // this gets parsed elsewhere so don't modify unless you know what you are doing
                                AuthorizationCode += ", " + cryptLabel + crypt;
                            }
                        }
                        else
                        {
                            result = AppLogic.GetString("gw.moneris.code." + AuthorizationResult, UseBillingAddress.SkinID, UseBillingAddress.LocaleSetting);
                            if (result == "gw.moneris.code." + AuthorizationResult)
                            {
                                result = "Card not accepted. Please try again or choose a different payment method.";
                            }
                        }
                    }
                    else
                    {
                        // failed to Deserialize
                        result = "System error. Unexpected response from payment gateway.";
                    }
                }
                else
                {
                    // failed to communicate
                    result = "System error. Failed to communicate to payment gateway.";
                    return(result);
                }
            }
            catch
            {
                result = "System error. Communications to payment gateway aborted unexpectedly.";
            }

            if (result != AppLogic.ro_OK && TransactionResponse.Length == 0)
            {
                TransactionResponse = result;
            }
            return(result);
        }
예제 #24
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)
        {
            var result   = AppLogic.ro_OK;
            var session  = new CustomerSession(customerID);
            var customer = new Customer(customerID);
            var shippingTwoLetterCountryCode = AppLogic.GetCountryTwoLetterISOCode(customer.PrimaryShippingAddress.Country);
            var billingTwoLetterCountryCode  = AppLogic.GetCountryTwoLetterISOCode(customer.PrimaryBillingAddress.Country);

            authorizationCode     = string.Empty;
            authorizationResult   = string.Empty;
            authorizationTransID  = string.Empty;
            avsResult             = string.Empty;
            transactionCommandOut = string.Empty;
            transactionResponse   = string.Empty;
            var threeDSecureEnabled = AppConfigProvider.GetAppConfigValue <bool>("SagePayPi.3dSecureEnabled");
            var isRecurringOrder    = TransactionType != null && TransactionType.EqualsIgnoreCase("repeat");

            if (isRecurringOrder)
            {
                //process recurring order charge and set the result
                if (TransactionId != null)
                {
                    var repeatJsonObject = new JObject(
                        new JProperty("transactionType", "Repeat"),
                        new JProperty("referenceTransactionId", TransactionId),
                        new JProperty("vendorTxCode", orderNumber.ToString()),
                        new JProperty("amount", GetSmallestCurrencyUnit(orderTotal, Localization.StoreCurrency())),
                        new JProperty("currency", Localization.StoreCurrency()),
                        new JProperty("description", $"{HttpContext.Current.Server.UrlEncode(AppConfigProvider.GetAppConfigValue("StoreName"))} Order {orderNumber}"),
                        new JProperty("shippingDetails",
                                      new JObject(
                                          new JProperty("recipientFirstName", customer.PrimaryShippingAddress.FirstName),
                                          new JProperty("recipientLastName", customer.PrimaryShippingAddress.LastName),
                                          new JProperty("shippingAddress1", customer.PrimaryShippingAddress.Address1),
                                          new JProperty("shippingAddress2", customer.PrimaryShippingAddress.Address2),
                                          new JProperty("shippingCity", customer.PrimaryShippingAddress.City),
                                          new JProperty("shippingPostalCode", shippingTwoLetterCountryCode.EqualsIgnoreCase("IE")
                                                                        ? string.Empty
                                                                        : customer.PrimaryShippingAddress.Zip),
                                          new JProperty("shippingCountry", AppLogic.GetCountryTwoLetterISOCode(customer.PrimaryShippingAddress.Country)),
                                          new JProperty("shippingState", shippingTwoLetterCountryCode.EqualsIgnoreCase("US")
                                                                        ? GetStateAbbreviationById(customer.PrimaryShippingAddress.StateID)
                                                                        : string.Empty)
                                          )
                                      )
                        );
                    var url = (useLiveTransactions
                                                ? $"{AppConfigProvider.GetAppConfigValue("SagePayPi.LiveUrl")}transactions"
                                                : $"{AppConfigProvider.GetAppConfigValue("SagePayPi.TestUrl")}transactions");

                    var apiResponse       = SagePayPiApiCall(repeatJsonObject.ToString(), url, "POST");
                    var formattedResponse = JObject.Parse(apiResponse);
                    var responseHasError  = ResponseHasError(formattedResponse, "status", "ok");

                    transactionCommandOut = $"URL: {url}, Request: {repeatJsonObject}";
                    transactionResponse   = formattedResponse.ToString();

                    if (responseHasError)
                    {
                        result = GetResponseError(formattedResponse, "statusDetail", customerID);

                        if (result.EqualsIgnoreCase(StringResourceProvider.GetString("sagepaypi.error.unknownresponseerror")))
                        {
                            result = GetResponseError(formattedResponse, "description", customerID);
                        }

                        if (result.EqualsIgnoreCase(StringResourceProvider.GetString("sagepaypi.error.unknownresponseerror")))
                        {
                            result = GetResponseError(formattedResponse, "errors", customerID);
                        }

                        return($"{StringResourceProvider.GetString("admin.sagepaypi.transaction.repeaterror")} {result}");
                    }
                    else
                    {
                        //Get the checkout context so we can use the shipping method the customer chose
                        authorizationTransID = formattedResponse["transactionId"].ToString() ?? string.Empty;
                        authorizationCode    = formattedResponse["bankAuthorisationCode"].ToString() ?? string.Empty;
                        authorizationResult  = formattedResponse["statusDetail"].ToString() ?? string.Empty;
                        avsResult            = string.Empty;

                        useBillingAddress.CardType   = formattedResponse["paymentMethod"]["card"]["cardType"].ToString();
                        useBillingAddress.CardNumber = formattedResponse["paymentMethod"]["card"]["lastFourDigits"].ToString();
                        useBillingAddress.UpdateDB();

                        //Update the transaction id on the original order. This needs freshened up because the Sage Pay gateway archives all
                        //transactions that are older than 2 years old.
                        if (RecurringOrderNumberOriginal > 0 && !string.IsNullOrEmpty(authorizationTransID))
                        {
                            UpdateOriginalTransactionID(RecurringOrderNumberOriginal, authorizationTransID);
                        }
                    }
                }
                else
                {
                    result = $"{StringResourceProvider.GetString("admin.sagepaypi.transaction.repeaterror")} {StringResourceProvider.GetString("admin.sagepaypi.transaction.repeatnotransactionid")}";
                }
            }
            else
            {
                //Make a transaction, if 3d secure is required it will be returned here
                if ((threeDSecureEnabled &&
                     session[AppLogic.SagePayPi3dSecureKey].EqualsIgnoreCase("false") &&
                     session[AppLogic.SagePayPiPaymentMethod].EqualsIgnoreCase("creditcard")) ||
                    (!threeDSecureEnabled))
                {
                    var jsonObject = new JObject(
                        new JProperty("transactionType", AppLogic.TransactionModeIsAuthOnly()
                                                                                                                        ? "Deferred"
                                                                                                                        : "Payment"),
                        new JProperty("paymentMethod",
                                      new JObject(
                                          new JProperty("card",
                                                        new JObject(
                                                            new JProperty("merchantSessionKey", session[AppLogic.SagePayPiMerchantSessionKey]),
                                                            new JProperty("cardIdentifier", session[AppLogic.SagePayPiCardIdentifier]),
                                                            new JProperty("save", true)
                                                            )
                                                        )
                                          )
                                      ),
                        new JProperty("vendorTxCode", orderNumber.ToString()),
                        new JProperty("amount", GetSmallestCurrencyUnit(orderTotal, Localization.StoreCurrency())),
                        new JProperty("currency", Localization.StoreCurrency()),
                        new JProperty("description", $"{HttpContext.Current.Server.UrlEncode(AppConfigProvider.GetAppConfigValue("StoreName"))} Order {orderNumber}"),
                        new JProperty("apply3DSecure", "UseMSPSetting"),
                        new JProperty("applyAvsCvcCheck", "UseMSPSetting"),
                        new JProperty("customerFirstName", customer.PrimaryBillingAddress.FirstName),
                        new JProperty("customerLastName", customer.PrimaryBillingAddress.LastName),
                        new JProperty("customerEmail", customer.EMail),
                        new JProperty("customerPhone", customer.Phone),
                        new JProperty("billingAddress",
                                      new JObject(
                                          new JProperty("address1", customer.PrimaryBillingAddress.Address1),
                                          new JProperty("address2", customer.PrimaryBillingAddress.Address2),
                                          new JProperty("city", customer.PrimaryBillingAddress.City),
                                          new JProperty("postalCode", billingTwoLetterCountryCode.EqualsIgnoreCase("IE")
                                                                ? string.Empty
                                                                : customer.PrimaryBillingAddress.Zip),
                                          new JProperty("country", AppLogic.GetCountryTwoLetterISOCode(customer.PrimaryBillingAddress.Country)),
                                          new JProperty("state", billingTwoLetterCountryCode.EqualsIgnoreCase("US")
                                                                ? GetStateAbbreviationById(customer.PrimaryBillingAddress.StateID)
                                                                : string.Empty)
                                          )
                                      ),
                        new JProperty("shippingDetails",
                                      new JObject(
                                          new JProperty("recipientFirstName", customer.PrimaryShippingAddress.FirstName),
                                          new JProperty("recipientLastName", customer.PrimaryShippingAddress.LastName),
                                          new JProperty("shippingAddress1", customer.PrimaryShippingAddress.Address1),
                                          new JProperty("shippingAddress2", customer.PrimaryShippingAddress.Address2),
                                          new JProperty("shippingCity", customer.PrimaryShippingAddress.City),
                                          new JProperty("shippingPostalCode", shippingTwoLetterCountryCode.EqualsIgnoreCase("IE")
                                                                ? string.Empty
                                                                : customer.PrimaryShippingAddress.Zip),
                                          new JProperty("shippingCountry", AppLogic.GetCountryTwoLetterISOCode(customer.PrimaryShippingAddress.Country)),
                                          new JProperty("shippingState", shippingTwoLetterCountryCode.EqualsIgnoreCase("US")
                                                                ? GetStateAbbreviationById(customer.PrimaryShippingAddress.StateID)
                                                                : string.Empty)
                                          )
                                      ),
                        new JProperty("entryMethod", "Ecommerce")
                        );

                    var url = (useLiveTransactions
                                                ? $"{AppConfigProvider.GetAppConfigValue("SagePayPi.LiveUrl")}transactions"
                                                : $"{AppConfigProvider.GetAppConfigValue("SagePayPi.TestUrl")}transactions");

                    var apiResponse       = SagePayPiApiCall(jsonObject.ToString(), url, "POST");
                    var formattedResponse = JObject.Parse(apiResponse);
                    var responseHasError  = ResponseHasError(formattedResponse, "status", "ok");

                    if (responseHasError)
                    {
                        transactionCommandOut = $"URL: {url}, Request: {jsonObject}";
                        transactionResponse   = formattedResponse.ToString();

                        if (AppConfigProvider.GetAppConfigValue <bool>("SagePayPI.CustomerFriendlyErrors"))
                        {
                            ClearPaymentMethod(customerID);
                            return($"{StringResourceProvider.GetString("sagepaypi.transaction.didnotprocess")} {StringResourceProvider.GetString("sagepaypi.error.reentercarddetails")}");
                        }

                        result = GetResponseError(formattedResponse, "statusDetail", customerID);

                        if (result.EqualsIgnoreCase(StringResourceProvider.GetString("sagepaypi.error.unknownresponseerror")))
                        {
                            result = GetResponseError(formattedResponse, "description", customerID);
                        }

                        if (result.EqualsIgnoreCase(StringResourceProvider.GetString("sagepaypi.error.unknownresponseerror")))
                        {
                            result = GetResponseError(formattedResponse, "errors", customerID);
                        }

                        ClearPaymentMethod(customerID);
                        return($"{StringResourceProvider.GetString("sagepaypi.transaction.paymenterror")} {result.TrimEnd('.')}. {StringResourceProvider.GetString("sagepaypi.error.reentercarddetails")}");
                    }
                    else
                    {
                        session[AppLogic.SagePayPiMd] = formattedResponse["transactionId"].ToString();

                        //Implement 3-d secure logic if it is required per the transaction response
                        if (threeDSecureEnabled &&
                            session[AppLogic.SagePayPi3dSecureKey].EqualsIgnoreCase("false") &&
                            session[AppLogic.SagePayPiPaymentMethod].EqualsIgnoreCase("creditcard") &&
                            formattedResponse["status"].ToString().EqualsIgnoreCase("3dauth"))                        //Do a 3DSecure redirect
                        {
                            session[AppLogic.SagePayPiPaReq]   = formattedResponse["paReq"].ToString();
                            session[AppLogic.SagePayPiTermUrl] = string.Format("{0}{1}",
                                                                               HttpContext
                                                                               .Current
                                                                               .Request
                                                                               .Url
                                                                               .AbsoluteUri
                                                                               .Replace(
                                                                                   HttpContext
                                                                                   .Current
                                                                                   .Request
                                                                                   .Url
                                                                                   .LocalPath,
                                                                                   string.Empty),
                                                                               AppConfigProvider.GetAppConfigValue("SagePayPi.3DSecureTermUrl"));
                            session[AppLogic.SagePayPiAcsUrl] = formattedResponse["acsUrl"].ToString();
                            var sagePayPiThreeDSecureViewModel = new SagePayPiThreeDSecureViewModel(
                                paReq: formattedResponse["paReq"].ToString(),
                                termUrl: string.Format("{0}{1}",
                                                       HttpContext
                                                       .Current
                                                       .Request
                                                       .Url
                                                       .AbsoluteUri
                                                       .Replace(
                                                           HttpContext
                                                           .Current
                                                           .Request
                                                           .Url
                                                           .LocalPath,
                                                           string.Empty),
                                                       AppConfigProvider.GetAppConfigValue("SagePayPi.3DSecureTermUrl")),
                                md: formattedResponse["transactionId"].ToString(),
                                acsUrl: formattedResponse["acsUrl"].ToString()
                                );
                            session["3DSecure.OrderNumber"] = orderNumber.ToString();
                            result = AppLogic.ro_3DSecure;
                            return(result);
                        }
                    }
                }

                //Do a final retrieval of the completed transaction and record some of the results
                var emptyObject    = new JObject();
                var transactionUrl = (useLiveTransactions
                                        ? $"{AppConfigProvider.GetAppConfigValue("SagePayPi.LiveUrl")}transactions/{session[AppLogic.SagePayPiMd]}"
                                        : $"{AppConfigProvider.GetAppConfigValue("SagePayPi.TestUrl")}transactions/{session[AppLogic.SagePayPiMd]}");

                var apiTransactionResponse       = SagePayPiApiCall(emptyObject.ToString(), transactionUrl, "GET");
                var formattedTransactionResponse = JObject.Parse(apiTransactionResponse);
                var transactionResponseError     = ResponseHasError(formattedTransactionResponse, "status", "ok");

                transactionCommandOut = $"GET Method - URL: {transactionUrl}";
                transactionResponse   = formattedTransactionResponse.ToString();

                if (transactionResponseError)
                {
                    if (AppConfigProvider.GetAppConfigValue <bool>("SagePayPI.CustomerFriendlyErrors"))
                    {
                        result = $"{StringResourceProvider.GetString("sagepaypi.transaction.didnotprocess")} {StringResourceProvider.GetString("sagepaypi.error.reentercarddetails")}";
                    }
                    else
                    {
                        result = string.Format(
                            "{0} 3-D Secure status: {1}.",
                            GetResponseError(formattedTransactionResponse, "statusDetail", customerID),
                            GetThreeDSecureStatus(formattedTransactionResponse["3DSecure"]["status"].ToString()));
                    }
                }
                else
                {
                    var threeDSecureStatus = formattedTransactionResponse["3DSecure"]["status"].ToString();

                    if (formattedTransactionResponse["status"].ToString().EqualsIgnoreCase("ok"))
                    {
                        authorizationTransID = formattedTransactionResponse["transactionId"].ToString() ?? string.Empty;
                        authorizationCode    = formattedTransactionResponse["bankAuthorisationCode"].ToString() ?? string.Empty;
                        authorizationResult  = formattedTransactionResponse["statusDetail"].ToString() ?? string.Empty;
                        avsResult            = string.Empty;

                        useBillingAddress.CardType   = formattedTransactionResponse["paymentMethod"]["card"]["cardType"].ToString();
                        useBillingAddress.CardNumber = formattedTransactionResponse["paymentMethod"]["card"]["lastFourDigits"].ToString();
                        useBillingAddress.UpdateDB();
                    }
                    else
                    {
                        //if the transaction did not retrieve properly, put an error from sage pay into result
                        result = formattedTransactionResponse["statusDetail"].ToString();
                    }

                    if (threeDSecureEnabled && threeDSecureStatus.ToString().EqualsIgnoreCase("Error"))
                    {
                        //We need to stop processing the order if 3d secure is required but had an error
                        result = $"{StringResourceProvider.GetString("sagepaypi.threedsecure.error")} {StringResourceProvider.GetString("sagepaypi.error.reentercarddetails")}";

                        ClearPaymentMethod(customerID);
                    }
                }
            }
            return(result);
        }
예제 #25
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;

            SecureNetSvc.SecureNetPayment    oPG = new SecureNetPayment();
            SecureNetSvc.TransactionInfo     oTi = new TransactionInfo();
            SecureNetSvc.TransactionResponse oTr = new TransactionResponse();

            // "https://gateway.securenet.com/payment.asmx"
            oPG.Url = CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), AppLogic.AppConfig("SecureNet.LiveURL"), AppLogic.AppConfig("SecureNet.TestURL"));

            // set oTi values here
            oTi.SecurenetID = AppLogic.AppConfig("SecureNet.ID");
            oTi.SecureKey   = AppLogic.AppConfig("SecureNet.Key");

            oTi.Test    = CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), "FALSE", "TRUE");
            oTi.OrderID = OrderNumber.ToString();
            oTi.Amount  = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
            oTi.Method  = "CC"; // Credit Card

            // AUTH_CAPTURE, AUTH_ONLY, CREDIT, VOID, PRIOR_AUTH_CAPTURE
            oTi.Type = CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), "AUTH_ONLY", "AUTH_CAPTURE");

            oTi.Card_num  = UseBillingAddress.CardNumber;
            oTi.Exp_date  = UseBillingAddress.CardExpirationMonth.PadLeft(2, '0') + UseBillingAddress.CardExpirationYear.ToString().Substring(2, 2); //MMYY
            oTi.Card_code = CardExtraCode;

            oTi.Customer_id = CustomerID.ToString();
            oTi.First_name  = UseBillingAddress.FirstName;
            oTi.Last_name   = UseBillingAddress.LastName;
            oTi.Company     = UseBillingAddress.Company;
            oTi.Address     = UseBillingAddress.Address1;
            oTi.City        = UseBillingAddress.City;
            oTi.State       = UseBillingAddress.State;
            oTi.Zip         = UseBillingAddress.Zip;
            oTi.Country     = UseBillingAddress.Country;
            oTi.Phone       = UseBillingAddress.Phone;
            oTi.Email       = UseBillingAddress.EMail;

            oTi.Invoice_num         = OrderNumber.ToString();
            oTi.Invoice_Description = AppLogic.AppConfig("StoreName");

            if (UseShippingAddress != null)
            {
                oTi.Shipping_First_name = UseShippingAddress.FirstName;
                oTi.Shipping_Last_name  = UseShippingAddress.LastName;
                oTi.Shipping_Company    = UseShippingAddress.Company;
                oTi.Shipping_Address    = UseShippingAddress.Address1 + CommonLogic.IIF(UseShippingAddress.Address2 != "", " " + UseShippingAddress.Address2, "") + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, "");
                oTi.Shipping_City       = UseShippingAddress.City;
                oTi.Shipping_State      = UseShippingAddress.State;
                oTi.Shipping_Zip        = UseShippingAddress.Zip;
                oTi.Shipping_Country    = UseShippingAddress.Country;
            }

            if (!String.IsNullOrEmpty(ECI))
            {
                oTi.MPI_Authentication_Indicator = ECI;
            }

            if (!String.IsNullOrEmpty(CAVV))
            {
                oTi.MPI_Authentication_Value = CAVV;
            }

            oTr = oPG.Process(oTi);       // Run transaction

            if (oTr.Response_Code == "1") // 1=Approved, 2=Declined, 3=Error
            {
                AuthorizationTransID = oTr.Transaction_ID;
                AuthorizationCode    = "Response Code: " + oTr.Response_Code + ", Reason Code: " + oTr.Response_Reason_Code;

                if (!String.IsNullOrEmpty(oTr.AVS_Result_Code))
                {
                    AVSResult = oTr.AVS_Result_Code;
                }

                if (!String.IsNullOrEmpty(oTr.Card_Code_Response_Code))
                {
                    if (AVSResult.Length > 0)
                    {
                        AVSResult += ", ";
                    }
                    AVSResult += "ExtraCode: " + oTr.Card_Code_Response_Code;
                }

                if (!String.IsNullOrEmpty(oTr.CAVV_Response_Code))
                {
                    if (AVSResult.Length > 0)
                    {
                        AVSResult += ", ";
                    }
                    AVSResult += "CAVV: " + oTr.CAVV_Response_Code;
                }

                AuthorizationResult = oTr.Response_Reason_Text + ", Approval Code: " + oTr.Approval_Code;
                result = AppLogic.ro_OK;
            }
            else
            {
                AuthorizationResult = "Error: [" + oTr.Response_Code + "] " + oTr.Response_Reason_Text;
                result = oTr.Response_Reason_Text;
            }

            TransactionCommandOut = XmlCommon.SerializeObject(oTi, oTi.GetType()).Replace(AppLogic.AppConfig("SecureNet.Key") + "</SecureKey>", "*****</SecureKey>");
            TransactionResponse   = XmlCommon.SerializeObject(oTr, oTr.GetType()).Replace(AppLogic.AppConfig("SecureNet.Key") + "</SecureKey>", "*****</SecureKey>");

            return(result);
        }
예제 #26
0
        /// <summary>
        /// Authorizes and/or captures the order thru this gateway
        /// </summary>
        /// <param name="OrderNumber">The order number</param>
        /// <param name="CustomerID">The customer id</param>
        /// <param name="OrderTotal">The order total</param>
        /// <param name="useLiveTransactions">Whether to use live transaction</param>
        /// <param name="TransactionMode">The transaction mode</param>
        /// <param name="UseBillingAddress">The billing address to use</param>
        /// <param name="CardExtraCode">The card extra code</param>
        /// <param name="UseShippingAddress">The shipping address to use</param>
        /// <param name="CAVV">The CAVV</param>
        /// <param name="ECI">The ECI</param>
        /// <param name="XID">The XID</param>
        /// <param name="AVSResult">The AVS result</param>
        /// <param name="AuthorizationResult">The Authorozation result</param>
        /// <param name="AuthorizationCode">The Auhtorization code</param>
        /// <param name="AuthorizationTransID">The Authorixation transaction id</param>
        /// <param name="TransactionCommandOut">The transaction command sent to the gateway</param>
        /// <param name="TransactionResponse">The transaction detail receive from the gateway</param>
        /// <returns>Status</returns>
        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)
        {
            DataSet ds     = null;
            String  result = AppLogic.ro_OK;

            TransactionCommandOut = "";

            TRANSACTION_PROCESSING tp = new TRANSACTION_PROCESSING();

            if (AppLogic.AppConfigBool("UseLiveTransactions"))
            {
                tp.Url = AppLogic.AppConfig("SagePayments.ServiceURL");
            }
            else
            {
                tp.Url = AppLogic.AppConfig("SagePayments.ServiceURLTEST");
            }

            ds = ProcessServiceTransaction(tp, UseBillingAddress, UseShippingAddress, CardExtraCode, CustomerID, OrderTotal, OrderNumber, TransactionMode, ref TransactionCommandOut);

            AVSResult            = ds.Tables[0].Rows[0]["AVS_INDICATOR"].ToString();
            AuthorizationResult  = ds.Tables[0].Rows[0]["MESSAGE"].ToString();
            AuthorizationCode    = ds.Tables[0].Rows[0]["CODE"].ToString();
            AuthorizationTransID = ds.Tables[0].Rows[0]["REFERENCE"].ToString();;
            TransactionResponse  = ds.GetXml();

            if (ds.Tables[0].Rows[0]["APPROVAL_INDICATOR"].ToString() != "A")
            {
                //  Declined
                result = AuthorizationResult;
            }

            return(result);
        }
예제 #27
0
파일: HSBC.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;

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

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

            String BillingISOCode  = String.Empty;
            String ShippingISOCode = String.Empty;

            try
            {
                using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRS("select NumericISOCode from Country where CountryID=" + UseBillingAddress.CountryID, con))
                    {
                        if (rs.Read())
                        {
                            BillingISOCode = rs["NumericISOCode"].ToString();
                        }
                        else
                        {
                            BillingISOCode = "0";
                        }
                    }
                }
            }
            catch { BillingISOCode = "0"; }

            try
            {
                using (SqlConnection con = new SqlConnection(DB.GetDBConn()))
                {
                    con.Open();
                    using (IDataReader rs = DB.GetRS("select NumericISOCode from Country where CountryID=" + UseShippingAddress.CountryID, con))
                    {
                        if (rs.Read())
                        {
                            ShippingISOCode = rs["NumericISOCode"].ToString();
                        }
                        else
                        {
                            ShippingISOCode = "0";
                        }
                    }
                }
            }
            catch { ShippingISOCode = "0"; }

            CustomerSession cSession    = new CustomerSession(CustomerID);
            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 && cSession["3Dsecure.HSBCPASResult"].Length == 0)
            {
                // This is round one, we need to have the customer submit the form to The HSBC PAS (Payer Authentication Service).
                cSession["3Dsecure.HSBCAmountRaw"] = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(".", "");
                cSession["3Dsecure.HSBCAmount"]    = Localization.CurrencyStringForDisplayWithoutExchangeRate(OrderTotal);
                cSession["3DSecure.CustomerID"]    = CustomerID.ToString();
                cSession["3DSecure.OrderNumber"]   = OrderNumber.ToString();
                cSession["3DSecure.MD"]            = OrderNumber.ToString();
                return(AppLogic.ro_3DSecure);
            }

            String TransactionAuthentication = String.Empty;

            if (Try3DSecure && cSession["3Dsecure.HSBCPASResult"].Length != 0)
            {
                // This is round two, we need to submit the authorization request using the PAS details.

                String CcpaResultsCode = cSession["3Dsecure.HSBCPASResult"];
                cSession["3Dsecure.HSBCPASResult"] = String.Empty;
                switch (CcpaResultsCode)
                {
                case "0":
                    /*
                     * Payer authentication was successful. The XID,       Set PayerSecurityLevel to 2.
                     * CAVV, and ECI indicator should be extracted         Set PayerAuthenticationCode to the
                     * and sent with the authorisation request. A          returned CAVV
                     * result code of 0 indicates the transaction is       Set PayerTxnId to the returned XID.
                     * eligible for Chargeback protection.                 Set CardholderPresentCode to 13.
                     */
                    TransactionAuthentication  = "<PayerSecurityLevel>2</PayerSecurityLevel>";
                    TransactionAuthentication += "<PayerAuthenticationCode>" + CAVV + "</PayerAuthenticationCode>";
                    TransactionAuthentication += "<PayerTxnId>" + XID + "</PayerTxnId>";
                    TransactionAuthentication += "<CardholderPresentCode>13</CardholderPresentCode>";
                    break;

                case "1":
                    /*
                     * The cardholder’s card was not within a participating    Set PayerSecurityLevel to 5.
                     * BIN range. Payer authentication was not performed.      Set CardholderPresentCode to 13.
                     */
                    TransactionAuthentication  = "<PayerSecurityLevel>5</PayerSecurityLevel>";
                    TransactionAuthentication += "<CardholderPresentCode>13</CardholderPresentCode>";
                    break;

                case "2":
                    /*
                     * The cardholder was in a participating BIN range, but    Set PayerSecurityLevel to 1.
                     * was not enrolled in 3-D Secure. Payer authentication    Set CardholderPresentCode to 13.
                     * was not performed.
                     */
                    TransactionAuthentication  = "<PayerSecurityLevel>1</PayerSecurityLevel>";
                    TransactionAuthentication += "<CardholderPresentCode>13</CardholderPresentCode>";
                    break;

                case "3":
                    /*
                     * The cardholder was not enrolled in 3-D Secure.          Set PayerSecurityLevel to 6.
                     * However, the cardholder was authenticated using the     Set PayerAuthenticationCode to the
                     * 3-D Secure attempt server. The XID, CAVV, and ECI       returned CAVV
                     * indicator should be extracted and sent with the         Set PayerTxnId to the returned XID.
                     * authorisation request. A result code of 3 indicates the Set CardholderPresentCode to 13.
                     * transaction is eligible for Chargeback protection.
                     */
                    TransactionAuthentication  = "<PayerSecurityLevel>6</PayerSecurityLevel>";
                    TransactionAuthentication += "<PayerAuthenticationCode>" + CAVV + "</PayerAuthenticationCode>";
                    TransactionAuthentication += "<PayerTxnId>" + XID + "</PayerTxnId>";
                    TransactionAuthentication += "<CardholderPresentCode>13</CardholderPresentCode>";
                    break;

                case "4":
                    /*
                     * The cardholder was enrolled in 3-D Secure. A PARes      Try 3-D Secure again or set
                     * has not yet been received for this transaction.         PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "7":
                    /*
                     * The ACS was unable to provide authentication            Set PayerSecurityLevel to 4.
                     * results. The transaction should proceed as a standard
                     * e-commerce transaction.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "8":
                    /*
                     * The CCPA failed to communicate with the                 Try 3-D Secure again or set
                     * Directory Server.                                       PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "9":
                    /*
                     * The CCPA was unable to interpret the results from       Try 3-D Secure again or set
                     * payer authentication or enrolment verification.         PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "10":
                    /*
                     * The CCPA failed to locate or access configuration       Try 3-D Secure again or set
                     * information for this merchant.                          PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "11":
                    /*
                     * Data submitted or configured in the CCPA has failed     Try 3-D Secure again, check input
                     * validation checks.                                      fields, or set PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "12":
                    /*
                     * Unexpected system error from CCPA.                      Try 3-D Secure again or set
                     *                                                      PayerSecurityLevel to 4.
                     */
                    TransactionAuthentication = "<PayerSecurityLevel>4</PayerSecurityLevel>";
                    break;

                case "14":
                    /*
                     * Indicates that card submitted is not recognised, or the     Try 3-D Secure again or proceed as
                     * PAS does not support the card type.                         standard e-commerce transaction
                     *                                                          (i.e. set CardholderPresentCode to 7).
                     */
                    break;
                }
            }
            transactionCommand.Append("<?xml version=\"1.0\"  encoding=\"UTF-8\"?>");
            transactionCommand.Append("<EngineDocList>");
            transactionCommand.Append("<DocVersion>" + AppLogic.AppConfig("HSBC.DocVersion") + "</DocVersion>");
            transactionCommand.Append("<EngineDoc>");
            transactionCommand.Append("<ContentType>OrderFormDoc</ContentType>");
            transactionCommand.Append("<User>");
            if (AppLogic.AppConfig("HSBC.ClientID").Length != 0)
            {
                transactionCommand.Append("<ClientId DataType=\"S32\">" + AppLogic.AppConfig("HSBC.ClientID") + "</ClientId>");
            }
            else
            {
                transactionCommand.Append("<Alias>" + AppLogic.AppConfig("HSBC.ClientAlias") + "</Alias>");
            }
            transactionCommand.Append("<Name>" + AppLogic.AppConfig("HSBC.ClientName") + "</Name>");
            transactionCommand.Append("<Password>" + AppLogic.AppConfig("HSBC.ClientPassword") + "</Password>");
            transactionCommand.Append("</User>");
            transactionCommand.Append("<Instructions>");
            transactionCommand.Append("<Pipeline>" + AppLogic.AppConfig("HSBC.Pipeline") + "</Pipeline>");
            transactionCommand.Append("</Instructions>");
            transactionCommand.Append("<OrderFormDoc>");
            transactionCommand.Append("<Mode>" + CommonLogic.IIF(AppLogic.AppConfigBool("UseLiveTransactions"), AppLogic.AppConfig("HSBC.Mode.Live"), AppLogic.AppConfig("HSBC.Mode.Test")) + "</Mode>");
            transactionCommand.Append("<Consumer>");
            transactionCommand.Append("<PaymentMech>");
            transactionCommand.Append("<Type>CreditCard</Type>");
            transactionCommand.Append("<CreditCard>");
            transactionCommand.Append("<Number>" + UseBillingAddress.CardNumber + "</Number>");
            transactionCommand.AppendFormat("<Expires DataType=\"ExpirationDate\" Locale=\"{0}\">{1}/{2}</Expires>", Localization.StoreCurrencyNumericCode(), UseBillingAddress.CardExpirationMonth.PadLeft(2, '0'), UseBillingAddress.CardExpirationYear.Substring(UseBillingAddress.CardExpirationYear.Length - 2).PadLeft(2, '0'));
            if (CardExtraCode.Length != 0)
            {
                transactionCommand.Append("<Cvv2Indicator>1</Cvv2Indicator>");
                transactionCommand.Append("<Cvv2Val>" + CardExtraCode.Trim() + "</Cvv2Val>");
            }
            if (UseBillingAddress.CardIssueNumber.Length != 0)
            {
                transactionCommand.Append("<IssueNum>" + UseBillingAddress.CardIssueNumber + "</IssueNum>");
            }
            if (UseBillingAddress.CardStartDate.Length != 0)
            {
                transactionCommand.AppendFormat("<StartDate DataType=\"StartDate\">{0}/{1}</StartDate>", UseBillingAddress.CardStartDate.Substring(0, 2), UseBillingAddress.CardStartDate.Substring(UseBillingAddress.CardStartDate.Length - 2, 2));
            }
            transactionCommand.Append("<ExchangeType>1</ExchangeType>");

            transactionCommand.Append("</CreditCard>");
            transactionCommand.Append("</PaymentMech>");
            transactionCommand.Append("<Email>" + XmlCommon.XmlEncode(UseBillingAddress.EMail) + "</Email>");

            transactionCommand.Append("<BillTo>");
            transactionCommand.Append("<Location>");
            transactionCommand.Append("<Email>" + XmlCommon.XmlEncode(UseBillingAddress.EMail) + "</Email>");
            transactionCommand.Append("<TelVoice>" + XmlCommon.XmlEncode(UseBillingAddress.Phone) + "</TelVoice>");
            transactionCommand.Append("<Address>");
            transactionCommand.Append("<City>" + XmlCommon.XmlEncode(UseBillingAddress.City) + "</City>");
            transactionCommand.Append("<Company>" + XmlCommon.XmlEncode(UseBillingAddress.Company) + "</Company>");
            transactionCommand.Append("<Country>" + XmlCommon.XmlEncode(BillingISOCode) + "</Country>");
            transactionCommand.Append("<FirstName>" + XmlCommon.XmlEncode(UseBillingAddress.FirstName) + "</FirstName>");
            transactionCommand.Append("<LastName>" + XmlCommon.XmlEncode(UseBillingAddress.LastName) + "</LastName>");
            transactionCommand.Append("<PostalCode>" + XmlCommon.XmlEncode(UseBillingAddress.Zip) + "</PostalCode>");
            transactionCommand.Append("<StatProv>" + XmlCommon.XmlEncode(UseBillingAddress.State) + "</StatProv>");
            transactionCommand.Append("<Street1>" + XmlCommon.XmlEncode(UseBillingAddress.Address1) + "</Street1>");
            transactionCommand.Append("<Street2>" + XmlCommon.XmlEncode(UseBillingAddress.Address2) + "</Street2>");
            transactionCommand.Append("<Street3>" + XmlCommon.XmlEncode(UseBillingAddress.Suite) + "</Street3>");
            transactionCommand.Append("</Address>");
            transactionCommand.Append("</Location>");
            transactionCommand.Append("</BillTo>");

            transactionCommand.Append("<ShipTo>");
            transactionCommand.Append("<Location>");
            transactionCommand.Append("<Email>" + XmlCommon.XmlEncode(UseShippingAddress.EMail) + "</Email>");
            transactionCommand.Append("<TelVoice>" + XmlCommon.XmlEncode(UseShippingAddress.Phone) + "</TelVoice>");
            transactionCommand.Append("<Address>");
            transactionCommand.Append("<City>" + XmlCommon.XmlEncode(UseShippingAddress.City) + "</City>");
            transactionCommand.Append("<Company>" + XmlCommon.XmlEncode(UseShippingAddress.Company) + "</Company>");
            transactionCommand.Append("<Country>" + XmlCommon.XmlEncode(ShippingISOCode) + "</Country>");
            transactionCommand.Append("<FirstName>" + XmlCommon.XmlEncode(UseShippingAddress.FirstName) + "</FirstName>");
            transactionCommand.Append("<LastName>" + XmlCommon.XmlEncode(UseShippingAddress.LastName) + "</LastName>");
            transactionCommand.Append("<PostalCode>" + XmlCommon.XmlEncode(UseShippingAddress.Zip) + "</PostalCode>");
            transactionCommand.Append("<StatProv>" + XmlCommon.XmlEncode(UseShippingAddress.State) + "</StatProv>");
            transactionCommand.Append("<Street1>" + XmlCommon.XmlEncode(UseShippingAddress.Address1) + "</Street1>");
            transactionCommand.Append("<Street2>" + XmlCommon.XmlEncode(UseShippingAddress.Address2) + "</Street2>");
            transactionCommand.Append("<Street3>" + XmlCommon.XmlEncode(UseShippingAddress.Suite) + "</Street3>");
            transactionCommand.Append("</Address>");
            transactionCommand.Append("</Location>");
            transactionCommand.Append("</ShipTo>");

            transactionCommand.Append("</Consumer>");
            transactionCommand.Append("<Transaction>");
            transactionCommand.Append("<InvNumber>" + OrderNumber.ToString() + "</InvNumber>");
            transactionCommand.Append("<Type>" + CommonLogic.IIF(TransactionMode == TransactionModeEnum.auth, "PreAuth", "Auth") + "</Type>");
            transactionCommand.Append("<CurrentTotals>");
            transactionCommand.Append("<Totals>");
            transactionCommand.Append("<Total DataType=\"Money\" Currency=\"" + Localization.StoreCurrencyNumericCode() + "\">" + Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal).Replace(".", "") + "</Total>");
            transactionCommand.Append("</Totals>");
            transactionCommand.Append("</CurrentTotals>");
            if (TransactionAuthentication.Length != 0)
            {
                transactionCommand.Append(TransactionAuthentication);
            }
            transactionCommand.Append("</Transaction>");
            transactionCommand.Append("</OrderFormDoc>");
            transactionCommand.Append("</EngineDoc>");
            transactionCommand.Append("</EngineDocList>");

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

            // Prepare web request...
            String AuthServer = CommonLogic.IIF(useLiveTransactions, AppLogic.AppConfig("HSBC.Live.Server"), AppLogic.AppConfig("HSBC.Test.Server"));

            WebResponse myResponse;
            String      rawResponseString = String.Empty;

            try
            {
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(AuthServer);
                myRequest.ContentType   = "text/xml;charset=\"utf-8\"";
                myRequest.Accept        = "text/xml";
                myRequest.Method        = "POST";
                myRequest.ContentLength = data.Length;
                Stream newStream = myRequest.GetRequestStream();
                // Send the data.
                newStream.Write(data, 0, data.Length);
                newStream.Close();
                // get the response
                myResponse = myRequest.GetResponse();
                StreamReader sr = new StreamReader(myResponse.GetResponseStream());
                rawResponseString = sr.ReadToEnd();
                // Close and clean up the StreamReader
                sr.Close();
                //Close the Response
                myResponse.Close();
            }
            catch
            {
                result = "NO RESPONSE FROM HSBC GATEWAY!";
            }

            // rawResponseString now has gateway response
            TransactionResponse = rawResponseString;

            AVSResult = String.Empty;

            String replyCode    = String.Empty;
            String approvalCode = String.Empty;
            String authResponse = String.Empty;
            String TransID      = String.Empty;

            XmlDocument responseXml = new XmlDocument();

            try
            {
                responseXml.LoadXml(rawResponseString);

                XmlNode n = responseXml.SelectSingleNode("//Overview");
                replyCode = XmlCommon.XmlField(n, "TransactionStatus");
                String CcErrCode = XmlCommon.XmlField(n, "CcErrCode");
                approvalCode = XmlCommon.XmlField(n, "AuthCode");
                authResponse = XmlCommon.XmlField(n, "Notice");

                if (TransactionAuthentication.Length != 0)
                {
                    // encode it to store in the session, it will be decoded before being saved to the database
                    byte[] str = System.Text.Encoding.UTF8.GetBytes(TransactionAuthentication);
                    cSession["3DSecure.LookupResult"] = Convert.ToBase64String(str);
                }

                if (authResponse.Length == 0)
                {
                    XmlNode n2 = CommonLogic.IsNull(responseXml.SelectSingleNode("//Message/Text"), responseXml.SelectSingleNode("//Transaction/CardProcResp/CcReturnMsg"));
                    if (n2 != null)
                    {
                        authResponse = n2.InnerText;
                    }
                }
                TransID = XmlCommon.XmlField(n, "OrderId");
                try
                {
                    AVSResult = "AVSDisplay: " + responseXml.SelectSingleNode("//AvsDisplay").InnerText + ", CVV2Resp: " + responseXml.SelectSingleNode("//Cvv2Resp").InnerText + ", FraudConfidence: " + responseXml.SelectSingleNode("//FraudConfidence").InnerText;
                    AVSResult = AVSResult.Substring(0, 50); // our db is 50 max!
                }
                catch { }
            }
            catch
            {
                throw new ArgumentException("HSBC Unexpected Response: " + rawResponseString);
            }

            AuthorizationCode     = approvalCode;
            AuthorizationResult   = rawResponseString;
            AuthorizationTransID  = TransID;
            TransactionCommandOut = transactionCommand.ToString();
            TransactionResponse   = authResponse;

            if (replyCode.Equals("A", StringComparison.InvariantCultureIgnoreCase) == false &&
                replyCode.Equals("C", StringComparison.InvariantCultureIgnoreCase) == false)
            {
                result = authResponse;
                if (result.Length == 0)
                {
                    result = "Unspecified Error";
                }
            }
            return(result);
        }
예제 #28
0
        private DataSet ProcessServiceTransaction(TRANSACTION_PROCESSING transactionProcessor, Address billingAddress, Address shippingAddress,
                                                  string cardExtraCode, int customerId, decimal orderTotal, int orderNumber, TransactionModeEnum transactionMode, ref string transactionCommand)
        {
            // This is not the real transaction command, we are just building up a list of key value pairs being passed into the web service method and kicking them out as xml.
            transactionCommand = GetProcessCardCommand(billingAddress, shippingAddress, cardExtraCode, customerId.ToString(), orderTotal.ToString("0.00"), "", "", orderNumber.ToString(), transactionMode).ToString();


            if (transactionMode == TransactionModeEnum.auth) //  AUTH_ONLY
            {
                return(transactionProcessor.BANKCARD_AUTHONLY(M_id, M_key, billingAddress.FirstName + ' ' + billingAddress.LastName, billingAddress.Address1, billingAddress.City, billingAddress.State, billingAddress.Zip,
                                                              billingAddress.Country, billingAddress.EMail, billingAddress.CardNumber, billingAddress.CardExpirationMonth.PadLeft(2, '0') + billingAddress.CardExpirationYear.ToString().Substring(2, 2),
                                                              cardExtraCode, customerId.ToString(), orderTotal.ToString("0.00"), "", "", orderNumber.ToString(), billingAddress.Phone, "", shippingAddress.FirstName + ' ' + shippingAddress.LastName,
                                                              shippingAddress.Address1, shippingAddress.City, shippingAddress.State, shippingAddress.Zip, shippingAddress.Country));
            }
            else //  AUTH_CAPTURE
            {
                return(transactionProcessor.BANKCARD_SALE(M_id, M_key, billingAddress.FirstName + ' ' + billingAddress.LastName, billingAddress.Address1, billingAddress.City, billingAddress.State, billingAddress.Zip,
                                                          billingAddress.Country, billingAddress.EMail, billingAddress.CardNumber, billingAddress.CardExpirationMonth.PadLeft(2, '0') + billingAddress.CardExpirationYear.ToString().Substring(2, 2),
                                                          cardExtraCode, customerId.ToString(), orderTotal.ToString("0.00"), "", "", orderNumber.ToString(), billingAddress.Phone, "", shippingAddress.FirstName + ' ' + shippingAddress.LastName,
                                                          shippingAddress.Address1, shippingAddress.City, shippingAddress.State, shippingAddress.Zip, shippingAddress.Country));
            }
        }
예제 #29
0
        // ProcessCard() is used for Credit Card processing via Website Payments Pro,
        // just like other credit card gateways.
        // ProcessPaypal() is used for Express Checkout and PayPal payments.
        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;
            try
            {
                // the request details object contains all payment details
                DoDirectPaymentRequestDetailsType RequestDetails = new DoDirectPaymentRequestDetailsType();

                // define the payment action to 'Sale'
                // (another option is 'Authorization', which would be followed later with a DoCapture API call)
                RequestDetails.PaymentAction = (PaymentActionCodeType)CommonLogic.IIF(AppLogic.TransactionModeIsAuthOnly(), (int)PaymentActionCodeType.Authorization, (int)PaymentActionCodeType.Sale);

                // define the total amount and currency for the transaction
                PaymentDetailsType PaymentDetails = new PaymentDetailsType();

                BasicAmountType totalAmount = new BasicAmountType();
                totalAmount.Value               = Localization.CurrencyStringForGatewayWithoutExchangeRate(OrderTotal);
                totalAmount.currencyID          = (CurrencyCodeType)Enum.Parse(typeof(CurrencyCodeType), AppLogic.AppConfig("Localization.StoreCurrency"), true);
                PaymentDetails.OrderTotal       = totalAmount;
                PaymentDetails.InvoiceID        = OrderNumber.ToString();
                PaymentDetails.ButtonSource     = PayPal.BN + "_DP_US";
                PaymentDetails.OrderDescription = AppLogic.AppConfig("StoreName");

                // define the credit card to be used

                CreditCardDetailsType creditCard = new CreditCardDetailsType();
                creditCard.CreditCardNumber  = UseBillingAddress.CardNumber;
                creditCard.ExpMonth          = Localization.ParseUSInt(UseBillingAddress.CardExpirationMonth);
                creditCard.ExpYear           = Localization.ParseUSInt(UseBillingAddress.CardExpirationYear);
                creditCard.ExpMonthSpecified = true;
                creditCard.ExpYearSpecified  = true;
                creditCard.CVV2 = CardExtraCode;

                if (UseBillingAddress.CardType == "AmericanExpress")
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), "Amex", true);
                }
                else
                {
                    creditCard.CreditCardType = (CreditCardTypeType)Enum.Parse(typeof(CreditCardTypeType), UseBillingAddress.CardType, true);
                }
                creditCard.CreditCardTypeSpecified = true;

                PayerInfoType  cardHolder      = new PayerInfoType();
                PersonNameType oPersonNameType = new PersonNameType();
                oPersonNameType.FirstName  = UseBillingAddress.FirstName;
                oPersonNameType.LastName   = UseBillingAddress.LastName;
                oPersonNameType.MiddleName = String.Empty;
                oPersonNameType.Salutation = String.Empty;
                oPersonNameType.Suffix     = String.Empty;
                cardHolder.PayerName       = oPersonNameType;

                AddressType PayerAddress = new AddressType();
                PayerAddress.Street1          = UseBillingAddress.Address1;
                PayerAddress.CityName         = UseBillingAddress.City;
                PayerAddress.StateOrProvince  = UseBillingAddress.State;
                PayerAddress.PostalCode       = UseBillingAddress.Zip;
                PayerAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseBillingAddress.Country), true);
                PayerAddress.CountrySpecified = true;

                if (UseShippingAddress != null)
                {
                    AddressType shippingAddress = new AddressType();
                    shippingAddress.Name             = (UseShippingAddress.FirstName + " " + UseShippingAddress.LastName).Trim();
                    shippingAddress.Street1          = UseShippingAddress.Address1;
                    shippingAddress.Street2          = UseShippingAddress.Address2 + CommonLogic.IIF(UseShippingAddress.Suite != "", " Ste " + UseShippingAddress.Suite, "");
                    shippingAddress.CityName         = UseShippingAddress.City;
                    shippingAddress.StateOrProvince  = UseShippingAddress.State;
                    shippingAddress.PostalCode       = UseShippingAddress.Zip;
                    shippingAddress.Country          = (CountryCodeType)Enum.Parse(typeof(CountryCodeType), AppLogic.GetCountryTwoLetterISOCode(UseShippingAddress.Country), true);
                    shippingAddress.CountrySpecified = true;
                    PaymentDetails.ShipToAddress     = shippingAddress;
                }

                cardHolder.Address   = PayerAddress;
                creditCard.CardOwner = cardHolder;

                RequestDetails.CreditCard     = creditCard;
                RequestDetails.PaymentDetails = PaymentDetails;
                RequestDetails.IPAddress      = CommonLogic.CustomerIpAddress();            // cart.ThisCustomer.LastIPAddress;

                if (RequestDetails.IPAddress == "::1")
                {
                    RequestDetails.IPAddress = "127.0.0.1";
                }

                // instantiate the actual request object
                PaymentRequest         = new DoDirectPaymentRequestType();
                PaymentRequest.Version = API_VER;
                PaymentRequest.DoDirectPaymentRequestDetails = RequestDetails;
                DDPReq = new DoDirectPaymentReq();
                DDPReq.DoDirectPaymentRequest = PaymentRequest;

                DoDirectPaymentResponseType responseDetails = (DoDirectPaymentResponseType)IPayPal.DoDirectPayment(DDPReq);

                //if (LogToErrorTable)
                //{
                //    PayPalController.Log(XmlCommon.SerializeObject(DDPReq, DDPReq.GetType()), "DoDirectPayment Request");
                //    PayPalController.Log(XmlCommon.SerializeObject(responseDetails, responseDetails.GetType()), "DoDirectPayment Response");
                //}

                if (responseDetails != null && responseDetails.Ack.ToString().StartsWith("success", StringComparison.InvariantCultureIgnoreCase))
                {
                    AuthorizationTransID = CommonLogic.IIF(TransactionMode.ToString().ToLower() == AppLogic.ro_TXModeAuthOnly.ToLower(), "AUTH=", "CAPTURE=") + responseDetails.TransactionID.ToString();
                    AuthorizationCode    = responseDetails.CorrelationID;
                    AVSResult            = responseDetails.AVSCode;
                    result = AppLogic.ro_OK;
                    AuthorizationResult = responseDetails.Ack.ToString() + "|AVSCode=" + responseDetails.AVSCode.ToString() + "|CVV2Code=" + responseDetails.CVV2Code.ToString();
                }
                else
                {
                    if (responseDetails.Errors != null)
                    {
                        String Separator = String.Empty;
                        for (int ix = 0; ix < responseDetails.Errors.Length; ix++)
                        {
                            AuthorizationResult += Separator;
                            AuthorizationResult += responseDetails.Errors[ix].LongMessage;                            // record failed TX
                            TransactionResponse += Separator;
                            try
                            {
                                TransactionResponse += String.Format("|{0},{1},{2}|", responseDetails.Errors[ix].ShortMessage, responseDetails.Errors[ix].ErrorCode, responseDetails.Errors[ix].LongMessage);                                 // record failed TX
                            }
                            catch { }
                            Separator = ", ";
                        }
                    }
                    result = AuthorizationResult;
                    // just store something here, as there is no other way to get data out of this gateway about the failure for logging in failed transaction table
                }
            }
            catch
            {
                result = "Transaction Failed";
            }
            return(result);
        }
예제 #30
0
        private XDocument GetProcessCardCommand(Address billingAddress, Address shippingAddress, string cardExtraCode, string customerId, string orderTotal, string orderShipping, string orderTax, string orderNumber, TransactionModeEnum transactionMode)
        {
            string cardNumber = AppLogic.SafeDisplayCardNumber(billingAddress.CardNumber, "", 0);

            return(new XDocument(
                       new XElement("Transaction", new XAttribute("TransactionMode", transactionMode.ToString())
                                    , new XElement("M_ID", M_id)
                                    , new XElement("M_KEY", M_key)
                                    , new XElement("C_NAME", billingAddress.FirstName + ' ' + billingAddress.LastName)
                                    , new XElement("C_ADDRESS", billingAddress.Address1)
                                    , new XElement("C_CITY", billingAddress.City)
                                    , new XElement("C_STATE", billingAddress.State)
                                    , new XElement("C_ZIP", billingAddress.Zip)
                                    , new XElement("C_COUNTRY", billingAddress.Country)
                                    , new XElement("C_EMAIL", billingAddress.EMail)
                                    , new XElement("C_CARDNUMBER", cardNumber)
                                    , new XElement("C_EXP", billingAddress.CardExpirationMonth.PadLeft(2, '0') + billingAddress.CardExpirationYear.ToString().Substring(2, 2))
                                    , new XElement("C_CVV", cardExtraCode)
                                    , new XElement("T_CUSTOMER_NUMBER", customerId)
                                    , new XElement("T_AMT", orderTotal)
                                    , new XElement("T_SHIPPING", orderShipping)
                                    , new XElement("T_TAX", orderTax)
                                    , new XElement("T_ORDERNUM", orderNumber)
                                    , new XElement("C_TELEPHONE", billingAddress.Phone)
                                    , new XElement("C_FAX", "")
                                    , new XElement("C_SHIP_NAME", shippingAddress.FirstName + ' ' + shippingAddress.LastName)
                                    , new XElement("C_SHIP_ADDRESS", shippingAddress.Address1)
                                    , new XElement("C_SHIP_CITY", shippingAddress.City)
                                    , new XElement("C_SHIP_STATE", shippingAddress.State)
                                    , new XElement("C_SHIP_ZIP", shippingAddress.Zip)
                                    , new XElement("C_SHIP_COUNTRY", shippingAddress.Country)
                                    )));
        }