コード例 #1
0
        public async Task <PaymentGatewayResponse> ProcessPayment(string creditCardNumber, string cardHolder, decimal amount)
        {
            var result = new PaymentGatewayResponse();

            result.StatusCode    = 200;
            result.PaymentStatus = "Processed";
            result.Message       = "Payment has been processed successfully";
            //using (var httpClient = new HttpClient())
            //{
            //    httpClient.Timeout = System.Threading.Timeout.InfiniteTimeSpan;
            //    try
            //    {
            //        var data = new JsonContent(new { creditCardNumber, cardHolder, amount });
            //        using (HttpResponseMessage res = await httpClient.PostAsync("https://somedummyurl", data))
            //        {
            //            using (HttpContent content = res.Content)
            //            {
            //                var response = await content.ReadAsStringAsync();
            //                res.EnsureSuccessStatusCode();
            //                //this section depends on the response structure from the service
            //                result.StatusCode = 200;
            //                result.PaymentStatus = "";
            //                result.Message = "";
            //            }
            //        }
            //    }
            //    catch (Exception ex)
            //    {
            //        result.StatusCode = 500;
            //        result.PaymentStatus = "Failed";
            //        result.Message = ex.ToString();
            //    }
            //}
            return(result);
        }
コード例 #2
0
        public IActionResult Index(string msg, int orderid)
        {
            if (msg.Equals("success") && orderid != 0)
            {
                ViewBag.message         = "Your Order is confirm. We will reach you in Sometime";
                ViewBag.orderId         = "Your Order id is pdos" + orderid;
                ViewBag.DeliveryMessage = "Your order Will be dilivered in 5-7 working days. Thank You For Shopping.";

                if (HttpContext.Session.GetComplexData <List <int> >("cart") != null)
                {
                    HttpContext.Session.Remove("cart");
                    HttpContext.Session.Remove("count");
                }
            }
            else
            if (msg.Equals("fail"))
            {
                ViewBag.failmessage = "Your Order is not confirm";
            }
            else
            if (msg.Equals("payfail") && orderid != 0)
            {
                PaymentGatewayResponse paymentGatewayResponse = paymentGateway.GetResponseByOrderId(orderid);

                ViewBag.failmessage = "Your Order is not confirm";

                ViewData["heading"] = "Signature Verification Failed";
                return(View("FailPayment", paymentGatewayResponse));
            }
            return(View());
        }
コード例 #3
0
        public void Test_DirectResponse()
        {
            // customer profile returns this as string
            var directResponse = @"2,2,27,The transaction has been declined because of an AVS mismatch. The address provided does not match billing address of cardholder.,AE5V2W,N,40059863807,none,Test transaction for ValidateCustomerPaymentProfile.,0.00,CC,auth_only,customer-48,Verdie,Farrell,Schimmel, McGlynn and Kling,214 Lucinda Streets,West Barrett,Kansas,46201,TC,,,[email protected],,,,,,,,,0.00,0.00,0.00,FALSE,none,,P,2,,,,,,,,,,,XXXX0015,MasterCard,,,,,,,0S8C3LQM3HC6DEDAFV94OTO,,,,,,,,,,";

            var parsed = new PaymentGatewayResponse(directResponse);

            Assert.Equal(ResponseCodeEnum.Declined, parsed.ResponseCode);
        }
コード例 #4
0
        /// <summary>
        /// endpoint: /API/Laser.Orchard.PaymentGateway/PaymentGatewayAPI/GetPosNames
        /// A call to this endpoint, with no parameters, returns the list of the names of available payment methods.
        /// Example response:
        /// {
        ///  "ErrorCode": 0,
        ///  "ResolutionAction": 0,
        ///  "Success": true,
        ///  "Message": "",
        ///  "Data": {
        ///    "posNames": [
        ///      "Braintree and PayPal",
        ///      "CartaSì X-Pay",
        ///      "GestPay"
        ///    ]
        ///  }
        /// }
        /// </summary>
        /// <returns>A response whose Data field contains an array called posNames that contains the names to be used when referring
        /// to the payment methods in the other API calls.</returns>
        public PaymentGatewayResponse GetPosNames()
        {
            PaymentGatewayResponse res = new PaymentGatewayResponse()
            {
                Success   = true,
                ErrorCode = PaymentGatewayErrorCode.NoError,
                Data      = new { posNames = AllPosNames() },
                Message   = ""
            };

            return(res);
        }
コード例 #5
0
        public IActionResult HandleResponse(IFormCollection form)
        {
            string secretKey   = configuration["PaymentGatewaysecretKey"];
            int    orderId     = Convert.ToInt32(Request.Form["orderId"]);
            string orderAmount = Request.Form["orderAmount"];
            string referenceId = Request.Form["referenceId"];
            string txStatus    = Request.Form["txStatus"];
            string paymentMode = Request.Form["paymentMode"];
            string txMsg       = Request.Form["txMsg"];
            string txTime      = Request.Form["txTime"];
            string signature   = Request.Form["signature"];

            PaymentGatewayResponse paymentGatewayResponse = new PaymentGatewayResponse()
            {
                Order       = orderRepository.GetOrderDetailsById(orderId),
                paymentMode = paymentMode,
                orderAmount = orderAmount,
                referenceId = referenceId,
                txMsg       = txMsg,
                txStatus    = txStatus,
                txTime      = txTime
            };

            paymentGateway.AddPaymentGatewayResponse(paymentGatewayResponse);


            string signatureData = orderId + orderAmount + referenceId + txStatus + paymentMode + txMsg + txTime;

            var hmacsha256 = new HMACSHA256(StringEncode(secretKey));

            byte[] gensignature      = hmacsha256.ComputeHash(StringEncode(signatureData));
            string computedsignature = Convert.ToBase64String(gensignature);

            if (signature == computedsignature && txStatus.Equals("SUCCESS"))
            {
                ViewData["panel"]   = "panel panel-success";
                ViewData["heading"] = "Signature Verification Successful";
                orderRepository.UpdatePaymentSatus(orderId, "DoneOnlinepayment");
            }
            else
            {
                ViewData["panel"]   = "panel panel-danger";
                ViewData["heading"] = "Signature Verification Failed";

                orderRepository.UpdatePaymentSatus(orderId, "FailOnlinePayment");
                return(RedirectToAction("Index", "OrderConformation", new { msg = "payfail", orderid = orderId }));
            }

            return(View(paymentGatewayResponse));
        }
コード例 #6
0
        public async Task <PaymentServiceResponse> MakePayment(PaymentViewModel payment)
        {
            var gatewayResult = new PaymentGatewayResponse();

            if (payment.Amount <= 20)
            {
                gatewayResult = await _cheapPaymentGateway.ProcessPayment(payment.CreditCardNumber, payment.CardHolder, payment.Amount);
            }
            else if (payment.Amount <= 500)
            {
                gatewayResult = await _expensivePaymentGateway.ProcessPayment(payment.CreditCardNumber, payment.CardHolder, payment.Amount);

                if (gatewayResult.StatusCode != 200)
                {
                    gatewayResult = await _cheapPaymentGateway.ProcessPayment(payment.CreditCardNumber, payment.CardHolder, payment.Amount);
                }
            }
            else if (payment.Amount > 500)
            {
                int numberOfRetries = 3;
                int i = 0;
                while (i < numberOfRetries)
                {
                    gatewayResult = await _premiumPaymentGateway.ProcessPayment(payment.CreditCardNumber, payment.CardHolder, payment.Amount);

                    if (gatewayResult.StatusCode == 200)
                    {
                        break;
                    }
                    i++;
                }
            }
            if (gatewayResult.StatusCode == 200)
            {
                SavePayment(payment, gatewayResult.PaymentStatus);
            }
            var result = new PaymentServiceResponse {
                StatusCode = gatewayResult.StatusCode, Message = gatewayResult.Message
            };

            return(result);
        }
コード例 #7
0
ファイル: PaymentGateways.cs プロジェクト: yayiekim/store
        public PaymentGatewayResponse CheckOutTwoCheckOut(ChargeAuthorizeServiceOptions charge)
        {
            TwoCheckoutConfig.SellerID   = ConfigurationManager.AppSettings["TwoCheckOutSellerId"];
            TwoCheckoutConfig.PrivateKey = ConfigurationManager.AppSettings["TwoCheckOutPrivateKey"];;
            TwoCheckoutConfig.Sandbox    = true;


            var _res = new PaymentGatewayResponse();


            try
            {
                var Charge = new ChargeService();
                var result = Charge.Authorize(charge);

                _res.amount         = result.total;
                _res.refNo          = result.transactionId.ToString();
                _res.responseStatus = result.responseCode;
                _res.message        = result.responseMsg;

                if (charge.total == result.total)
                {
                    _res.PaymentStatus = "paid";
                }
                else if (charge.total > result.total)
                {
                    _res.PaymentStatus = "partial";
                }

                return(_res);
            }
            catch (Exception ex)
            {
                _res.responseStatus = "failed";
                _res.message        = ex.Message;

                return(_res);
            }
        }
コード例 #8
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[]   separator      = { '|' };
                string[] responseValues = rawResponse.Split(separator, StringSplitOptions.None);

                //should be at least 39 elements
                if (responseValues.Length > 38)
                {
                    responseCode = responseValues[ResponseCodePosition];
                    switch (responseCode)
                    {
                    case "1":
                        response = PaymentGatewayResponse.Approved;
                        break;

                    case "2":
                        response = PaymentGatewayResponse.Declined;
                        break;

                    case "3":
                        response = PaymentGatewayResponse.Error;
                        break;
                    }

                    reasonCode     = responseValues[ResponseReasonCodePosition];
                    responseReason = responseValues[ResponseReasonTextPosition];
                    approvalCode   = responseValues[ResponseAuthCodePosition];
                    avsResultCode  = responseValues[ResponseAvsCodePosition];
                    if (AVSResultTextLookup.Contains(avsResultCode))
                    {
                        avsResultText = (string)AVSResultTextLookup[avsResultCode];
                    }

                    transactionID = responseValues[ResponseTransactionIdPosition];
                }
            }
        }
コード例 #9
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[] separator = { '|' };
                string[] responseValues = rawResponse.Split(separator, StringSplitOptions.None);

                //should be at least 39 elements
                if (responseValues.Length > 38)
                {
                    responseCode = responseValues[ResponseCodePosition];
                    switch (responseCode)
                    {
                        case "1":
                            response = PaymentGatewayResponse.Approved;
                            break;

                        case "2":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        case "3":
                            response = PaymentGatewayResponse.Error;
                            break;

                    }

                    reasonCode = responseValues[ResponseReasonCodePosition];
                    responseReason = responseValues[ResponseReasonTextPosition];
                    approvalCode = responseValues[ResponseAuthCodePosition];
                    avsResultCode = responseValues[ResponseAvsCodePosition];
                    if (AVSResultTextLookup.Contains(avsResultCode))
                    {
                        avsResultText = (string)AVSResultTextLookup[avsResultCode];
                    }

                    transactionID = responseValues[ResponseTransactionIdPosition];
                }
            }
        }
コード例 #10
0
        /// <summary>
        /// DoExpressCheckoutPayment Request
        /// Request to obtain payment with PayPal Express Checkout.
        /// IMPORTANT: PayPal requires that a merchant using Express Checkout display to the
        /// customer the same amount that the merchant sends to PayPal in the AMT
        /// parameter with the DoExpressCheckoutPayment request API.
        /// </summary>
        /// <returns></returns>
        public bool CallDoExpressCheckoutPayment()
        {
            bool result = false;

            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("USER="******"&PWD=" + HttpUtility.UrlEncode(merchantAPIPassword));
            requestBody.Append("&SIGNATURE=" + HttpUtility.UrlEncode(merchantAPITransactionKey));
            //requestBody.Append("&VERSION=3.2");
            requestBody.Append("&VERSION=" + HttpUtility.UrlEncode(apiVersion));
            requestBody.Append("&METHOD=DoExpressCheckoutPayment");

            //TOKEN
            if (payPalToken.Length == 0) throw new ArgumentException("PayPalToken must be provided");

            requestBody.Append("&TOKEN=" + HttpUtility.UrlEncode(payPalToken));

            //PAYMENTACTION
            requestBody.Append("&PAYMENTACTION=Sale");
            //PAYERID
            if (payPalPayerId.Length == 0) throw new ArgumentException("PayPalPayerId must be provided");

            requestBody.Append("&PAYERID=" + HttpUtility.UrlEncode(payPalPayerId));

            //Total of order, including shipping, handling, and tax.
            //AMT
            requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));

            // ## END REQUIRED

            // DESC order description
            // Description of items the customer is purchasing
            if (orderDescription.Length > 0)
            {
                requestBody.Append("&DESC=" + HttpUtility.UrlEncode(orderDescription));
            }

            //CUSTOM A free-form field for your own use, such as a tracking number or other
            //value you want PayPal to return on GetExpressCheckoutDetails
            //response and DoExpressCheckoutPayment response. max length 256
            if (merchantCartId.Length > 0)
            {
                requestBody.Append("&CUSTOM=" + HttpUtility.UrlEncode(merchantCartId));
            }

            //INVNUM
            //Your own unique invoice or tracking number. PayPal returns this value to
            //you on DoExpressCheckoutPayment response.
            //If the transaction does not include a one-time purchase, this field is
            //ignored.
            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&INVNUM=" + HttpUtility.UrlEncode(merchantInvoiceNumber));
            }

            //BUTTONSOURCE -
            //An identification code for use by third-party applications to identify
            // transactions.
            //
            requestBody.Append("&BUTTONSOURCE=SourceTreeSolutions_SP");

            //NOTIFYURL
            //Your URL for receiving Instant Payment Notification (IPN) about this
            //transaction.
            //NOTE: If you do not specify this value in the request, the notification URL
            //from your Merchant Profile is used, if one exists.
            if (notificationUrl.Length > 0)
            {
                requestBody.Append("&NOTIFYURL=" + HttpUtility.UrlEncode(notificationUrl));
            }

            //ITEMAMT Sum of cost of all items in this order.
            //SHIPPINGAMT Total shipping costs for this order.

            //HANDLINGAMT Total handling costs for this order.

            //TAXAMT Sum of tax for all items in this order.

            // CURRENCYCODE default is USD
            if (currencyCode.Length > 0)
            {
                requestBody.Append("&CURRENCYCODE=" + HttpUtility.UrlEncode(currencyCode));
            }

            // L_NAMEn Item name. max length 127
            //L_NUMBERn Item number.
            //L_QTYn Item quantity.
            //L_TAXAMTn Item sales tax.
            //L_AMTn Cost of item
            //L_EBAYITEMNUMBERn Auction item number
            //L_EBAYITEMAUCTIONTXNIDn
            //L_EBAYITEMORDERIDn

            //SHIPTOSTREET
            if (shipToAddress.Length > 0)
            {
                requestBody.Append("&SHIPTOSTREET=" + HttpUtility.UrlEncode(shipToAddress));

                //SHIPTONAME
                if (shipToLastName.Length > 0)
                {
                    requestBody.Append("&SHIPTONAME=" + HttpUtility.UrlEncode(shipToFirstName + " " + shipToLastName));
                }

                //SHIPTOSTREET2

                //SHIPTOCITY
                if (shipToCity.Length > 0)
                {
                    requestBody.Append("&SHIPTOCITY=" + HttpUtility.UrlEncode(shipToCity));
                }

                //SHIPTOSTATE
                if (shipToState.Length > 0)
                {
                    requestBody.Append("&SHIPTOSTATE=" + HttpUtility.UrlEncode(shipToState));
                }

                //SHIPTOCOUNTRYCODE
                if (shipToCountry.Length > 0)
                {
                    requestBody.Append("&SHIPTOCOUNTRYCODE=" + HttpUtility.UrlEncode(shipToCountry));
                }

                //SHIPTOZIP
                if (shipToPostalCode.Length > 0)
                {
                    requestBody.Append("&SHIPTOZIP=" + HttpUtility.UrlEncode(shipToPostalCode));
                }

                //SHIPTOPHONENUM
                if (shipToPhone.Length > 0)
                {
                    requestBody.Append("&SHIPTOPHONENUM=" + HttpUtility.UrlEncode(shipToPhone));
                }

            }

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";

            webRequest.Timeout = timeoutInMilliseconds;

            webRequest.ContentType = "application/x-www-form-urlencoded";

            string encodedBody = requestBody.ToString();
            log.Debug(encodedBody);

            webRequest.ContentLength = encodedBody.Length;

            requestStream = new StreamWriter(webRequest.GetRequestStream());

            if (requestStream != null)
            {

                requestStream.Write(encodedBody);

            }

            if (requestStream != null)
                requestStream.Close();

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseDoExpressCheckoutPaymentResponse();

            }
            else
            {
                response = PaymentGatewayResponse.Error;
                return false;
            }

            return result;
        }
コード例 #11
0
        private void ParseDoExpressCheckoutPaymentResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[] pairSeparator = { '&' };
                char[] keyValSeparator = { '=' };
                string[] keyValPairs = rawResponse.Split(pairSeparator, StringSplitOptions.None);

                StringDictionary responseResults = new StringDictionary();

                foreach (string keyVal in keyValPairs)
                {
                    string[] pair = keyVal.Split(keyValSeparator, StringSplitOptions.None);
                    if (pair.Length >= 2)
                    {
                        responseResults.Add(pair[0], pair[1]);
                    }
                }

                if (responseResults.ContainsKey("ACK"))
                {
                    switch (responseResults["ACK"])
                    {
                        case "Success":
                        case "SuccessWithWarning":

                            response = PaymentGatewayResponse.Approved;
                            break;

                        case "2":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        case "Warning":
                        case "Failure":
                        case "FailureWithWarning":
                        case "Error":

                            response = PaymentGatewayResponse.Error;

                            if (responseResults.ContainsKey("L_LONGMESSAGE0"))
                            {
                                responseReason = HttpUtility.UrlDecode(responseResults["L_LONGMESSAGE0"]);
                            }

                            if (responseResults.ContainsKey("L_ERRORCODE0"))
                            {
                                reasonCode = HttpUtility.UrlDecode(responseResults["L_ERRORCODE0"]);

                            }

                            break;
                    }

                }

                //TOKEN The timestamped token value that was returned by SetExpressCheckout response and
                // passed on GetExpressCheckoutDetails request.
                if (responseResults.ContainsKey("TOKEN"))
                {
                    payPalToken = HttpUtility.UrlDecode(responseResults["TOKEN"]);

                }

                //TRANSACTIONID Unique transaction ID of the payment
                if (responseResults.ContainsKey("TRANSACTIONID"))
                {
                    transactionID = HttpUtility.UrlDecode(responseResults["TRANSACTIONID"]);

                }

                //TRANSACTIONTYPE The type of transaction
                //The type of transaction
                //Character length and limitations:15 single-byte characters
                //Possible values:
                // cart
                // express-checkout
                if (responseResults.ContainsKey("TRANSACTIONTYPE"))
                {
                    payPalTransactionType = HttpUtility.UrlDecode(responseResults["TRANSACTIONTYPE"]);

                }

                //PAYMENTTYPE Indicates whether the payment is instant or delayed
                // none echeck instant
                if (responseResults.ContainsKey("PAYMENTTYPE"))
                {
                    payPalPaymentType = HttpUtility.UrlDecode(responseResults["PAYMENTTYPE"]);

                }

                //ORDERTIME Time/date stamp of payment
                if (responseResults.ContainsKey("ORDERTIME"))
                {
                    DateTime orderTime;
                    if(DateTime.TryParse(HttpUtility.UrlDecode(responseResults["ORDERTIME"]), out orderTime))
                    {
                        payPalOrderTimeStamp = orderTime;
                    }

                }

                //CURRENCYCODE A three-character currency code for one of the currencies
                if (responseResults.ContainsKey("CURRENCYCODE"))
                {
                    currencyCode = HttpUtility.UrlDecode(responseResults["CURRENCYCODE"]);

                }

                CultureInfo currencyCulture = ResourceHelper.GetCurrencyCulture(currencyCode);

                //AMT The final amount charged, including any shipping and taxes from your Merchant Profile
                if (responseResults.ContainsKey("AMT"))
                {
                    this.chargeTotal = decimal.Parse(HttpUtility.UrlDecode(responseResults["AMT"]), currencyCulture);

                }

                //FEEAMT PayPal fee amount charged for the transaction
                if (responseResults.ContainsKey("FEEAMT"))
                {
                    this.payPalFeeAmount = decimal.Parse(HttpUtility.UrlDecode(responseResults["FEEAMT"]), currencyCulture);

                }

                //SETTLEAMT Amount deposited in your PayPal account after a currency conversion
                if (responseResults.ContainsKey("SETTLEAMT"))
                {
                    this.payPalSettlementAmount = decimal.Parse(HttpUtility.UrlDecode(responseResults["SETTLEAMT"]), currencyCulture);

                }

                //TAXAMT Tax charged on the transaction
                if (responseResults.ContainsKey("TAXAMT"))
                {
                    this.payPalTaxTotal = decimal.Parse(HttpUtility.UrlDecode(responseResults["TAXAMT"]), currencyCulture);

                }

                //EXCHANGERATE Exchange rate if a currency conversion occurred
                if (responseResults.ContainsKey("EXCHANGERATE"))
                {
                    payPalExchangeRate = HttpUtility.UrlDecode(responseResults["EXCHANGERATE"]);

                }

                //PAYMENTSTATUS Status of the payment
                // Completed, Pending
                if (responseResults.ContainsKey("PAYMENTSTATUS"))
                {
                    payPalPaymentStatus = HttpUtility.UrlDecode(responseResults["PAYMENTSTATUS"]);

                    if (payPalPaymentStatus == "Completed")
                        response = PaymentGatewayResponse.Approved;

                    if (payPalPaymentStatus == "Pending")
                        response = PaymentGatewayResponse.Pending;

                }

                //PENDINGREASON The reason the payment is pending
                if (responseResults.ContainsKey("PENDINGREASON"))
                {
                    payPalPendingReason = HttpUtility.UrlDecode(responseResults["PENDINGREASON"]);

                }

                //none: No pending reason

                //address: The payment is pending because your customer did not include a confirmed
                //shipping address and your Payment Receiving Preferences is set such that you want to
                //manually accept or deny each of these payments. To change your preference, go to the
                //Preferences section of your Profile.

                //echeck: The payment is pending because it was made by an eCheck that has not yet
                //cleared.

                //intl: The payment is pending because you hold a non-U.S. account and do not have a
                //withdrawal mechanism. You must manually accept or deny this payment from your
                //Account Overview.

                //REASONCODE The reason for a reversal if TransactionType is reversal
                if (responseResults.ContainsKey("REASONCODE"))
                {
                    reasonCode = HttpUtility.UrlDecode(responseResults["REASONCODE"]);

                }
                // none: No reason code
                //chargeback: A reversal has occurred on this transaction due to a chargeback by your customer.
                //guarantee: A reversal has occurred on this transaction due to your customer
                //triggering a money-back guarantee
                //buyer-complaint: A reversal has occurred on this transaction due to a complaint
                //about the transaction from your customer.
                //refund: A reversal has occurred on this transaction because you have given the
                //customer a refund.
                //other: A reversal has occurred on this transaction due to a reason not listed above

                //REDIRECTREQUIRED Flag to indicate whether you need to redirect the customer to back to PayPal after
                //completing the transaction.
                //NOTE: Use this field only if you are using giropay or bank transfer payment methods in
                //Germany.

            }
        }
コード例 #12
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                //PARSE THE RESPONSE FROM PNP
                dictionaryResponseDecode(rawResponse);


                if (_ResponseDictionary.ContainsKey("FinalStatus"))
                {
                    if (_ResponseDictionary["FinalStatus"].ToString() == "success")
                    {
                        response = PaymentGatewayResponse.Approved;
                    }
                    else
                    {
                        response = PaymentGatewayResponse.Declined;
                    }
                }
                else
                {
                    response = PaymentGatewayResponse.Error;
                }

                try
                {
                    reasonCode = _ResponseDictionary["FinalStatus"].ToString();
                }
                catch { }

                try
                {
                    responseReason = _ResponseDictionary["MerrMsg"].ToString();
                }
                catch { }

                try
                {
                    approvalCode = _ResponseDictionary["auth-code"].ToString();
                }
                catch { }
                try
                {
                    avsResultCode = _ResponseDictionary["avs-code"].ToString();
                }
                catch { }

                if (AVSResultTextLookup.Contains(avsResultCode))
                {
                    avsResultText = (string)AVSResultTextLookup[avsResultCode];
                }

                try
                {
                    cardSecurityCodeResponseCode = _ResponseDictionary["cvvresp"].ToString();
                }
                catch { }

                transactionID = _ResponseDictionary["orderID"].ToString(); // not to be confused with order-id which we sent to the gateway
            }
        }
コード例 #13
0
        protected void OnPay(object sender, EventArgs e)
        {
            if (!Page.IsValid) return;

             var service = GetCardService();
             CardProfile = SetCreditCardViewModel(service);

             var cardExpiresOnDate =
            new DateTime(MemberProtect.Utility.ValidateInteger(CardProfile.ExpirationYear),
                         MemberProtect.Utility.ValidateInteger(CardProfile.ExpirationMonth), 1)
               .AddMonths(1).AddDays(-1);

             if (cardExpiresOnDate.CompareTo(DateTime.Today) <= 0)
             {
            SetMessage(
               _transientCardEntry
                  ? "Please choose a valid credit card expiration date in the future."
                  : "This card is expired please choose or add another card.",
               MessageTone.Negative);
            return;
             }

             var sErrors = string.Empty;

             if (_transientCardEntry)
             {
            if (CardProfile.CardType == "American Express")
            {
               var oRegex = new Regex("^\\d{15}$");
               if (!oRegex.Match(CardProfile.CreditCardNumber).Success)
               {
                  sErrors += "Credit Card Number must be a valid American Express number (123123412341234).<br/>";
               }

               if (CardProfile.CardVerificationCode.Length != 4)
               {
                  sErrors += "Please enter your 4 digit security code.<br/>";
               }
            }
            else
            {
               var oRegex = new Regex("^\\d{16}$");
               if (!oRegex.Match(CardProfile.CreditCardNumber).Success)
               {
                  sErrors += "Credit Card Number must be a valid credit card number (1234123412341234).<br/>";
               }

               if (CardProfile.CardVerificationCode.Length != 3)
               {
                  sErrors += "Please enter your 3 digit security code.<br/>";
               }
            }

            if (!m_chkAgree.Checked)
            {
               sErrors += "You must accept the Terms & Conditions.";
            }

            if (sErrors != string.Empty)
            {
               SetMessage(sErrors, MessageTone.Negative);
               return;
            }
             }

             var oExpirationDateTime =
            new DateTime(MemberProtect.Utility.ValidateInteger(m_cboCreditCardExpireYear.SelectedValue),
                         MemberProtect.Utility.ValidateInteger(m_cboCreditCardExpireMonth.SelectedValue), 1).AddMonths(1).AddDays(-1);

             var oTransactionInformation = new AuthorizeNETTransactionInformation(CardProfile.CreditCardNumber, GetTotal(), oExpirationDateTime)
             {
            FirstName = CardProfile.FirstName,
            LastName = CardProfile.LastName,
            CreditCardCode = CardProfile.CardVerificationCode,
            Email = CardProfile.ReceiptEmailAddressCsv,
            Description = "Invoice Payment",
            Company = (m_txtCompany.Text.Length > 50) ? m_txtCompany.Text.Substring(0, 49) : m_txtCompany.Text,
            InvoiceNumber = GetListOfInvoiceNumbers()
             };

             if (_transientCardEntry && m_chkSavePaymentInformation.Checked)
             {
            var errors = service.SaveCreditCard(CardProfile);
            if (errors.Any())
            {
               SetMessage(errors.Aggregate((msg, error) => msg + error + "<br />"), MessageTone.Negative);
               return;
            }

            // just flip the bit?  hope the state is all proper
            _transientCardEntry = false;
             }

             var paymentGatewayResponse = new PaymentGatewayResponse(string.Empty);

             if (_transientCardEntry)
             {
            var oAuthorizeNet = new AuthorizeNET(ApplicationContext.SiteProperites.AuthorizeNetIsDebug,
                                                 MemberProtect.Cryptography.Decrypt(ApplicationContext.SiteProperites.AuthorizeNetLoginID),
                                                 MemberProtect.Cryptography.Decrypt(ApplicationContext.SiteProperites.AuthorizeNetTransactionKey));

            if (!oAuthorizeNet.ProcessAuthorizationAndCapture(oTransactionInformation))
            {
               var message = "Your payment could not be processed, please double-check all information and try again.";
               if (ApplicationContext.SiteProperites.AuthorizeNetIsDebug)
               {
                  var response = CreditCards.ParseAuthorizeNetResponse(oAuthorizeNet.Response);
                  message += string.Format(" (Response: {0}, Reason: {1})", response.ResponseCode, response.ResponseReasonCode);
               }

               SetMessage(message, MessageTone.Negative);
               return;
            }

            paymentGatewayResponse = oAuthorizeNet.PaymentGatewayResponse;
             }
             else
             {
            // go through CIM to process transaction
            paymentGatewayResponse = service.CIMAuthorizationAndCapture(oTransactionInformation,
                                                                        CardProfile.CIMProfileId,
                                                                        CardProfile.CIMPaymentProfileId);
            if (paymentGatewayResponse.Errors.Any() || paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode) != "1")
            {
               var message = paymentGatewayResponse.Errors.Any()
                                ? paymentGatewayResponse.Errors.Aggregate((messages, error) => messages + ", " + error)
                                : paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText);
               ShowMessage(message, MessageTone.Negative);
               return;
            }
             }

             var oIAPayment = SavePayment(paymentGatewayResponse);

             StringBuilder oSpeedySpotsLineItems;
             var oLineItems = SaveLineItems(oIAPayment, out oSpeedySpotsLineItems);

             // QB Import Payment Rule
             // - All of the line items within a payment MUST associate with an actual QB Invoice and the amount on the individual line items must match up with the invoice, otherwise
             var bIsPaymentAutoImported = QuickBooksInvoiceMatching(oIAPayment);

             // Clear the invoice in memory
             Session["InvoicePayments"] = null;

             SendPaymentReceiptEmail(CardProfile, oLineItems, oIAPayment);

             SendBillingEmail(CardProfile, bIsPaymentAutoImported, oSpeedySpotsLineItems, oIAPayment);

             // Clear the invoice in memory
             Session["InvoicePayments"] = null;

             // Display the receipt
             m_divPayment.Visible = false;
             m_divReceipt.Visible = true;
        }
コード例 #14
0
    public async Task TestCustomerProfileAsync(CustomerProfile profile, CancellationToken cancellationToken)
    {
        // 1. create customer / payment profile with validation enabled.
        var paymentProfiles = new Collection <CustomerPaymentProfileType>
        {
            new CustomerPaymentProfileType
            {
                CustomerType = profile.CustomerType,
                Payment      = new PaymentType
                {
                    CreditCard = new CreditCardType
                    {
                        CardNumber     = profile.CardNumber,
                        ExpirationDate = profile.ExpirationDate,
                        CardCode       = profile.CardCode
                    }
                },
                BillTo = new CustomerAddressType
                {
                    FirstName = profile.FirstName,
                    LastName  = profile.LastName,
                    Address   = profile.StreetLine,
                    Company   = profile.Company,
                    City      = profile.City,
                    State     = profile.StateOrProvice,
                    Zip       = profile.ZipCode,
                    Country   = profile.Country
                }
            }
        };

        var createRequest = new CreateCustomerProfileRequest
        {
            RefId          = profile.ReferenceId,
            ValidationMode = _options.ValidationMode,
            Profile        = new CustomerProfileType
            {
                Description        = profile.Description,
                Email              = profile.Email,
                MerchantCustomerId = profile.CustomerId,
                ProfileType        = profile.CustomerProfileType,
                PaymentProfiles    = paymentProfiles,
            },
        };

        var createResponse = await _customerProfileClient.CreateAsync(createRequest, cancellationToken);

        // validation list is in the same order as it has been submitted by the client code
        var parsedCreation = new PaymentGatewayResponse(createResponse.ValidationDirectResponseList[0]);

        // creation for the profile was successful
        if (createResponse.Messages.ResultCode == MessageTypeEnum.Ok)
        {
            var customerProfileId        = createResponse.CustomerProfileId;
            var customerPaymentProfileId = createResponse.CustomerPaymentProfileIdList[0];

            _logger.LogInformation(
                "CreateResponse - {customerProfileId} - {paymentProfile} - {asvCode}",
                customerProfileId,
                createResponse.CustomerPaymentProfileIdList[0],
                parsedCreation.AVSResponseText);

            DisplayResponse("CreateResponse", createResponse);

            // 2. create another payment profile
            var secondaryProfile = _sampleData.GetCustomerProfiles()[1];

            var secondaryProfileRequest = new CreateCustomerPaymentProfileRequest
            {
                RefId             = profile.ReferenceId,
                ValidationMode    = _options.ValidationMode,
                CustomerProfileId = customerProfileId,
                PaymentProfile    = new CustomerPaymentProfileType
                {
                    Payment = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardCode       = secondaryProfile.CardCode,
                            CardNumber     = secondaryProfile.CardNumber,
                            ExpirationDate = secondaryProfile.ExpirationDate,
                        }
                    },
                    CustomerType = CustomerTypeEnum.Business,
                    BillTo       = new CustomerAddressType
                    {
                        FirstName = secondaryProfile.FirstName,
                        LastName  = secondaryProfile.LastName,
                        Address   = secondaryProfile.StreetLine,
                        Company   = secondaryProfile.Company,
                        City      = secondaryProfile.City,
                        State     = secondaryProfile.StateOrProvice,
                        Zip       = secondaryProfile.ZipCode,
                        Country   = secondaryProfile.Country
                    }
                }
            };

            var secondaryPaymentResponse = await _customerPaymentProfileClient.CreateAsync(secondaryProfileRequest, cancellationToken);

            var secondaryProfileId = secondaryPaymentResponse.CustomerPaymentProfileId;

            if (secondaryPaymentResponse.Messages.ResultCode == MessageTypeEnum.Ok)
            {
                var validateRequest = new ValidateCustomerPaymentProfileRequest
                {
                    CustomerPaymentProfileId = secondaryProfileId,
                    CustomerProfileId        = customerProfileId,
                    ValidationMode           = _options.ValidationMode,
                    RefId = profile.ReferenceId
                };

                var validateResponse = await _customerPaymentProfileClient.ValidateAsync(validateRequest, cancellationToken);

                var parsedValidation = new PaymentGatewayResponse(validateResponse?.DirectResponse !);

                if (validateResponse?.Messages.ResultCode == MessageTypeEnum.Error)
                {
                    _logger.LogWarning("{cardNumber}-{expDate}-{ccv}-{zip}-{parsed}", profile.CardNumber, profile.ExpirationDate, profile.CardCode, profile.ZipCode, parsedValidation.ResponseReasonText);
                    _logger.LogWarning(validateResponse.DirectResponse);
                }

                DisplayResponse("ValidationResponse", validateResponse !);

                // get customer profile
                var customerRequest = new GetCustomerProfileRequest
                {
                    CustomerProfileId = customerProfileId
                };

                var customerResponse = await _customerProfileClient.GetAsync(customerRequest, cancellationToken);

                DisplayResponse(" GetCustomerProfileResponse", customerResponse);

                var paymentRequest = new GetCustomerPaymentProfileRequest
                {
                    CustomerPaymentProfileId = customerPaymentProfileId,
                    CustomerProfileId        = customerProfileId,
                    UnmaskExpirationDate     = true
                };

                var paymentResponse = await _customerPaymentProfileClient.GetAsync(paymentRequest, cancellationToken);

                DisplayResponse(" GetCustomerPaymentProfileResponse", paymentResponse);
            }
        }

        _logger.LogWarning("CreateResponse - {responseCode}", parsedCreation.ResponseCode);

        // delete
        var deleteResponse = await _customerProfileClient.DeleteAsync(
            new DeleteCustomerProfileRequest
        {
            CustomerProfileId = createResponse.CustomerProfileId,
            RefId             = profile.ReferenceId
        },
            cancellationToken);

        DisplayResponse("DeleteResponse", deleteResponse);
    }
コード例 #15
0
        public async Task Fail_To_Create_Customer_Profile_With_Credit_Card_That_Declined_Test()
        {
            // Arrange
            var client  = _sp.GetRequiredService <ICustomerProfileClient>();
            var options = _sp.GetRequiredService <IOptions <AuthorizeNetOptions> >();

            // customer payment profile
            var customerPaymentProfiles = new Collection <CustomerPaymentProfileType>
            {
                new CustomerPaymentProfileType
                {
                    CustomerType = CustomerTypeEnum.Business,
                    Payment      = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardNumber     = "5424000000000015",
                            ExpirationDate = "2024-02",
                            CardCode       = "904",
                        }
                    },
                    BillTo = new CustomerAddressType
                    {
                        Address = "1234 main st",
                        City    = "Washington",
                        State   = "DC",
                        Zip     = "46282"
                    },
                }
            };

            // create request
            var createRequest = new CreateCustomerProfileRequest
            {
                Profile = new CustomerProfileType
                {
                    Description        = "Declined Test Customer Account",
                    Email              = "*****@*****.**",
                    MerchantCustomerId = "Declined-Id-2",
                    ProfileType        = CustomerProfileTypeEnum.Regular,
                    PaymentProfiles    = customerPaymentProfiles,
                },

                ValidationMode = options.Value.ValidationMode
            };

            var createResponse = await client.CreateAsync(createRequest);

            // E00039 - A duplicate record with ID 1517706063 already exists.
            var code = createResponse.Messages.Message[0].Code;
            var text = createResponse.Messages.Message[0].Text;

            Assert.Equal("E00027", code);
            Assert.Equal("This transaction has been declined.", text);
            Assert.Equal(MessageTypeEnum.Error, createResponse.Messages.ResultCode);

            var createResult = new PaymentGatewayResponse(createResponse.ValidationDirectResponseList[0]);

            // Assert.Equal(ResponseCodeEnum.HeldForReview, createResult.ResponseCode);
            Assert.Equal(ResponseCodeEnum.Declined, createResult.ResponseCode);

            // "N" => "No Match on Address(Street) or ZIP"
            Assert.Equal("Z", createResult.AVSResponseCode);
            Assert.Equal("Five digit ZIP matches, Address (Street) does not", createResult.AVSResponseText);

            // Assert.Equal("A", createResult.AVSResponseCode);
            // Assert.Equal("Address(Street) matches, ZIP does not", createResult.AVSResponseText);

            // good address match
            // Assert.Equal("Y", createResult.AVSResponseCode);
            // Assert.Equal("Address(Street) and five digit ZIP match", createResult.AVSResponseText);
            Assert.Equal("auth_only", createResult.TransactionType);
            Assert.Equal("This transaction has been declined", createResult.ResponseReasonCode);
            Assert.Equal("Visa", createResult.CardType);

            // N - No Match indicates the code entered is incorrect.
            Assert.Equal("N", createResult.CardCodeResponse);
            Assert.Equal("000000", createResult.AuthorizationCode);
            Assert.Equal(string.Empty, createResult.CardholderAuthenticationVerificationResponse);
            Assert.Equal("CC", createResult.Method);
        }
コード例 #16
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string Locale = CultureInfo.CurrentCulture.Name;

            _country = Locale.Substring(3, 2);

            MembershipUser <DistributorProfileModel> member = null;

            var    memberDefault = Membership.GetUser();
            string DistributorID = string.Empty;

            try
            {
                member        = (MembershipUser <DistributorProfileModel>)memberDefault;
                DistributorID = (member != null && member.Value != null) ? member.Value.Id : string.Empty;
            }
            catch (Exception ex)
            {
                LoggerHelper.Error(string.Format("PaymentGatewayManager Null member cast failed : {0} ", ex.Message));
            }

            if (!string.IsNullOrEmpty(DistributorID))
            {
                _sessionInfo = SessionInfo.GetSessionInfo(DistributorID, Locale);
            }

            if (!IsPostBack)
            {
                ProductsBase.RemoveDupCheckCookie();
                (Master as OrderingMaster).SetPageHeader(GetLocalResourceObject("PageResource1.Title") as string);
                PaymentGatewayResponse gatewayResponse = null;
                try
                {
                    gatewayResponse = PaymentGatewayResponse.Create();
                    if (null != gatewayResponse)
                    {
                        LoggerHelper.Warn(string.Format("PaymentGatewayRequest Splunk Log : Request {0}", LogFormData(Request.Form)));
                    }
                }
                catch (Exception ex)
                {
                    LoggerHelper.Error(string.Format("PaymentGatewayManager failed to create a Response: {0}", ex.Message));
                }

                if (gatewayResponse == null)
                {
                    MyHLShoppingCart ShoppingCart = (null != this._sessionInfo && null != this._sessionInfo.ShoppingCart) ? this._sessionInfo.ShoppingCart : ShoppingCartProvider.GetShoppingCart(DistributorID, Locale);
                    if (ShoppingCart != null)
                    {
                        try
                        {
                            PaymentGatewayInvoker invoker = PaymentGatewayInvoker.Create(HLConfigManager.Configurations.PaymentsConfiguration.PaymentGatewayPaymentMethods, (ShoppingCart.Totals as OrderTotals_V01).AmountDue);
                            invoker.Submit();
                        }
                        catch (ThreadAbortException)
                        {
                            //this just seems to come along with the redirect request. We don't want this in the logs
                        }
                        catch (Exception ex)
                        {
                            PaymentGatewayInvoker.LogBlindError(string.Format("Error occurred Invoking Payment Gateway {0}. The error is: {1}", HLConfigManager.Configurations.PaymentsConfiguration.PaymentGatewayInvoker, ex.Message));
                            if (HLConfigManager.Configurations.DOConfiguration.IsChina && _sessionInfo.StandAloneDonationError == standAloneDonation)
                            {
                                _sessionInfo.StandAloneDonationError = standAloneDonationerror;
                                Response.Redirect("~/Ordering/Donation.aspx");
                            }
                            else
                            {
                                Response.Redirect("~/Ordering/Checkout.aspx");
                            }
                        }
                    }
                }
                else
                {
                    if (gatewayResponse is PGHPaymentGatewayResponse && _sessionInfo != null)
                    {
                        Session[PaymentGatewayResponse.PGH_FPX_PaymentStatus] =
                            ((PGHPaymentGatewayResponse)gatewayResponse).PhgPaymentStatus;
                    }

                    if (gatewayResponse.IsReturning)
                    {
                        bool pending   = gatewayResponse.IsPendingTransaction;
                        bool cancelled = gatewayResponse.IsCancelled;
                        PaymentGatewayRecordStatusType gatewayResponseStatus = gatewayResponse.Status;
                        if (gatewayResponse.IsApproved)
                        {
                            if (!gatewayResponse.CanSubmitIfApproved && _sessionInfo != null)
                            {
                                _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmitted;
                                _sessionInfo.OrderNumber = gatewayResponse.OrderNumber;
                                if (_sessionInfo.ShoppingCart != null)
                                {
                                    ShoppingCartProvider.UpdateShoppingCart(_sessionInfo.ShoppingCart,
                                                                            string.Empty,
                                                                            gatewayResponse.OrderNumber, DateTime.Now);
                                }
                                return;
                            }
                        }

                        if (gatewayResponseStatus == PaymentGatewayRecordStatusType.OrderSubmitted && _sessionInfo != null)
                        {
                            _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmitted;
                            _sessionInfo.OrderNumber = gatewayResponse.OrderNumber;
                            ShoppingCartProvider.UpdateShoppingCart(_sessionInfo.ShoppingCart,
                                                                    string.Empty,
                                                                    gatewayResponse.OrderNumber, DateTime.Now);
                            return;
                        }
                        else if (pending && _sessionInfo != null)
                        {
                            _sessionInfo.OrderStatus = SubmitOrderStatus.Unknown;
                            if (_sessionInfo.ShoppingCart != null)
                            {
                                _sessionInfo.ShoppingCart.CloseCart();
                            }
                            Response.Redirect("~/Ordering/Catalog.aspx?ETO=FALSE");
                            return;
                        }
                        else if (cancelled && _sessionInfo != null)
                        {
                            _sessionInfo.OrderStatus = SubmitOrderStatus.Unknown;
                            Response.Redirect("~/Ordering/Checkout.aspx");
                            return;
                        }
                        else if (gatewayResponse.IsApproved)
                        {
                            //Let it fall through the natural flow...
                        }
                        else if (gatewayResponseStatus == PaymentGatewayRecordStatusType.Declined)
                        {
                            Session[PaymentGatewayResponse.PaymentGateWateSessionKey] = gatewayResponse;
                            if (HLConfigManager.Configurations.DOConfiguration.IsChina && _sessionInfo.StandAloneDonationError == standAloneDonation)
                            {
                                _sessionInfo.StandAloneDonationError = standAloneDonationerror;
                                Response.Redirect("~/Ordering/Donation.aspx");
                            }
                            else
                            {
                                if (_sessionInfo != null)
                                {
                                    _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmitFailed;
                                    _sessionInfo.OrderNumber = gatewayResponse.OrderNumber;
                                }
                                Response.Redirect("~/Ordering/Checkout.aspx");
                            }

                            return;
                        }
                        else
                        {
                            if (_sessionInfo != null)
                            {
                                _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmitFailed;
                                return;
                            }
                        }
                    }

                    //For PGH-Submitted orders
                    if (gatewayResponse is PGHPaymentGatewayResponse)
                    {
                        if (gatewayResponse.Status == PaymentGatewayRecordStatusType.OrderSubmitted && _sessionInfo != null)
                        {
                            // Timer1.Enabled = false;
                            _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmitted;
                            _sessionInfo.OrderNumber = gatewayResponse.OrderNumber;
                            return;
                        }
                    }

                    if (member == null || member.Value == null) //Being posted to by a gateway
                    {
                        offLinePost     = true;
                        Timer1.Enabled  = false;
                        _customResponse = gatewayResponse.SpecialResponse;
                        bool approved = gatewayResponse.IsApproved;
                        if (approved)
                        {
                            if (gatewayResponse.CanSubmitIfApproved)
                            {
                                SubmitOrder(gatewayResponse);
                            }

                            return;
                        }
                    }

                    string orderNumber = gatewayResponse.OrderNumber;
                    if (null != _sessionInfo)
                    {
                        if (_sessionInfo.OrderStatus == SubmitOrderStatus.OrderSubmitted && orderNumber != _sessionInfo.OrderNumber)
                        {
                            _sessionInfo.OrderStatus = SubmitOrderStatus.Unknown;
                        }
                        if (_sessionInfo.OrderStatus == SubmitOrderStatus.Unknown)
                        {
                            if (gatewayResponse.IsApproved && gatewayResponse.CanSubmitIfApproved)
                            {
                                _sessionInfo.OrderStatus = SubmitOrderStatus.OrderBeingSubmitted;
                                if (string.IsNullOrEmpty(_sessionInfo.OrderMonthShortString))
                                {
                                    var orderMonth = new OrderMonth(_country);
                                    //orderMonth.ResolveOrderMonth();
                                    _sessionInfo.OrderMonthShortString = orderMonth.OrderMonthShortString;
                                    _sessionInfo.OrderMonthString      = orderMonth.OrderMonthString;
                                }
                                if (null == _sessionInfo.ShoppingCart)
                                {
                                    _sessionInfo.ShoppingCart = ShoppingCartProvider.GetShoppingCart(DistributorID, Locale);
                                }

                                (new AsyncSubmitOrderProvider()).AsyncSubmitOrder(gatewayResponse, _country, _sessionInfo);
                            }
                            else
                            {
                                if (gatewayResponse.Status == PaymentGatewayRecordStatusType.ApprovalPending && HLConfigManager.Configurations.PaymentsConfiguration.CanSubmitPending)
                                {
                                    if (null != gatewayResponse as PGHPaymentGatewayResponse)
                                    {
                                        if ((gatewayResponse as PGHPaymentGatewayResponse).OrderStatus == HL.PGH.Api.OrderStatus.GatewayWillSubmit)
                                        {
                                            _sessionInfo.OrderStatus = SubmitOrderStatus.OrderSubmittedProcessing;
                                            Response.Redirect("~/Ordering/Confirm.aspx?OrderNumber=" + orderNumber);
                                            return;
                                        }
                                    }
                                    _sessionInfo.OrderStatus = SubmitOrderStatus.OrderBeingSubmitted;
                                    if (string.IsNullOrEmpty(_sessionInfo.OrderMonthShortString))
                                    {
                                        var orderMonth = new OrderMonth(_country);
                                        _sessionInfo.OrderMonthShortString = orderMonth.OrderMonthShortString;
                                        _sessionInfo.OrderMonthString      = orderMonth.OrderMonthString;
                                    }
                                    if (null == _sessionInfo.ShoppingCart)
                                    {
                                        _sessionInfo.ShoppingCart = ShoppingCartProvider.GetShoppingCart(DistributorID, Locale);
                                    }
                                    (new AsyncSubmitOrderProvider()).AsyncSubmitOrder(gatewayResponse, _country, _sessionInfo);
                                }
                                else
                                {
                                    Session[PaymentGatewayResponse.PaymentGateWateSessionKey] = gatewayResponse;
                                    if (HLConfigManager.Configurations.DOConfiguration.IsChina && _sessionInfo.StandAloneDonationError == standAloneDonation)
                                    {
                                        _sessionInfo.StandAloneDonationError = standAloneDonationerror;
                                        Response.Redirect("~/Ordering/Donation.aspx");
                                    }
                                    else
                                    {
                                        Response.Redirect("~/Ordering/Checkout.aspx");
                                    }
                                    return;
                                }
                            }
                        }
                    }
                    else
                    {
                        lbSubmitOrderStatus.Text = string.Format((string)GetLocalResourceObject("PaymentGatewayOrderSubmitFailed"), orderNumber);
                        if (gatewayResponse != null && !string.IsNullOrEmpty(orderNumber))
                        {
                            var status = OrderProvider.GetPaymentGatewayRecordStatus(orderNumber);
                            if (status == PaymentGatewayRecordStatusType.Approved || status == PaymentGatewayRecordStatusType.OrderSubmitted)
                            {
                                SettleCustomerOrderPayment(orderNumber);
                                Response.Redirect("~/Ordering/Confirm.aspx?OrderNumber=" + orderNumber);
                            }
                        }
                        lbSubmitOrderStatus.Style.Add(HtmlTextWriterStyle.Color, "Red");
                        Timer1.Enabled = false;
                    }
                }
            }
        }
コード例 #17
0
ファイル: easebuzz.cs プロジェクト: vikzatak/tollpay
        // this function is required to initiate payment
        public string initiatePaymentAPI(string aAmount, String Firstname, String Email, String Phone, String Productinfo, String Surl, String Furl, String Txnid)
        {
            env = ckv.easebuzzenv;
            string[] hashVarsSeq;
            string   hash_string = string.Empty;
            string   saltvalue   = ckv.easebuzzsalt;
            string   amount      = aAmount;
            string   firstname   = Firstname;
            string   email       = Email;
            string   phone       = Phone;
            string   productinfo = Productinfo;
            string   surl        = Surl;
            string   furl        = Furl;
            string   udf1        = "";
            string   udf2        = "";
            string   udf3        = "";
            string   udf4        = "";
            string   udf5        = "";

            // Generate transaction ID -> make sure this is unique for all transactions
            Random rnd     = new Random();
            string strHash = Easebuzz_Generatehash512(rnd.ToString() + DateTime.Now);

            //txnid = strHash.ToString().Substring(0, 20);
            txnid = Txnid;

            string paymentUrl = getURL();

            // Get configs from web config
            easebuzz_action_url = paymentUrl; // + "/pay/secure";

            // generate hash table
            System.Collections.Hashtable data = new System.Collections.Hashtable(); // adding values in gash table for data post
            data.Add("txnid", txnid);
            data.Add("key", ckv.easebuzzkey);
            string AmountForm = Convert.ToDecimal(amount.Trim()).ToString("g29");// eliminating trailing zeros

            amount = AmountForm;
            data.Add("amount", amount);
            data.Add("firstname", firstname.Trim());
            data.Add("email", email.Trim());
            data.Add("phone", phone.Trim());
            data.Add("productinfo", productinfo.Trim());
            data.Add("surl", surl.Trim());
            data.Add("furl", furl.Trim());
            data.Add("udf1", udf1.Trim());
            data.Add("udf2", udf2.Trim());
            data.Add("udf3", udf3.Trim());
            data.Add("udf4", udf4.Trim());
            data.Add("udf5", udf5.Trim());


            // generate hash
            hashVarsSeq = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10".Split('|'); // spliting hash sequence from config
            hash_string = "";
            foreach (string hash_var in hashVarsSeq)
            {
                hash_string = hash_string + (data.ContainsKey(hash_var) ? data[hash_var].ToString() : "");
                hash_string = hash_string + '|';
            }
            hash_string += salt;                                            // appending SALT
            gen_hash     = Easebuzz_Generatehash512(hash_string).ToLower(); //generating hash
            data.Add("hash", gen_hash);
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var client  = new RestClient("https://pay.easebuzz.in/payment/initiateLink");
            var request = new RestRequest(Method.POST);

            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            string postdata = "firstname=" + firstname + "&amount=" + amount + "&email=" + email + "&productinfo=FastagRecharge&phone=" + phone + "&surl=https://payment.tollpay.in/success.aspx&furl=https://payment.tollpay.in/success.aspx&txnid=" + txnid + "&key=" + ckv.easebuzzkey + "&udf1=&udf2=&udf3=&udf4=&udf4=&udf5=&udf6=&udf7=&udf8=&udf9=&udf10=&hash=" + gen_hash;

            request.AddParameter("application/x-www-form-urlencoded", postdata, ParameterType.RequestBody);
            IRestResponse   response = client.Execute(request);
            clsRespEaseBuzz obj      = JsonConvert.DeserializeObject <clsRespEaseBuzz>(response.Content);

            if (obj.status == 1)
            {
                DP_TPEntities          db  = new DP_TPEntities();
                PaymentGatewayResponse pgr = new PaymentGatewayResponse();
                pgr.firstname   = firstname;
                pgr.email       = email;
                pgr.CreatedDate = DateTime.Now;
                pgr.phone       = phone;
                pgr.amount      = Convert.ToDecimal(amount);
                pgr.txnid       = txnid;
                db.PaymentGatewayResponses.Add(pgr);
                db.SaveChanges();
                string strForm = easebuzz_action_url + obj.data;                     //Easebuzz_PreparePOSTForm(easebuzz_action_url, data);
                return(strForm);
            }
            else
            {
                DP_TPEntities          db  = new DP_TPEntities();
                PaymentGatewayResponse pgr = new PaymentGatewayResponse();
                pgr.firstname   = firstname;
                pgr.email       = email;
                pgr.CreatedDate = DateTime.Now;
                pgr.phone       = phone;
                pgr.amount      = Convert.ToDecimal(amount);
                pgr.txnid       = txnid;
                db.PaymentGatewayResponses.Add(pgr);
                db.SaveChanges();
                return(response.Content);
            }
        }
コード例 #18
0
 public bool ExecuteTransaction()
 {
     response = PaymentGatewayResponse.NoRequestInitiated;
     return false;
 }
コード例 #19
0
        /// <summary>
        /// Pass order info to paypal and recieve back a token
        /// then redirect to PayPal passing the token.
        /// When PayPal redirects back to your site call
        /// GetExpressCheckoutDetails passing the token
        /// </summary>
        /// <returns></returns>
        public bool CallSetExpressCheckout()
        {
            bool result = false;

            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("USER="******"&PWD=" + HttpUtility.UrlEncode(merchantAPIPassword));
            requestBody.Append("&SIGNATURE=" + HttpUtility.UrlEncode(merchantAPITransactionKey));
            requestBody.Append("&VERSION=" + HttpUtility.UrlEncode(apiVersion));
            requestBody.Append("&METHOD=SetExpressCheckout");

            // ## REQUIRED
            //AMT is deprecated since version 63.0. Use PAYMENTREQUEST_0_AMT instead.
            requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
            //requestBody.Append("&PAYMENTREQUEST_0_AMT=" + HttpUtility.UrlEncode(FormatCharge()));

            //Sum of cost of all items in this order. For digital goods, this field is required.
            //requestBody.Append("&PAYMENTREQUEST_0_ITEMAMT=" + HttpUtility.UrlEncode(FormatCharge()));

            if (returnUrl.Length == 0) throw new ArgumentException("ReturnUrl must be provided");

            // TODO: do we need to urlencode here?
            requestBody.Append("&RETURNURL=" + HttpUtility.UrlEncode(returnUrl));
            // URL to which the customer’s browser is returned after choosing to pay
            // with PayPal.
            // NOTE: PayPal recommends that the value be the final review page on
            // which the customer confirms the order and payment or billing
            // agreement.

            if (cancelUrl.Length == 0) throw new ArgumentException("CancelUrl must be provided");

            // TODO: do we need to urlencode here?
            requestBody.Append("&CANCELURL=" + HttpUtility.UrlEncode(cancelUrl));
            //CANCELURL URL to which the customer is returned if he does not approve the use of
            //PayPal to pay you.
            //NOTE: PayPal recommends that the value be the original page on which
            //the customer chose to pay with PayPal or establish a billing
            //agreement.

            // ## END REQUIRED

            requestBody.Append("&PAYMENTACTION=Sale");
            //How you want to obtain payment:

            // Sale indicates that this is a final sale for which you are requesting payment.

            // Authorization indicates that this payment is a basic authorization
            // subject to settlement with PayPal Authorization & Capture.

            // Order indicates that this payment is an order authorization subject to
            // settlement with PayPal Authorization & Capture.

            //If the transaction does not include a one-time purchase, this field is
            //ignored.
            //NOTE:You cannot set this value to Sale in SetExpressCheckout
            //request and then change this value to Authorization or Order
            //on the final API DoExpressCheckoutPayment request. If the
            //value is set to Authorization or Order in
            //SetExpressCheckout, the value may be set to Sale or the same
            //value (either Authorization or Order) in
            //DoExpressCheckoutPayment.
            //Character length and limit: Up to 13 single-byte alphabetic characters
            //Default value: Sale

            if (currencyCode.Length > 0)
            {
                //CURRENCYCODE is deprecated since version 63.0. Use PAYMENTREQUEST_n_CURRENCYCODE instead.
                requestBody.Append("&CURRENCYCODE=" + HttpUtility.UrlEncode(currencyCode));
                //requestBody.Append("&PAYMENTREQUEST_0_CURRENCYCODE=" + HttpUtility.UrlEncode(currencyCode));
            }

            //requestBody.Append("");

            //requestBody.Append("&MAXAMT=");
            //MAXAMT - optional The expected maximum total amount of the complete order, including
            // shipping cost and tax charges.

            //EMAIL customer email
            if (buyerEmail.Length > 0)
            {
                requestBody.Append("&EMAIL=" + HttpUtility.UrlEncode(buyerEmail));
            }

            // DESC order description
            // Description of items the customer is purchasing
            if (orderDescription.Length > 0)
            {
                requestBody.Append("&DESC=" + HttpUtility.UrlEncode(orderDescription));
            }

            //CUSTOM A free-form field for your own use, such as a tracking number or other
            //value you want PayPal to return on GetExpressCheckoutDetails
            //response and DoExpressCheckoutPayment response. max length 256
            if (merchantCartId.Length > 0)
            {
                requestBody.Append("&CUSTOM=" + HttpUtility.UrlEncode(merchantCartId));
            }

            //INVNUM
            //Your own unique invoice or tracking number. PayPal returns this value to
            //you on DoExpressCheckoutPayment response.
            //If the transaction does not include a one-time purchase, this field is
            //ignored.
            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&INVNUM=" + HttpUtility.UrlEncode(merchantInvoiceNumber));
            }

            //REQCONFIRMSHIPPING  1 = require a validated address for shipping, default 0
            if (requireConfirmedShippingAddress)
            {
                requestBody.Append("&REQCONFIRMSHIPPING=1");

            }

            //NOSHIPPING 1 = true means dont show shipping options
            if (noShipping)
            {
                requestBody.Append("&NOSHIPPING=1");
            }

            // ADDROVERRIDE 1 = true 0 = false
            // indicates that the PayPal pages should display the shipping
            // address set by you
            if (overrideShippingAddress)
            {
                requestBody.Append("&ADDROVERRIDE=1");
            }

            //SHIPTOSTREET
            if (shipToAddress.Length > 0)
            {
                requestBody.Append("&SHIPTOSTREET=" + HttpUtility.UrlEncode(shipToAddress));

                //SHIPTONAME
                if (shipToLastName.Length > 0)
                {
                    requestBody.Append("&SHIPTONAME=" + HttpUtility.UrlEncode(shipToFirstName + " " + shipToLastName));
                }

                //SHIPTOSTREET2

                //SHIPTOCITY
                if (shipToCity.Length > 0)
                {
                    requestBody.Append("&SHIPTOCITY=" + HttpUtility.UrlEncode(shipToCity));
                }

                //SHIPTOSTATE
                if (shipToState.Length > 0)
                {
                    requestBody.Append("&SHIPTOSTATE=" + HttpUtility.UrlEncode(shipToState));
                }

                //SHIPTOCOUNTRYCODE
                if (shipToCountry.Length > 0)
                {
                    requestBody.Append("&SHIPTOCOUNTRYCODE=" + HttpUtility.UrlEncode(shipToCountry));
                }

                //SHIPTOZIP
                if (shipToPostalCode.Length > 0)
                {
                    requestBody.Append("&SHIPTOZIP=" + HttpUtility.UrlEncode(shipToPostalCode));
                }

                //PHONENUM
                if (shipToPhone.Length > 0)
                {
                    requestBody.Append("&PHONENUM=" + HttpUtility.UrlEncode(shipToPhone));
                }

            }

            //TOKEN -- not required here as PayPal will generate it ad provide it in the response
            // we will pass it for subsequent requests, ie GetCheckoutDetails DoPayment
            // A timestamped token by which you identify to PayPal that you are
            // processing this payment with Express Checkout.

            //LOCALECODE  optional
            //Locale of pages displayed by PayPal during Express Checkout
            // unknown values default to US
            // options AU DE FR IT GB ES US
            if (this.shipToCountry.Length > 0)
            {
                requestBody.Append("&LOCALECODE=" + HttpUtility.UrlEncode(shipToCountry));
            }

            //PAGESTYLE
            //Sets the Custom Payment Page Style for payment pages associated with
            //this button/link. This value corresponds to the HTML variable page_style
            //for customizing payment pages. The value is the same as the Page Style
            //Name you chose when adding or editing the page style from the Profile
            //subtab of the My Account tab of your PayPal account.
            //Character length and limitations: 30 single-byte alphabetic characters.

            //HDRIMG
            //URL for the image you want to appear at the top left of the payment page.
            //The image has a maximum size of 750 pixels wide by 90 pixels high.
            //PayPal recommends that you provide an image that is stored on a secure
            //(https) server. If you do not specify an image, the business name is
            //displayed.

            //HDRBORDERCOLOR
            //Sets the border color around the header of the payment page. The border
            //is a 2-pixel perimeter around the header space, which is 750 pixels wide
            //by 90 pixels high. By default, the color is black.
            //Character length and limitations: Six character HTML hexadecimal color
            //code in ASCII

            //HDRBACKCOLOR
            //Sets the background color for the header of the payment page. By default,
            //the color is white.
            //Character length and limitation: Six character HTML hexadecimal color
            //code in ASCII

            //GIROPAYSUCCESSURL
            //The URL on the merchant site to redirect to after a successful giropay
            //payment. .
            //Use this field only if you are using giropay or bank transfer payment
            //methods in Germany.

            //GIROPAYCANCELURL
            //The URL on the merchant site to redirect to after a giropay or bank
            //transfer payment is cancelled or fails.
            //Use this field only if you are using giropay or bank transfer payment
            //methods in Germany.

            //BANKTXNPENDINGURL
            //The URL on the merchant site to transfer to after a bank transfer payment.
            //Use this field only if you are using giropay or bank transfer payment
            //methods in Germany.

            //L_BILLINGTYPEn Type of billing agreement.
            //For recurring payments, this field is required and must be set to
            //RecurringPayments.

            //L_BILLING
            //AGREEMENT
            //DESCRIPTIONn
            //Description of goods or services associated with the billing agreement.
            //PayPal recommends that you provide a brief summary of the terms &
            //conditions of the billing agreement

            //L_CUSTOMn Custom annotation field for your own use.
            //NOTE: This field is ignored for recurring payments

            //L_PAYMENTTYPEn Specifies type of PayPal payment you require for the billing agreement,
            //which is one of the following values.
            // Any
            //InstantOnly
            //NOTE: This field is ignored for recurring payments

            //IMPORTANT: To use SetExpressCheckout for recurring payments, you must set the
            //version parameter to 50.0 in your NVP API calls.

            //requestBody.Append("&VERSION=50.0");

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";

            webRequest.Timeout = timeoutInMilliseconds;

            webRequest.ContentType = "application/x-www-form-urlencoded";

            string encodedBody = requestBody.ToString();
            log.Debug(encodedBody);

            webRequest.ContentLength = encodedBody.Length;

            requestStream = new StreamWriter(webRequest.GetRequestStream());

            if (requestStream != null)
            {

                requestStream.Write(encodedBody);

            }

            if (requestStream != null)
                requestStream.Close();

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseSetExpressCheckoutResponse();
            }
            else
            {

                response = PaymentGatewayResponse.Error;
                return false;
            }

            //After you receive a successful response from SetExpressCheckout, add the TOKEN from
            //SetExpressCheckout response as a name/value pair to the following URL, and redirect your
            //customer’s browser to it:
            //https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&
            //token=value_from_SetExpressCheckoutResponse
            //For redirecting the customer’s browser to the PayPal login page, PayPal recommends that you
            //use the HTTPS response 302 “Object Moved” with the URL above as the value of the
            //Location header in the HTTPS response. Ensure that you use an SSL-enabled server to prevent
            //browser warnings about a mix of secure and insecure graphics.

            return result;
        }
コード例 #20
0
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public bool CallGetExpressCheckoutDetails()
        {
            bool result = false;

            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("USER="******"&PWD=" + HttpUtility.UrlEncode(merchantAPIPassword));
            requestBody.Append("&SIGNATURE=" + HttpUtility.UrlEncode(merchantAPITransactionKey));
            //if (merchantPayPalEmailAddress.Length > 0)
            //{
            //    requestBody.Append("&SUBJECT=" + HttpUtility.UrlEncode(merchantPayPalEmailAddress));
            //}
            requestBody.Append("&VERSION=" + HttpUtility.UrlEncode(apiVersion));

            //TOKEN A timestamped token, the value of which was returned by
            //SetExpressCheckout response.
            //Character length and limitations: 20 single-byte characters
            if (payPalToken.Length == 0) throw new ArgumentException("PayPalToken must be provided");

            requestBody.Append("&TOKEN=" + HttpUtility.UrlEncode(payPalToken));
            requestBody.Append("&METHOD=GetExpressCheckoutDetails");

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";

            webRequest.Timeout = timeoutInMilliseconds;

            webRequest.ContentType = "application/x-www-form-urlencoded";

            string encodedBody = requestBody.ToString();
            log.Debug(encodedBody);

            webRequest.ContentLength = encodedBody.Length;

            requestStream = new StreamWriter(webRequest.GetRequestStream());

            if (requestStream != null)
            {

                requestStream.Write(encodedBody);

            }

            if (requestStream != null)
                requestStream.Close();

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseGetExpressCheckoutDetailsResponse();

            }
            else
            {

                response = PaymentGatewayResponse.Error;
                return false;
            }

            return result;
        }
コード例 #21
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[]   pairSeparator   = { '&' };
                char[]   keyValSeparator = { '=' };
                string[] keyValPairs     = rawResponse.Split(pairSeparator, StringSplitOptions.None);

                StringDictionary responseResults = new StringDictionary();

                foreach (string keyVal in keyValPairs)
                {
                    string[] pair = keyVal.Split(keyValSeparator, StringSplitOptions.None);
                    if (pair.Length >= 2)
                    {
                        responseResults.Add(pair[0], pair[1]);
                    }
                }

                if (responseResults.ContainsKey("ACK"))
                {
                    switch (responseResults["ACK"])
                    {
                    case "Success":
                    case "SuccessWithWarning":

                        response = PaymentGatewayResponse.Approved;
                        break;

                    case "2":
                        response = PaymentGatewayResponse.Declined;
                        break;

                    case "Warning":
                    case "Failure":
                    case "FailureWithWarning":
                    case "Error":

                        if (responseResults.ContainsKey("L_LONGMESSAGE0"))
                        {
                            responseReason = HttpUtility.UrlDecode(responseResults["L_LONGMESSAGE0"]);
                        }

                        if (responseResults.ContainsKey("L_ERRORCODE0"))
                        {
                            reasonCode = HttpUtility.UrlDecode(responseResults["L_ERRORCODE0"]);
                        }

                        string shortMessage = string.Empty;

                        if (responseResults.ContainsKey("L_SHORTMESSAGE0"))
                        {
                            shortMessage = HttpUtility.UrlDecode(responseResults["L_SHORTMESSAGE0"]);
                        }

                        switch (shortMessage)
                        {
                        case "Gateway Decline":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        default:
                            response = PaymentGatewayResponse.Error;
                            break;
                        }

                        break;
                    }
                }

                if (responseResults.ContainsKey("TIMESTAMP"))
                {
                }

                if (responseResults.ContainsKey("AVSCODE"))
                {
                    avsResultCode = HttpUtility.UrlDecode(responseResults["AVSCODE"]);
                }

                if (responseResults.ContainsKey("TRANSACTIONID"))
                {
                    transactionID = HttpUtility.UrlDecode(responseResults["TRANSACTIONID"]);
                }

                if (responseResults.ContainsKey("AUTHORIZATIONID"))
                {
                    approvalCode = HttpUtility.UrlDecode(responseResults["AUTHORIZATIONID"]);
                }

                //if (responseResults.ContainsKey("CVV2MATCH"))
                //{


                //}

                //if (responseResults.ContainsKey("AMT"))
                //{


                //}

                //
            }
        }
コード例 #22
0
 public bool deSerializeAndSubmitOrder(PaymentGatewayResponse response, out string error, out SerializedOrderHolder holder)
 {
     return(OrderProvider.deSerializeAndSubmitOrder(response, out error, out holder));
 }
コード例 #23
0
        private void SubmitOrder(PaymentGatewayResponse response)
        {
            LoggerHelper.Info(string.Format("SubmitOrder. OrderNumber - {0}", response.OrderNumber));
            string distributorId = string.Empty;
            string locale        = string.Empty;
            string error         = string.Empty;
            var    holder        = new SerializedOrderHolder();

            if (OrderProvider.deSerializeAndSubmitOrder(response, out error, out holder))
            {
                if (holder != null && !String.IsNullOrEmpty(holder.Email))
                {
                    try
                    {
                        MyHLShoppingCart shoppingCart = null;
                        if (response.ReloadShoppingCart)
                        {
                            shoppingCart = ShoppingCartProvider.GetBasicShoppingCartFromService(holder.ShoppingCartId, holder.DistributorId, locale);
                        }
                        else
                        {
                            shoppingCart = ShoppingCartProvider.GetShoppingCart(holder.DistributorId, holder.Locale, true);
                        }
                        //ExceptionFix: Validating shoppingCart is not null
                        if (shoppingCart != null)
                        {
                            shoppingCart.EmailAddress = holder.Email;
                            if (holder.Order != null)
                            {
                                shoppingCart.Totals = (holder.Order as Order_V01).Pricing as OrderTotals_V01;
                                if (shoppingCart.ShoppingCartID == holder.ShoppingCartId)
                                {
                                    EmailHelper.SendEmail(shoppingCart, holder.Order as Order_V01);
                                }
                            }
                            CleanupOrder(shoppingCart, shoppingCart.DistributorID);
                        }
                    }
                    catch (Exception ex)
                    {
                        LoggerHelper.Error(string.Format("PaymentGatewayManager SubmitOrder-SendEmail fails : {0} ", ex.Message));
                    }
                }
            }
            else
            {
                LoggerHelper.Info(string.Format("SubmitOrder. deSerializeAndSubmitOrder could not deSerializeAndSubmitOrder. OrderNumber - {0}", response.OrderNumber));
                LoggerHelper.Error(error);
                if (error.Contains("DUPLICATE"))
                {
                }
                else if (error.Contains("TIMEOUT"))
                {
                    lbSubmitOrderStatus.Text = PlatformResources.GetGlobalResourceString("ErrorMessage", "Resubmit");
                }
                else if (error.Contains("ORDER CANNOT BE FULFILLED FOR THE DISTRIBUTOR"))
                {
                    lbSubmitOrderStatus.Text = PlatformResources.GetGlobalResourceString("ErrorMessage", "CantOrder");
                }
                else
                {
                    lbSubmitOrderStatus.Text = PlatformResources.GetGlobalResourceString("ErrorMessage", "TransactionFail");
                }
            }
        }
コード例 #24
0
        private void ParseGetExpressCheckoutDetailsResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[] pairSeparator = { '&' };
                char[] keyValSeparator = { '=' };
                string[] keyValPairs = rawResponse.Split(pairSeparator, StringSplitOptions.None);

                StringDictionary responseResults = new StringDictionary();

                foreach (string keyVal in keyValPairs)
                {
                    string[] pair = keyVal.Split(keyValSeparator, StringSplitOptions.None);
                    if (pair.Length >= 2)
                    {
                        responseResults.Add(pair[0], pair[1]);
                    }

                }

                if (responseResults.ContainsKey("ACK"))
                {
                    switch (responseResults["ACK"])
                    {
                        case "Success":
                        case "SuccessWithWarning":

                            response = PaymentGatewayResponse.Approved;
                            break;

                        case "2":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        case "Warning":
                        case "Failure":
                        case "FailureWithWarning":
                        case "Error":

                            response = PaymentGatewayResponse.Error;

                            if (responseResults.ContainsKey("L_LONGMESSAGE0"))
                            {
                                responseReason = HttpUtility.UrlDecode(responseResults["L_LONGMESSAGE0"]);
                            }

                            if (responseResults.ContainsKey("L_ERRORCODE0"))
                            {
                                reasonCode = HttpUtility.UrlDecode(responseResults["L_ERRORCODE0"]);

                            }

                            break;
                    }

                }

                //TOKEN The timestamped token value that was returned by SetExpressCheckout response
                //and passed on GetExpressCheckoutDetails request
                if (responseResults.ContainsKey("TOKEN"))
                {
                    payPalToken = HttpUtility.UrlDecode(responseResults["TOKEN"]);

                }

                //EMAIL Email address of payer
                if (responseResults.ContainsKey("EMAIL"))
                {
                    buyerEmail = HttpUtility.UrlDecode(responseResults["EMAIL"]);

                }

                //PAYERID Unique PayPal customer account identification number
                if (responseResults.ContainsKey("PAYERID"))
                {
                    payPalPayerId = HttpUtility.UrlDecode(responseResults["PAYERID"]);

                }

                //PAYERSTATUS Status of payer. verified or unverified
                if (responseResults.ContainsKey("PAYERSTATUS"))
                {
                    payPalPayerStatus = HttpUtility.UrlDecode(responseResults["PAYERSTATUS"]);

                }

                //SALUTATION Payer’s salutation
                if (responseResults.ContainsKey("SALUTATION"))
                {
                    shipToSalutation = HttpUtility.UrlDecode(responseResults["SALUTATION"]);

                }

                //FIRSTNAME Payer’s first name
                if (responseResults.ContainsKey("FIRSTNAME"))
                {
                    shipToFirstName = HttpUtility.UrlDecode(responseResults["FIRSTNAME"]);

                }

                //MIDDLENAME Payer’s middle name
                //LASTNAME Payer’s last name
                if (responseResults.ContainsKey("LASTNAME"))
                {
                    shipToLastName = HttpUtility.UrlDecode(responseResults["LASTNAME"]);

                }
                //SUFFIX Payer’s suffix
                if (responseResults.ContainsKey("SUFFIX"))
                {
                    shipToNameSuffix = HttpUtility.UrlDecode(responseResults["SUFFIX"]);

                }

                //COUNTRYCODE Payer’s country of residence in the form of ISO standard 3166 two-character country
                //codes.

                //SHIPTONAME Person’s name associated with this address
                //if (responseResults.ContainsKey("SHIPTONAME"))
                //{
                //    shipToLastName = HttpUtility.UrlDecode(responseResults["SHIPTONAME"]);

                //}

                //SHIPTOSTREET First street address
                if (responseResults.ContainsKey("SHIPTOSTREET"))
                {
                    shipToAddress = HttpUtility.UrlDecode(responseResults["SHIPTOSTREET"]);

                }

                //SHIPTOSTREET2 Second street address
                if (responseResults.ContainsKey("SHIPTOSTREET2"))
                {
                    shipToAddress2 = HttpUtility.UrlDecode(responseResults["SHIPTOSTREET2"]);

                }

                //SHIPTOCITY Name of city
                if (responseResults.ContainsKey("SHIPTOCITY"))
                {
                    shipToCity = HttpUtility.UrlDecode(responseResults["SHIPTOCITY"]);

                }

                //SHIPTOSTATE State or province
                if (responseResults.ContainsKey("SHIPTOSTATE"))
                {
                    shipToState = HttpUtility.UrlDecode(responseResults["SHIPTOSTATE"]);

                }

                //SHIPTOCOUNTRYCODE Country code
                if (responseResults.ContainsKey("SHIPTOCOUNTRYCODE"))
                {
                    shipToCountry = HttpUtility.UrlDecode(responseResults["SHIPTOCOUNTRYCODE"]);

                }

                //SHIPTOZIP U.S. Zip code or other country-specific postal code.
                if (responseResults.ContainsKey("SHIPTOZIP"))
                {
                    shipToPostalCode = HttpUtility.UrlDecode(responseResults["SHIPTOZIP"]);

                }

                //ADDRESSSTATUS Status of street address on file with PayPal
                if (responseResults.ContainsKey("ADDRESSSTATUS"))
                {
                    shipToAddressStatus = HttpUtility.UrlDecode(responseResults["ADDRESSSTATUS"]);

                }

                //CUSTOM A free-form field for your own use, as set by you in the Custom element of
                //SetExpressCheckout request
                if (responseResults.ContainsKey("CUSTOM"))
                {
                    this.merchantCartId = HttpUtility.UrlDecode(responseResults["CUSTOM"]);

                }

                //INVNUM Your own invoice or tracking number, as set by you in the element of the same name in
                if (responseResults.ContainsKey("INVNUM"))
                {
                    this.merchantInvoiceNumber = HttpUtility.UrlDecode(responseResults["INVNUM"]);

                }

                //SetExpressCheckout request .
                //PHONENUM Payer’s contact telephone number
                if (responseResults.ContainsKey("PHONENUM"))
                {
                    this.shipToPhone = HttpUtility.UrlDecode(responseResults["PHONENUM"]);

                }

                //REDIRECTREQUIRED Flag to indicate whether you need to redirect the customer to back to PayPal after
                //completing the transaction.
                //NOTE: Use this field only if you are using giropay or bank transfer payment methods in
                //Germany.

            }
        }
コード例 #25
0
        public bool ExecuteTransaction()
        {
            bool result = false;

            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("USER="******"&PWD=" + HttpUtility.UrlEncode(merchantAPIPassword));
            requestBody.Append("&SIGNATURE=" + HttpUtility.UrlEncode(merchantAPITransactionKey));
            //if (merchantPayPalEmailAddress.Length > 0)
            //{
            //    requestBody.Append("&SUBJECT=" + HttpUtility.UrlEncode(merchantPayPalEmailAddress));
            //}
            requestBody.Append("&VERSION=" + HttpUtility.UrlEncode(apiVersion));

            requestBody.Append("&BUTTONSOURCE=SourceTreeSolutions_SP");

            switch (transactionType)
            {
                // default transaction type
                case PaymentGatewayTransactionType.AuthCapture:
                    requestBody.Append("&METHOD=DoDirectPayment");
                    requestBody.Append("&PAYMENTACTION=Sale");
                    requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                    break;

                case PaymentGatewayTransactionType.AuthOnly:
                    requestBody.Append("&METHOD=DoDirectPayment");
                    requestBody.Append("&PAYMENTACTION=Authorization");
                    requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                    break;

                case PaymentGatewayTransactionType.CaptureOnly:

                    throw new NotSupportedException();

                case PaymentGatewayTransactionType.Credit:
                    if (previousTransactionID.Length == 0)
                        throw new NotSupportedException("Credit not supported without a previous transactionID");

                    requestBody.Append("&METHOD=RefundTransaction, ");
                    requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                    requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                    requestBody.Append("&REFUNDTYPE=Full");

                    break;

                case PaymentGatewayTransactionType.PriorAuthCapture:

                    if (previousTransactionID.Length == 0)
                        throw new NotSupportedException("PriorAuthCapture not supported without a previous transactionID");

                    requestBody.Append("&METHOD=DoCapture");
                    requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                    requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                    requestBody.Append("&COMPLETETYPE=Complete");

                    break;

                case PaymentGatewayTransactionType.Void:

                    if (previousTransactionID.Length == 0)
                        throw new NotSupportedException("Void not supported without a previous transactionID");

                    requestBody.Append("&METHOD=DoVoid");
                    requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                    requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                    requestBody.Append("&COMPLETETYPE=Complete");

                    break;

            }

            requestBody.Append("&CREDITCARDTYPE=" + HttpUtility.UrlEncode(cardType));
            requestBody.Append("&ACCT=" + HttpUtility.UrlEncode(cardNumber));
            requestBody.Append("&EXPDATE=" + HttpUtility.UrlEncode(cardExpiration));

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&CVV2=" + HttpUtility.UrlEncode(cardSecurityCode));
            }

            requestBody.Append("&FIRSTNAME=" + HttpUtility.UrlEncode(cardOwnerFirstName));
            requestBody.Append("&LASTNAME=" + HttpUtility.UrlEncode(cardOwnerLastName));
            requestBody.Append("&STREET=" + HttpUtility.UrlEncode(cardBillingAddress));
            requestBody.Append("&CITY=" + HttpUtility.UrlEncode(cardBillingCity));
            requestBody.Append("&STATE=" + HttpUtility.UrlEncode(cardBillingState));
            requestBody.Append("&ZIP=" + HttpUtility.UrlEncode(cardBillingPostalCode));
            requestBody.Append("&COUNTRYCODE=" + HttpUtility.UrlEncode(cardBillingCountryCode));
            requestBody.Append("&PHONENUM=" + HttpUtility.UrlEncode(cardBillingPhone));
            requestBody.Append("&IPADDRESS=" + HttpUtility.UrlEncode(customerIPAddress));

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&INVNUM=" + HttpUtility.UrlEncode(merchantInvoiceNumber));
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&CURRENCYCODE=" + HttpUtility.UrlEncode(currencyCode));
            }

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";

            webRequest.Timeout = timeoutInMilliseconds;

            webRequest.ContentType = "application/x-www-form-urlencoded";

            string encodedBody = requestBody.ToString();
            log.Debug(encodedBody);
            webRequest.ContentLength = encodedBody.Length;

            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
            {

                requestStream.Write(encodedBody);

            }

            if (requestStream != null)
                requestStream.Close();

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseResponse();
            }
            else
            {
                response = PaymentGatewayResponse.Error;
                return false;
            }

            return result;
        }
コード例 #26
0
 private IAPayment SavePayment(PaymentGatewayResponse paymentGatewayResponse)
 {
     var oIAPayment = new IAPayment
      {
     Total = GetTotal(),
     Email = CardProfile.ReceiptEmailAddressCsv,
     Company = m_txtCompany.Text,
     Instructions = m_txtInstructions.Text,
     CreditCardFirstName = MemberProtect.Cryptography.Encrypt(CardProfile.FirstName),
     CreditCardLastName = MemberProtect.Cryptography.Encrypt(CardProfile.LastName),
     CreditCardType = MemberProtect.Cryptography.Encrypt(CardProfile.CardType),
     CreditCardNumber = MemberProtect.Cryptography.Encrypt(CardProfile.CreditCardNumber),
     AuthorizeNetTransactionID = paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.TransactionId),
     AuthorizeNetProcessResponse = paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText),
     CreatedDateTime = DateTime.Now,
     Zip = ""
      };
      DataAccess.IAPayments.InsertOnSubmit(oIAPayment);
      DataAccess.SubmitChanges();
      return oIAPayment;
 }
コード例 #27
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[] pairSeparator = { '&' };
                char[] keyValSeparator = { '=' };
                string[] keyValPairs = rawResponse.Split(pairSeparator, StringSplitOptions.None);

                StringDictionary responseResults = new StringDictionary();

                foreach (string keyVal in keyValPairs)
                {
                    string[] pair = keyVal.Split(keyValSeparator, StringSplitOptions.None);
                    if (pair.Length >= 2)
                    {
                        responseResults.Add(pair[0], pair[1]);
                    }
                }

                if (responseResults.ContainsKey("ACK"))
                {
                    switch (responseResults["ACK"])
                    {
                        case "Success":
                        case "SuccessWithWarning":

                            response = PaymentGatewayResponse.Approved;
                            break;

                        case "2":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        case "Warning":
                        case "Failure":
                        case "FailureWithWarning":
                        case "Error":

                            if (responseResults.ContainsKey("L_LONGMESSAGE0"))
                            {
                                responseReason = HttpUtility.UrlDecode(responseResults["L_LONGMESSAGE0"]);
                            }

                            if (responseResults.ContainsKey("L_ERRORCODE0"))
                            {
                                reasonCode = HttpUtility.UrlDecode(responseResults["L_ERRORCODE0"]);

                            }

                            string shortMessage = string.Empty;

                            if (responseResults.ContainsKey("L_SHORTMESSAGE0"))
                            {
                                shortMessage = HttpUtility.UrlDecode(responseResults["L_SHORTMESSAGE0"]);
                            }

                            switch (shortMessage)
                            {
                                case "Gateway Decline":
                                    response = PaymentGatewayResponse.Declined;
                                    break;

                                default:
                                    response = PaymentGatewayResponse.Error;
                                    break;

                            }

                            break;

                    }

                }

                if (responseResults.ContainsKey("TIMESTAMP"))
                {

                }

                if (responseResults.ContainsKey("AVSCODE"))
                {
                    avsResultCode = HttpUtility.UrlDecode(responseResults["AVSCODE"]);

                }

                if (responseResults.ContainsKey("TRANSACTIONID"))
                {
                    transactionID = HttpUtility.UrlDecode(responseResults["TRANSACTIONID"]);

                }

                if (responseResults.ContainsKey("AUTHORIZATIONID"))
                {
                    approvalCode = HttpUtility.UrlDecode(responseResults["AUTHORIZATIONID"]);

                }

                //if (responseResults.ContainsKey("CVV2MATCH"))
                //{

                //}

                //if (responseResults.ContainsKey("AMT"))
                //{

                //}

                //

            }
        }
コード例 #28
0
        public bool ExecuteTransaction()
        {
            bool          result      = false;
            StringBuilder requestBody = new StringBuilder();

            requestBody.Append("publisher-name=" + merchantAPILogin);
            requestBody.Append("&publisher-password="******"&paymethod=credit");
            credentials = String.Format("publisher-name={0}&publisher-password={1}", merchantAPILogin, merchantAPITransactionKey);

            switch (transactionType)
            {
            case PaymentGatewayTransactionType.AuthCapture:
                requestBody.Append("&mode=auth");
                requestBody.Append("&authtype=authpostauth");    //pnp Batches everything this autmatically marks transactions for settlement... useless if merchant uses automatic batches
                break;

            case PaymentGatewayTransactionType.AuthOnly:
                requestBody.Append("&mode=auth");
                requestBody.Append("&authtype=authonly");    //defaults to authonly, filled in for clarity
                break;

            case PaymentGatewayTransactionType.CaptureOnly:
                requestBody.Append("&mode=auth");
                requestBody.Append("&authtype=authpostauth");    //AFAIK they don't do this, with maybe the exception of Mercury Gift cards... which are catured realtime
                break;

            case PaymentGatewayTransactionType.Credit:
                requestBody.Append("&mode=newreturn");    //mode becomes newreturn
                break;

            case PaymentGatewayTransactionType.PriorAuthCapture:
                requestBody.Append("&authtype=authprev");    //don't know the translation here between anet and pnp assUme force-auth or authprev
                break;

            case PaymentGatewayTransactionType.Void:
                requestBody.Append("&mode=void");
                requestBody.Append("&txn-type=auth");
                break;
            }

            requestBody.Append("&card-amount=" + FormatCharge());
            //requestBody.Append("&x_delim_data=TRUE");
            //requestBody.Append("&x_delim_char=|");
            //requestBody.Append("&x_relay_response=FALSE");

            requestBody.Append("&card-number=" + cardNumber);
            requestBody.Append("&card-exp=" + cardExpiration);

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&card-cvv=" + cardSecurityCode);
            }

            //if (authenticationIndicator.Length > 0)
            //{
            //    requestBody.Append("&x_authentication_indicator=" + authenticationIndicator);
            //}

            //if (cardholderAuthenticationValue.Length > 0)
            //{
            //   requestBody.Append("&x_cardholder_authentication_value=" + cardholderAuthenticationValue);
            //}

            if (previousTransactionID.Length > 0)
            {
                requestBody.Append("&prevorderid=" + previousTransactionID);
            }

            // if (previousApprovalCode.Length > 0)
            //{
            // requestBody.Append("&x_auth_code=" + previousApprovalCode);
            // }

            //requestBody.Append("&x_first_name=" + cardOwnerFirstName);
            //requestBody.Append("&x_last_name=" + cardOwnerLastName);
            requestBody.Append("&card-name=" + cardOwnerFirstName + " " + cardOwnerLastName);//This could be bad, should try to figure out how to have "Name as it appears on you cc"
            //requestBody.Append("&x_company=" + cardOwnerCompanyName);
            requestBody.Append("&card-address1=" + cardBillingAddress);
            requestBody.Append("&card-city=" + cardBillingCity);
            if ((cardBillingCountry != "US") && (cardBillingCountry != "CA"))
            {
                requestBody.Append("&card-state=ZZ");
                requestBody.Append("&card-prov=" + cardBillingState);
            }
            else
            {
                requestBody.Append("&card-state=" + cardBillingState);
            }
            requestBody.Append("&card-zip=" + cardBillingPostalCode);
            requestBody.Append("&card-country=" + cardBillingCountry);
            requestBody.Append("&phone=" + cardBillingPhone);
            bool shipInfo = false;

            if (shipToFirstName.Length > 0)
            {
                requestBody.Append("&shipname=" + shipToFirstName);
            }
            if (shipToLastName.Length > 0)
            {
                requestBody.Append(" " + shipToLastName);
            }
            //            if (shipToCompanyName.Length > 0)
            //            {
            //                requestBody.Append("&x_ship_to_company=" + shipToCompanyName);
            //            }
            if (shipToAddress.Length > 0)
            {
                requestBody.Append("&shipaddress1=" + shipToAddress);
            }
            if (shipToCity.Length > 0)
            {
                requestBody.Append("&city=" + shipToCity);
            }
            if (shipToState.Length > 0)
            {
                if ((shipToCountry != "US") && (shipToCountry != "CA"))
                {
                    requestBody.Append("&state=ZZ");
                    requestBody.Append("&province=" + shipToState);
                }
                else
                {
                    requestBody.Append("&state=" + shipToState);
                }
            }
            if (shipToPostalCode.Length > 0)
            {
                requestBody.Append("&zip=" + shipToPostalCode);
            }
            if (shipToCountry.Length > 0)
            {
                requestBody.Append("&country=" + shipToCountry);
            }
            if (shipInfo)
            {
                requestBody.Append("&shipinfo=1");
            }

            if (customerID.Length > 0)
            {
                requestBody.Append("&acct_code=" + customerID);
            }

            if (customerTaxID.Length > 0)
            {
                requestBody.Append("&acct_code2=" + customerTaxID);
            }

            requestBody.Append("&ipaddress=" + customerIPAddress);

            if (sendCustomerEmailConfirmation)
            {
                requestBody.Append("&email=" + cardBillingEmail);//pnp the merchant sets the email template in pnp admin area
            }
            else
            {
                requestBody.Append("&dontsndmail=yes");//pnp Do Not Send Email
            }

            if (merchantEmail.Length > 0)
            {
                requestBody.Append("&publisher-email=" + merchantEmail);
            }

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&order-id=" + merchantInvoiceNumber);//Not to be confused with orderID which must be unique and numeric
            }
            if (merchantTransactionDescription.Length > 0)
            {
                requestBody.Append(merchantTransactionDescription); //This may not be what the property is for but PNP allows you to have all the cart items passed to be used in their "easycart"
                requestBody.Append("&easycart=1");
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&currency=" + currencyCode);
            }

            if (useTestMode)
            {
                // Plug.N.Pay defines testmode by the account used to access it, there is no test server all transactions are performed on the live server
            }

            //requestBody.Append("&x_version=3.1");

            String url;

            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method      = "POST";
            webRequest.Timeout     = timeoutInMilliseconds;
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //string payload =  HttpUtility.UrlEncode(requestBody.ToString());
            //byte[] somebytes = Encoding.UTF8.GetBytes(payload);
            //webRequest.ContentLength = somebytes.Length;
            webRequest.ContentLength = requestBody.Length;


            //try
            //{
            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
            {
                requestStream.Write(requestBody.ToString());
            }

            //}
            //catch (Exception e)
            //{
            //    lastExecutionException = e;
            //    result = false;
            //}
            //finally
            //{
            if (requestStream != null)
            {
                requestStream.Close();
            }
            //}

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                           new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result      = true;
                }

                ParseResponse();
            }
            else
            {
                // TODO: error message?
                response = PaymentGatewayResponse.Error;
                return(false);
            }



            return(result);
        }
コード例 #29
0
 public bool ExecuteTransaction()
 {
     response = PaymentGatewayResponse.NoRequestInitiated;
     return(false);
 }
コード例 #30
0
 public void AddPaymentGatewayResponse(PaymentGatewayResponse paymentGatewayResponse)
 {
     context.Add(paymentGatewayResponse);
     int suc = context.SaveChanges();
 }
コード例 #31
0
        private void ParseResponse()
        {
            if (rawResponse.Length > 0)
            {
                //PARSE THE RESPONSE FROM PNP
                dictionaryResponseDecode(rawResponse);

                if (_ResponseDictionary.ContainsKey("FinalStatus"))
                {
                    if (_ResponseDictionary["FinalStatus"].ToString() == "success")
                    {
                        response = PaymentGatewayResponse.Approved;
                    }
                    else
                    {
                        response = PaymentGatewayResponse.Declined;
                    }
                }
                else
                {
                    response = PaymentGatewayResponse.Error;
                }

                try
                {
                    reasonCode = _ResponseDictionary["FinalStatus"].ToString();
                }
                catch { }

                try
                {
                    responseReason = _ResponseDictionary["MerrMsg"].ToString();
                }
                catch { }

                try
                {
                    approvalCode = _ResponseDictionary["auth-code"].ToString();
                }
                catch { }
                try
                {
                    avsResultCode = _ResponseDictionary["avs-code"].ToString();
                }
                catch { }

                if (AVSResultTextLookup.Contains(avsResultCode))
                {
                    avsResultText = (string)AVSResultTextLookup[avsResultCode];
                }

                try
                {
                    cardSecurityCodeResponseCode = _ResponseDictionary["cvvresp"].ToString();
                }
                catch { }

                transactionID = _ResponseDictionary["orderID"].ToString(); // not to be confused with order-id which we sent to the gateway

            }
        }
コード例 #32
0
        public CreditCardServiceResponse PayEstimate(CreditCardViewModel cardProfile, Func<string, string> urlBuilder, IARequest request, IARequestEstimate estimate)
        {
            var response = new CreditCardServiceResponse {SuccessfulCharge = true};

             var transaction = new AuthorizeNETTransactionInformation(cardProfile.CreditCardNumber, estimate.Charge, cardProfile.ExpirationDate)
             {
            FirstName = cardProfile.FirstName,
            LastName = cardProfile.LastName,
            CreditCardCode = cardProfile.CardVerificationCode,
            Email = cardProfile.ReceiptEmailAddressCsv,
            InvoiceNumber = string.Format("Est-{0}", request.RequestIdForDisplay),
            Description = "Request Estimate",
            Company = cardProfile.CompanyName.PadRight(50).Substring(0, 50).Trim(),
            Zip = ""
             };

             var paymentGatewayResponse = new PaymentGatewayResponse(string.Empty);

             if (cardProfile.CreditCardId == 0)
             {
            var authorizeNetDirect = new AuthorizeNET(_enableDebug, _loginId, _transactionKey);

            if (!authorizeNetDirect.ProcessAuthorizationAndCapture(transaction))
            {
               response.SuccessfulCharge = false;
               response.ErrorMessage = authorizeNetDirect.Error;
            }

            response.PaymentGatewayResponse = authorizeNetDirect.PaymentGatewayResponse;
             }
             else
             {
            // go through CIM to process transaction
            paymentGatewayResponse = CIMAuthorizationAndCapture(transaction,
                                                                cardProfile.CIMProfileId,
                                                                cardProfile.CIMPaymentProfileId);
            if (paymentGatewayResponse.Errors.Any() || paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode) != "1")
            {
               var message = paymentGatewayResponse.Errors.Any()
                                ? paymentGatewayResponse.Errors.Aggregate((messages, error) => messages + ", " + error)
                                : paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.ResponseReasonText);

               response.SuccessfulCharge = false;
               response.ErrorMessage = message;
            }
             }

             if (!response.SuccessfulCharge) return response;

             RecordOrder(cardProfile, paymentGatewayResponse, estimate);

             var requestStatusLookup = new RequestStatusLookup(_dataContext);
             request.IARequestStatusID = requestStatusLookup.GetRequestStatus(RequestStatus.Processing).IARequestStatusID;
             _dataContext.SubmitChanges();

             var approved = DateTime.Now;
             MarkEstimateAsPaid(request, estimate, approved);

             SendCustomerReceipt(cardProfile, request, estimate);

             InformBillingThatCustomerPaid(cardProfile, paymentGatewayResponse, urlBuilder, request, approved, estimate.Charge);

             return response;
        }
コード例 #33
0
        private void ParseSetExpressCheckoutResponse()
        {
            if (rawResponse.Length > 0)
            {
                char[] pairSeparator = { '&' };
                char[] keyValSeparator = { '=' };
                string[] keyValPairs = rawResponse.Split(pairSeparator, StringSplitOptions.None);

                StringDictionary responseResults = new StringDictionary();

                foreach (string keyVal in keyValPairs)
                {
                    string[] pair = keyVal.Split(keyValSeparator, StringSplitOptions.None);
                    if (pair.Length >= 2)
                    {
                        responseResults.Add(pair[0], pair[1]);
                    }
                }

                if (responseResults.ContainsKey("ACK"))
                {
                    switch (responseResults["ACK"])
                    {
                        case "Success":
                        case "SuccessWithWarning":
                            response = PaymentGatewayResponse.Approved;
                            break;

                        case "2":
                            response = PaymentGatewayResponse.Declined;
                            break;

                        case "Warning":
                        case "Failure":
                        case "FailureWithWarning":
                        case "Error":

                            response = PaymentGatewayResponse.Error;

                            if (responseResults.ContainsKey("L_LONGMESSAGE0"))
                            {
                                responseReason = HttpUtility.UrlDecode(responseResults["L_LONGMESSAGE0"]);
                            }

                            if (responseResults.ContainsKey("L_ERRORCODE0"))
                            {
                                reasonCode = HttpUtility.UrlDecode(responseResults["L_ERRORCODE0"]);

                            }

                            break;
                    }

                }

                //TOKEN A timestamped token by which you identify to PayPal that you are processing this
                //payment with Express Checkout.
                //NOTE: The token expires after three hours.
                //If you set the token in the SetExpressCheckout request, the value of the token in the
                //response is identical to the value in the request.
                //Character length and limitations: 20 single-byte characters
                if (responseResults.ContainsKey("TOKEN"))
                {
                    payPalToken = HttpUtility.UrlDecode(responseResults["TOKEN"]);

                    if (useTestMode)
                    {
                        payPalExpressUrl = payPalExpressSandboxCheckoutUrl + HttpUtility.UrlEncode(payPalToken);
                    }
                    else
                    {
                        payPalExpressUrl = payPalExpressProductionCheckoutUrl + HttpUtility.UrlEncode(payPalToken);
                    }

                }

            }
        }
コード例 #34
0
        public bool ExecuteTransaction()
        {
            bool          result      = false;
            StringBuilder requestBody = new StringBuilder();

            requestBody.Append("x_login="******"&x_tran_key=" + merchantAPITransactionKey);
            requestBody.Append("&x_method=CC");

            switch (transactionType)
            {
            case PaymentGatewayTransactionType.AuthCapture:
                requestBody.Append("&x_type=AUTH_CAPTURE");
                break;

            case PaymentGatewayTransactionType.AuthOnly:
                requestBody.Append("&x_type=AUTH_ONLY");
                break;

            case PaymentGatewayTransactionType.CaptureOnly:
                requestBody.Append("&x_type=CAPTURE_ONLY");
                break;

            case PaymentGatewayTransactionType.Credit:
                requestBody.Append("&x_type=CREDIT");
                break;

            case PaymentGatewayTransactionType.PriorAuthCapture:
                requestBody.Append("&x_type=PRIOR_AUTH_CAPTURE");
                break;

            case PaymentGatewayTransactionType.Void:
                requestBody.Append("&x_type=VOID");
                break;
            }

            requestBody.Append("&x_amount=" + FormatCharge());
            requestBody.Append("&x_delim_data=TRUE");
            requestBody.Append("&x_delim_char=|");
            requestBody.Append("&x_relay_response=FALSE");

            requestBody.Append("&x_card_num=" + cardNumber);
            requestBody.Append("&x_exp_date=" + cardExpiration);

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&x_card_code=" + cardSecurityCode);
            }

            if (authenticationIndicator.Length > 0)
            {
                requestBody.Append("&x_authentication_indicator=" + authenticationIndicator);
            }

            if (cardholderAuthenticationValue.Length > 0)
            {
                requestBody.Append("&x_cardholder_authentication_value=" + cardholderAuthenticationValue);
            }

            if (previousTransactionID.Length > 0)
            {
                requestBody.Append("&x_trans_id=" + previousTransactionID);
            }

            if (previousApprovalCode.Length > 0)
            {
                requestBody.Append("&x_auth_code=" + previousApprovalCode);
            }

            requestBody.Append("&x_first_name=" + cardOwnerFirstName);
            requestBody.Append("&x_last_name=" + cardOwnerLastName);
            requestBody.Append("&x_company=" + cardOwnerCompanyName);
            requestBody.Append("&x_address=" + cardBillingAddress);
            requestBody.Append("&x_city=" + cardBillingCity);
            requestBody.Append("&x_state=" + cardBillingState);
            requestBody.Append("&x_zip=" + cardBillingPostalCode);
            requestBody.Append("&x_country=" + cardBillingCountry);
            requestBody.Append("&x_phone=" + cardBillingPhone);

            if (shipToFirstName.Length > 0)
            {
                requestBody.Append("&x_ship_to_first_name=" + shipToFirstName);
            }
            if (shipToLastName.Length > 0)
            {
                requestBody.Append("&x_ship_to_last_name=" + shipToLastName);
            }
            if (shipToCompanyName.Length > 0)
            {
                requestBody.Append("&x_ship_to_company=" + shipToCompanyName);
            }
            if (shipToAddress.Length > 0)
            {
                requestBody.Append("&x_ship_to_address=" + shipToAddress);
            }
            if (shipToCity.Length > 0)
            {
                requestBody.Append("&x_ship_to_city=" + shipToCity);
            }
            if (shipToState.Length > 0)
            {
                requestBody.Append("&x_ship_to_state=" + shipToState);
            }
            if (shipToPostalCode.Length > 0)
            {
                requestBody.Append("&x_ship_to_zip=" + shipToPostalCode);
            }
            if (shipToCountry.Length > 0)
            {
                requestBody.Append("&x_ship_to_country=" + shipToCountry);
            }

            if (customerID.Length > 0)
            {
                requestBody.Append("&x_cust_id=" + customerID);
            }

            if (customerTaxID.Length > 0)
            {
                requestBody.Append("&x_customer_tax_id=" + customerTaxID);
            }

            requestBody.Append("&x_customer_ip=" + customerIPAddress);

            if (sendCustomerEmailConfirmation)
            {
                requestBody.Append("&x_email_customer=TRUE");
                requestBody.Append("&x_email=" + cardBillingEmail);
                if (merchantEmailConfirmationHeader.Length > 0)
                {
                    requestBody.Append("&x_header_email_receipt=" + merchantEmailConfirmationHeader);
                }
                if (merchantEmailConfirmationFooter.Length > 0)
                {
                    requestBody.Append("&x_footer_email_receipt=" + merchantEmailConfirmationFooter);
                }
            }

            if (merchantEmail.Length > 0)
            {
                requestBody.Append("&x_merchant_email=" + merchantEmail);
            }

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&x_invoice_num=" + merchantInvoiceNumber);
            }

            if (merchantTransactionDescription.Length > 0)
            {
                requestBody.Append("&x_description=" + merchantTransactionDescription);
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&x_currency_code=" + currencyCode);
            }

            if (useTestMode)
            {
                // authorize.net supports test requests
                // this is supported on both production and test servers
                // I'm commenting this out because I want to test on test server as if it were production
                // so I don't want to pass this
                //requestBody.Append("&x_test_request=TRUE");
            }

            requestBody.Append("&x_version=3.1");

            String url;

            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method      = "POST";
            webRequest.Timeout     = timeoutInMilliseconds;
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //string payload =  HttpUtility.UrlEncode(requestBody.ToString());
            //byte[] somebytes = Encoding.UTF8.GetBytes(payload);
            //webRequest.ContentLength = somebytes.Length;
            webRequest.ContentLength = requestBody.Length;


            //try
            //{
            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
            {
                requestStream.Write(requestBody.ToString());
            }

            //}
            //catch (Exception e)
            //{
            //    lastExecutionException = e;
            //    result = false;
            //}
            //finally
            //{
            if (requestStream != null)
            {
                requestStream.Close();
            }
            //}

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                           new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    responseStream.Close();
                    result = true;
                }

                ParseResponse();
            }
            else
            {
                // TODO: error message?
                response = PaymentGatewayResponse.Error;
                return(false);
            }



            return(result);
        }
コード例 #35
0
        private void InformBillingThatCustomerPaid(CreditCardViewModel paymentDetails, PaymentGatewayResponse paymentGatewayResponse,
                                                 Func<string, string> urlBuilder,
                                                 IARequest request, DateTime approved, decimal chargeAmount)
        {
            string subject;
             string customerType;

             var mpOrg = _dataContext.MPOrgUsers.FirstOrDefault(row => row.MPUserID == _customerMemberProtectUserId);
             var mpOrgId = mpOrg == null ? Guid.Empty : mpOrg.MPOrgID;

             if (_memberProtect.Utility.YesNoToBool(_memberProtect.Organization.GetDataItem(mpOrgId, "IsVerified")))
             {
            subject = "Estimate Payment made (verified)";
            customerType = "a verified";
             }
             else
             {
            subject = "Estimate Payment made (unverified)";
            customerType = "an unverified";
             }

             var paidEmail = new StringBuilder();
             paidEmail.AppendFormat("An estimate payment was made by {0} customer:<br/>", customerType);
             paidEmail.Append("<br/>");
             paidEmail.AppendFormat("Company: <a href='{0}?id={1}'>{2}</a><br/>", urlBuilder("company-modify.aspx"),
                                mpOrgId.ToString().Replace("-", string.Empty), _memberProtect.Organization.GetName(mpOrgId));
             paidEmail.AppendFormat("Customer: <a href='{0}?id={1}'>{2} {3}</a><br/>", urlBuilder("user-account.aspx"),
                                _customerMemberProtectUserId.ToString().Replace("-", string.Empty),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "FirstName"),
                                _memberProtect.User.GetDataItem(_customerMemberProtectUserId, "LastName"));
             paidEmail.AppendFormat("Email Receipt: {0}<br/>", paymentDetails.ReceiptEmailAddressCsv);
             paidEmail.AppendFormat("Request: <a href='{0}?rid={1}'>{2}</a><br/>", urlBuilder("create-job.aspx"), request.IARequestID, request.RequestIdForDisplay);
             paidEmail.AppendFormat("Amount: {0:c}<br/>", chargeAmount);
             paidEmail.AppendFormat("Card: {0} ending in {1}<br/>", paymentDetails.CardType, _memberProtect.Utility.Right(paymentDetails.CreditCardNumber, 4));
             paidEmail.AppendFormat("Name on Card: {0} {1}<br/>", paymentDetails.FirstName, paymentDetails.LastName);
             paidEmail.AppendFormat("When: {0:g}<br/>", approved);
             paidEmail.AppendFormat("Authorize Receipt: {0}<br/>", paymentGatewayResponse.GetValue(PaymentGatewayResponse.FieldNames.TransactionId));

             EmailCommunicationService.EstimatePaymentBillingNoticeSend(paidEmail, subject);
        }
コード例 #36
0
        public bool ExecuteTransaction()
        {
            bool result = false;
            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("publisher-name=" + merchantAPILogin);
            requestBody.Append("&publisher-password="******"&paymethod=credit");
            credentials = String.Format("publisher-name={0}&publisher-password={1}", merchantAPILogin, merchantAPITransactionKey);

            switch (transactionType)
            {
                case PaymentGatewayTransactionType.AuthCapture:
                    requestBody.Append("&mode=auth");
                    requestBody.Append("&authtype=authpostauth");//pnp Batches everything this autmatically marks transactions for settlement... useless if merchant uses automatic batches
                    break;

                case PaymentGatewayTransactionType.AuthOnly:
                    requestBody.Append("&mode=auth");
                    requestBody.Append("&authtype=authonly");//defaults to authonly, filled in for clarity
                    break;

                case PaymentGatewayTransactionType.CaptureOnly:
                    requestBody.Append("&mode=auth");
                    requestBody.Append("&authtype=authpostauth");//AFAIK they don't do this, with maybe the exception of Mercury Gift cards... which are catured realtime
                    break;

                case PaymentGatewayTransactionType.Credit:
                    requestBody.Append("&mode=newreturn");//mode becomes newreturn
                    break;

                case PaymentGatewayTransactionType.PriorAuthCapture:
                    requestBody.Append("&authtype=authprev");//don't know the translation here between anet and pnp assUme force-auth or authprev
                    break;

                case PaymentGatewayTransactionType.Void:
                    requestBody.Append("&mode=void");
                    requestBody.Append("&txn-type=auth");
                    break;

            }

            requestBody.Append("&card-amount=" + FormatCharge());
            //requestBody.Append("&x_delim_data=TRUE");
            //requestBody.Append("&x_delim_char=|");
            //requestBody.Append("&x_relay_response=FALSE");

            requestBody.Append("&card-number=" + cardNumber);
            requestBody.Append("&card-exp=" + cardExpiration);

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&card-cvv=" + cardSecurityCode);
            }

            //if (authenticationIndicator.Length > 0)
            //{
            //    requestBody.Append("&x_authentication_indicator=" + authenticationIndicator);
            //}

            //if (cardholderAuthenticationValue.Length > 0)
            //{
            //   requestBody.Append("&x_cardholder_authentication_value=" + cardholderAuthenticationValue);
            //}

            if (previousTransactionID.Length > 0)
            {
                requestBody.Append("&prevorderid=" + previousTransactionID);
            }

            // if (previousApprovalCode.Length > 0)
            //{
            // requestBody.Append("&x_auth_code=" + previousApprovalCode);
            // }

            //requestBody.Append("&x_first_name=" + cardOwnerFirstName);
            //requestBody.Append("&x_last_name=" + cardOwnerLastName);
            requestBody.Append("&card-name=" + cardOwnerFirstName + " " + cardOwnerLastName);//This could be bad, should try to figure out how to have "Name as it appears on you cc"
            //requestBody.Append("&x_company=" + cardOwnerCompanyName);
            requestBody.Append("&card-address1=" + cardBillingAddress);
            requestBody.Append("&card-city=" + cardBillingCity);
            if ((cardBillingCountry != "US") && (cardBillingCountry != "CA"))
            {
                requestBody.Append("&card-state=ZZ");
                requestBody.Append("&card-prov=" + cardBillingState);
            }
            else
                requestBody.Append("&card-state=" + cardBillingState);
            requestBody.Append("&card-zip=" + cardBillingPostalCode);
            requestBody.Append("&card-country=" + cardBillingCountry);
            requestBody.Append("&phone=" + cardBillingPhone);
            bool shipInfo = false;

            if (shipToFirstName.Length > 0)
            {
                requestBody.Append("&shipname=" + shipToFirstName);
            }
            if (shipToLastName.Length > 0)
            {
                requestBody.Append(" " + shipToLastName);
            }
            //            if (shipToCompanyName.Length > 0)
            //            {
            //                requestBody.Append("&x_ship_to_company=" + shipToCompanyName);
            //            }
            if (shipToAddress.Length > 0)
            {
                requestBody.Append("&shipaddress1=" + shipToAddress);
            }
            if (shipToCity.Length > 0)
            {
                requestBody.Append("&city=" + shipToCity);
            }
            if (shipToState.Length > 0)
            {
                if ((shipToCountry != "US") && (shipToCountry != "CA"))
                {
                    requestBody.Append("&state=ZZ");
                    requestBody.Append("&province=" + shipToState);
                }
                else
                    requestBody.Append("&state=" + shipToState);
            }
            if (shipToPostalCode.Length > 0)
            {
                requestBody.Append("&zip=" + shipToPostalCode);
            }
            if (shipToCountry.Length > 0)
            {
                requestBody.Append("&country=" + shipToCountry);
            }
            if (shipInfo)
                requestBody.Append("&shipinfo=1");

            if (customerID.Length > 0)
            {
                requestBody.Append("&acct_code=" + customerID);
            }

            if (customerTaxID.Length > 0)
            {
                requestBody.Append("&acct_code2=" + customerTaxID);
            }

            requestBody.Append("&ipaddress=" + customerIPAddress);

            if (sendCustomerEmailConfirmation)
            {
                requestBody.Append("&email=" + cardBillingEmail);//pnp the merchant sets the email template in pnp admin area
            }
            else
            {
                requestBody.Append("&dontsndmail=yes");//pnp Do Not Send Email
            }

            if (merchantEmail.Length > 0)
            {
                requestBody.Append("&publisher-email=" + merchantEmail);
            }

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&order-id=" + merchantInvoiceNumber);//Not to be confused with orderID which must be unique and numeric
            }
            if (merchantTransactionDescription.Length > 0)
            {
                 requestBody.Append(merchantTransactionDescription);//This may not be what the property is for but PNP allows you to have all the cart items passed to be used in their "easycart"
                 requestBody.Append("&easycart=1");
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&currency=" + currencyCode);
            }

            if (useTestMode)
            {
                // Plug.N.Pay defines testmode by the account used to access it, there is no test server all transactions are performed on the live server
            }

            //requestBody.Append("&x_version=3.1");

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.Timeout = timeoutInMilliseconds;
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //string payload =  HttpUtility.UrlEncode(requestBody.ToString());
            //byte[] somebytes = Encoding.UTF8.GetBytes(payload);
            //webRequest.ContentLength = somebytes.Length;
            webRequest.ContentLength = requestBody.Length;

            //try
            //{
            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
                requestStream.Write(requestBody.ToString());

            //}
            //catch (Exception e)
            //{
            //    lastExecutionException = e;
            //    result = false;
            //}
            //finally
            //{
            if (requestStream != null)
                requestStream.Close();
            //}

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseResponse();

            }
            else
            {
                // TODO: error message?
                response = PaymentGatewayResponse.Error;
                return false;
            }

            return result;
        }
コード例 #37
0
        private void RecordOrder(CreditCardViewModel paymentDetails, PaymentGatewayResponse response, IARequestEstimate estimate)
        {
            var iaOrder = new IAOrder
             {
            MPUserID = _customerMemberProtectUserId,
            CreditCardType = _memberProtect.Cryptography.Encrypt(paymentDetails.CardType),
            CreditCardNumber = _memberProtect.Cryptography.Encrypt(paymentDetails.CreditCardNumber),
            CreditCardExpirationMonth = _memberProtect.Cryptography.Encrypt(paymentDetails.ExpirationMonth),
            CreditCardExpirationYear = _memberProtect.Cryptography.Encrypt(paymentDetails.ExpirationYear),
            CreditCardFirstName = _memberProtect.Cryptography.Encrypt(paymentDetails.FirstName),
            CreditCardLastName = _memberProtect.Cryptography.Encrypt(paymentDetails.LastName),
            CreditCardZip = "",
            AuthorizeNetResponse = string.Empty,
            AuthorizeNetTransactionID = response.GetValue(PaymentGatewayResponse.FieldNames.TransactionId),
            AuthorizeNetProcessDatetime = DateTime.Now,
            AuthorizeNetProcessResponse = response.GetValue(PaymentGatewayResponse.FieldNames.ResponseCode),
            AuthorizeNetProcessUsername = _dataContext.MPUsers.First(u => u.MPUserID == _customerMemberProtectUserId).Username,
            AuthorizeNetProcessCaptureAmount = estimate.Charge,
            AuthorizeNetProcessCaptureAmountChangeReason = string.Empty,
            AuthorizeNetProcessStatus = "Captured",
            CreatedDateTime = DateTime.Now
             };
             _dataContext.IAOrders.InsertOnSubmit(iaOrder);
             _dataContext.SubmitChanges();

             var iaOrderLineItem = new IAOrderLineItem
             {
            IAOrderID = iaOrder.IAOrderID,
            Description = "Request Estimate",
            Quantity = 1,
            Price = estimate.Charge,
            IsSynched = false
             };
             _dataContext.IAOrderLineItems.InsertOnSubmit(iaOrderLineItem);

             estimate.IAOrderID = iaOrder.IAOrderID;
             _dataContext.SubmitChanges();
        }
コード例 #38
0
        public bool ExecuteTransaction()
        {
            bool result = false;
            StringBuilder requestBody = new StringBuilder();
            requestBody.Append("x_login="******"&x_tran_key=" + merchantAPITransactionKey);
            requestBody.Append("&x_method=CC");

            switch (transactionType)
            {
                case PaymentGatewayTransactionType.AuthCapture:
                    requestBody.Append("&x_type=AUTH_CAPTURE");
                    break;

                case PaymentGatewayTransactionType.AuthOnly:
                    requestBody.Append("&x_type=AUTH_ONLY");
                    break;

                case PaymentGatewayTransactionType.CaptureOnly:
                    requestBody.Append("&x_type=CAPTURE_ONLY");
                    break;

                case PaymentGatewayTransactionType.Credit:
                    requestBody.Append("&x_type=CREDIT");
                    break;

                case PaymentGatewayTransactionType.PriorAuthCapture:
                    requestBody.Append("&x_type=PRIOR_AUTH_CAPTURE");
                    break;

                case PaymentGatewayTransactionType.Void:
                    requestBody.Append("&x_type=VOID");
                    break;

            }

            requestBody.Append("&x_amount=" + FormatCharge());
            requestBody.Append("&x_delim_data=TRUE");
            requestBody.Append("&x_delim_char=|");
            requestBody.Append("&x_relay_response=FALSE");

            requestBody.Append("&x_card_num=" + cardNumber);
            requestBody.Append("&x_exp_date=" + cardExpiration);

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&x_card_code=" + cardSecurityCode);
            }

            if (authenticationIndicator.Length > 0)
            {
                requestBody.Append("&x_authentication_indicator=" + authenticationIndicator);
            }

            if (cardholderAuthenticationValue.Length > 0)
            {
                requestBody.Append("&x_cardholder_authentication_value=" + cardholderAuthenticationValue);
            }

            if (previousTransactionID.Length > 0)
            {
                requestBody.Append("&x_trans_id=" + previousTransactionID);
            }

            if (previousApprovalCode.Length > 0)
            {
                requestBody.Append("&x_auth_code=" + previousApprovalCode);
            }

            requestBody.Append("&x_first_name=" + cardOwnerFirstName);
            requestBody.Append("&x_last_name=" + cardOwnerLastName);
            requestBody.Append("&x_company=" + cardOwnerCompanyName);
            requestBody.Append("&x_address=" + cardBillingAddress);
            requestBody.Append("&x_city=" + cardBillingCity);
            requestBody.Append("&x_state=" + cardBillingState);
            requestBody.Append("&x_zip=" + cardBillingPostalCode);
            requestBody.Append("&x_country=" + cardBillingCountry);
            requestBody.Append("&x_phone=" + cardBillingPhone);

            if (shipToFirstName.Length > 0)
                requestBody.Append("&x_ship_to_first_name=" + shipToFirstName);
            if (shipToLastName.Length > 0)
                requestBody.Append("&x_ship_to_last_name=" + shipToLastName);
            if (shipToCompanyName.Length > 0)
                requestBody.Append("&x_ship_to_company=" + shipToCompanyName);
            if (shipToAddress.Length > 0)
                requestBody.Append("&x_ship_to_address=" + shipToAddress);
            if (shipToCity.Length > 0)
                requestBody.Append("&x_ship_to_city=" + shipToCity);
            if (shipToState.Length > 0)
                requestBody.Append("&x_ship_to_state=" + shipToState);
            if (shipToPostalCode.Length > 0)
                requestBody.Append("&x_ship_to_zip=" + shipToPostalCode);
            if (shipToCountry.Length > 0)
                requestBody.Append("&x_ship_to_country=" + shipToCountry);

            if (customerID.Length > 0)
            {
                requestBody.Append("&x_cust_id=" + customerID);
            }

            if (customerTaxID.Length > 0)
            {
                requestBody.Append("&x_customer_tax_id=" + customerTaxID);
            }

            requestBody.Append("&x_customer_ip=" + customerIPAddress);

            if (sendCustomerEmailConfirmation)
            {
                requestBody.Append("&x_email_customer=TRUE");
                requestBody.Append("&x_email=" + cardBillingEmail);
                if (merchantEmailConfirmationHeader.Length > 0)
                {
                    requestBody.Append("&x_header_email_receipt=" + merchantEmailConfirmationHeader);
                }
                if (merchantEmailConfirmationFooter.Length > 0)
                {
                    requestBody.Append("&x_footer_email_receipt=" + merchantEmailConfirmationFooter);
                }
            }

            if (merchantEmail.Length > 0)
            {
                requestBody.Append("&x_merchant_email=" + merchantEmail);
            }

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&x_invoice_num=" + merchantInvoiceNumber);
            }

            if (merchantTransactionDescription.Length > 0)
            {
                requestBody.Append("&x_description=" + merchantTransactionDescription);
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&x_currency_code=" + currencyCode);
            }

            if (useTestMode)
            {
                // authorize.net supports test requests
                // this is supported on both production and test servers
                // I'm commenting this out because I want to test on test server as if it were production
                // so I don't want to pass this
                //requestBody.Append("&x_test_request=TRUE");
            }

            requestBody.Append("&x_version=3.1");

            String url;
            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "POST";
            webRequest.Timeout = timeoutInMilliseconds;
            webRequest.ContentType = "application/x-www-form-urlencoded";

            //string payload =  HttpUtility.UrlEncode(requestBody.ToString());
            //byte[] somebytes = Encoding.UTF8.GetBytes(payload);
            //webRequest.ContentLength = somebytes.Length;
            webRequest.ContentLength = requestBody.Length;

            //try
            //{
            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
                requestStream.Write(requestBody.ToString());

            //}
            //catch (Exception e)
            //{
            //    lastExecutionException = e;
            //    result = false;
            //}
            //finally
            //{
            if (requestStream != null)
                requestStream.Close();
            //}

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                   new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result = true;
                }

                ParseResponse();
            }
            else
            {
                // TODO: error message?
                response = PaymentGatewayResponse.Error;
                return false;
            }

            return result;
        }
コード例 #39
0
        public async Task Create_Get_Delete_Customer_Profile_With_eCheck_Business_Checking_Successfully_Test()
        {
            // Arrange
            var client            = _sp.GetRequiredService <ICustomerProfileClient>();
            var paymentClient     = _sp.GetRequiredService <ICustomerPaymentProfileClient>();
            var transactionClient = _sp.GetRequiredService <ITransactionClient>();
            var options           = _sp.GetRequiredService <IOptions <AuthorizeNetOptions> >();

            var randomAccountNumber = new Random().Next(10000, int.MaxValue);

            // 1. Act create eCheck Customer/Payment profile
            var eCheckPaymentProfiles = new Collection <CustomerPaymentProfileType>
            {
                // e-check business checking
                new CustomerPaymentProfileType
                {
                    CustomerType = CustomerTypeEnum.Business,
                    Payment      = new PaymentType
                    {
                        BankAccount = new BankAccountType
                        {
                            BankName      = "Bank of China",
                            AccountType   = BankAccountTypeEnum.BusinessChecking,
                            RoutingNumber = "125008547",
                            AccountNumber = randomAccountNumber.ToString(),
                            NameOnAccount = "Joseph Stalin(Biden)",     // .Substring(0, 22),
                            EcheckType    = EcheckTypeEnum.CCD
                        },
                    }
                },

                new CustomerPaymentProfileType
                {
                    CustomerType = CustomerTypeEnum.Business,
                    Payment      = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardNumber     = "2223000010309703",
                            ExpirationDate = "2024-12",
                            CardCode       = "900"
                        }
                    },

                    // visa requires to have the address
                    BillTo = new CustomerAddressType
                    {
                        Address = "1600 Pennsylvania Avenue NW",
                        City    = "Washington",
                        State   = "DC",
                        Zip     = "20500"
                    },
                }
            };

            // 1a. create request
            var createProfileRequest = new CreateCustomerProfileRequest
            {
                Profile = new CustomerProfileType
                {
                    Description = "eCheck Business Checking Customer",
                    Email       = "*****@*****.**",

                    // id within e-commerce site for the customer
                    MerchantCustomerId = "echeck-id-2",
                    ProfileType        = CustomerProfileTypeEnum.Regular,
                    PaymentProfiles    = eCheckPaymentProfiles,
                },

                ValidationMode = options.Value.ValidationMode
            };

            var createResponse = await client.CreateAsync(createProfileRequest);

            var code = createResponse.Messages.Message[0].Code;
            var text = createResponse.Messages.Message[0].Text;

            Assert.Equal("I00001", code);
            Assert.Equal("Successful.", text);
            var createResult = new PaymentGatewayResponse(createResponse.ValidationDirectResponseList[0]);

            Assert.Equal(MessageTypeEnum.Ok, createResponse.Messages.ResultCode);
            Assert.Equal(ResponseCodeEnum.Approved, createResult.ResponseCode);
            Assert.Equal("This transaction has been approved.", createResult.ResponseReasonCode);

            // delay for the time to process the record
            await Task.Delay(TimeSpan.FromSeconds(10));

            // 2. Act get an Customer/Payment profile
            var getUpdatedProfileResponse = await client.GetAsync(new GetCustomerProfileRequest
            {
                Email = "*****@*****.**",
                UnmaskExpirationDate = true,
            });

            // 3. Act Charge Customer Payment profile
            // pay with e-check
            var paymentProfileId = getUpdatedProfileResponse
                                   .Profile
                                   .PaymentProfiles
                                   .FirstOrDefault(x => x.Payment.BankAccount.EcheckType == EcheckTypeEnum.CCD)?
                                   .CustomerPaymentProfileId;

            var chargeRequest = new CreateTransactionRequest
            {
                TransactionRequest = new TransactionRequestType
                {
                    Amount          = 15.05m,
                    TransactionType = Enum.GetName(typeof(TransactionTypeEnum), TransactionTypeEnum.AuthCaptureTransaction),
                    Profile         = new CustomerProfilePaymentType
                    {
                        CustomerProfileId = getUpdatedProfileResponse.Profile.CustomerProfileId,
                        PaymentProfile    = new PaymentProfile
                        {
                            // pay with e-check
                            PaymentProfileId = paymentProfileId
                        }
                    },

                    Customer = new CustomerDataType
                    {
                        Id = "profile-test-56789"
                    },
                    Order = new OrderType
                    {
                        InvoiceNumber = "eck-invoice-1"
                    },

                    CustomerIP = options.Value.IpAddress,
                }
            };

            var chargeResponse = await transactionClient.CreateAsync(chargeRequest);

            Assert.Equal(MessageTypeEnum.Ok, chargeResponse.Messages.ResultCode);
            Assert.Equal(ResponseCodeEnum.Approved, ResponseMapper.GetResponseCode(chargeResponse.TransactionResponse.ResponseCode));
            Assert.Equal("This transaction has been approved.", chargeResponse.TransactionResponse.Messages[0].Description);
            _output.WriteLine(chargeResponse.TransactionResponse.TransId);

            // 4. Act get an Update Customer Payment profile
            var deleteRequest = new DeleteCustomerProfileRequest
            {
                CustomerProfileId = createResponse.CustomerProfileId
            };

            var deleteResponse = await client.DeleteAsync(deleteRequest);

            Assert.Equal(MessageTypeEnum.Ok, deleteResponse.Messages.ResultCode);
        }
コード例 #40
0
        public bool ExecuteTransaction()
        {
            bool result = false;


            StringBuilder requestBody = new StringBuilder();

            requestBody.Append("USER="******"&PWD=" + HttpUtility.UrlEncode(merchantAPIPassword));
            requestBody.Append("&SIGNATURE=" + HttpUtility.UrlEncode(merchantAPITransactionKey));
            //if (merchantPayPalEmailAddress.Length > 0)
            //{
            //    requestBody.Append("&SUBJECT=" + HttpUtility.UrlEncode(merchantPayPalEmailAddress));
            //}
            requestBody.Append("&VERSION=" + HttpUtility.UrlEncode(apiVersion));

            requestBody.Append("&BUTTONSOURCE=SourceTreeSolutions_SP");


            switch (transactionType)
            {
            // default transaction type
            case PaymentGatewayTransactionType.AuthCapture:
                requestBody.Append("&METHOD=DoDirectPayment");
                requestBody.Append("&PAYMENTACTION=Sale");
                requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                break;

            case PaymentGatewayTransactionType.AuthOnly:
                requestBody.Append("&METHOD=DoDirectPayment");
                requestBody.Append("&PAYMENTACTION=Authorization");
                requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                break;

            case PaymentGatewayTransactionType.CaptureOnly:

                throw new NotSupportedException();

            case PaymentGatewayTransactionType.Credit:
                if (previousTransactionID.Length == 0)
                {
                    throw new NotSupportedException("Credit not supported without a previous transactionID");
                }

                requestBody.Append("&METHOD=RefundTransaction, ");
                requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                requestBody.Append("&REFUNDTYPE=Full");

                break;

            case PaymentGatewayTransactionType.PriorAuthCapture:

                if (previousTransactionID.Length == 0)
                {
                    throw new NotSupportedException("PriorAuthCapture not supported without a previous transactionID");
                }

                requestBody.Append("&METHOD=DoCapture");
                requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                requestBody.Append("&COMPLETETYPE=Complete");

                break;

            case PaymentGatewayTransactionType.Void:

                if (previousTransactionID.Length == 0)
                {
                    throw new NotSupportedException("Void not supported without a previous transactionID");
                }

                requestBody.Append("&METHOD=DoVoid");
                requestBody.Append("&TRANSACTIONID=" + HttpUtility.UrlEncode(previousTransactionID));
                requestBody.Append("&AMT=" + HttpUtility.UrlEncode(FormatCharge()));
                requestBody.Append("&COMPLETETYPE=Complete");

                break;
            }

            requestBody.Append("&CREDITCARDTYPE=" + HttpUtility.UrlEncode(cardType));
            requestBody.Append("&ACCT=" + HttpUtility.UrlEncode(cardNumber));
            requestBody.Append("&EXPDATE=" + HttpUtility.UrlEncode(cardExpiration));

            if (cardSecurityCode.Length > 0)
            {
                requestBody.Append("&CVV2=" + HttpUtility.UrlEncode(cardSecurityCode));
            }

            requestBody.Append("&FIRSTNAME=" + HttpUtility.UrlEncode(cardOwnerFirstName));
            requestBody.Append("&LASTNAME=" + HttpUtility.UrlEncode(cardOwnerLastName));
            requestBody.Append("&STREET=" + HttpUtility.UrlEncode(cardBillingAddress));
            requestBody.Append("&CITY=" + HttpUtility.UrlEncode(cardBillingCity));
            requestBody.Append("&STATE=" + HttpUtility.UrlEncode(cardBillingState));
            requestBody.Append("&ZIP=" + HttpUtility.UrlEncode(cardBillingPostalCode));
            requestBody.Append("&COUNTRYCODE=" + HttpUtility.UrlEncode(cardBillingCountryCode));
            requestBody.Append("&PHONENUM=" + HttpUtility.UrlEncode(cardBillingPhone));
            requestBody.Append("&IPADDRESS=" + HttpUtility.UrlEncode(customerIPAddress));

            if (merchantInvoiceNumber.Length > 0)
            {
                requestBody.Append("&INVNUM=" + HttpUtility.UrlEncode(merchantInvoiceNumber));
            }

            if (currencyCode.Length > 0)
            {
                requestBody.Append("&CURRENCYCODE=" + HttpUtility.UrlEncode(currencyCode));
            }

            String url;

            if (useTestMode)
            {
                url = testUrl;
            }
            else
            {
                url = productionUrl;
            }

            StreamWriter requestStream = null;

            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);

            webRequest.Method = "POST";

            webRequest.Timeout = timeoutInMilliseconds;

            webRequest.ContentType = "application/x-www-form-urlencoded";

            string encodedBody = requestBody.ToString();

            log.Debug(encodedBody);
            webRequest.ContentLength = encodedBody.Length;

            requestStream = new StreamWriter(webRequest.GetRequestStream());
            if (requestStream != null)
            {
                requestStream.Write(encodedBody);
            }

            if (requestStream != null)
            {
                requestStream.Close();
            }

            HttpWebResponse webResponse
                = (HttpWebResponse)webRequest.GetResponse();

            if (webResponse != null)
            {
                using (StreamReader responseStream =
                           new StreamReader(webResponse.GetResponseStream()))
                {
                    rawResponse = responseStream.ReadToEnd();
                    result      = true;
                }

                ParseResponse();
            }
            else
            {
                response = PaymentGatewayResponse.Error;
                return(false);
            }

            return(result);
        }
コード例 #41
0
        public async Task Fail_To_Create_Customer_Profile_With_Credit_Card_That_Expired_Test()
        {
            var client  = _sp.GetRequiredService <ICustomerProfileClient>();
            var options = _sp.GetRequiredService <IOptions <AuthorizeNetOptions> >();

            // customer payment profile
            var customerPaymentProfiles = new Collection <CustomerPaymentProfileType>
            {
                new CustomerPaymentProfileType
                {
                    CustomerType = CustomerTypeEnum.Business,
                    Payment      = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardNumber     = "4111111111111111",
                            ExpirationDate = "2020-12",
                            CardCode       = "900"
                        },
                    },
                }
            };

            // create request
            var createRequest = new CreateCustomerProfileRequest
            {
                Profile = new CustomerProfileType
                {
                    Description        = "Expired Test Customer Account",
                    Email              = "*****@*****.**",
                    MerchantCustomerId = "Expired-CustomerId-2",
                    ProfileType        = CustomerProfileTypeEnum.Regular,
                    PaymentProfiles    = customerPaymentProfiles,
                },

                ValidationMode = options.Value.ValidationMode
            };

            var createResponse = await client.CreateAsync(createRequest);

            Assert.Equal(MessageTypeEnum.Error, createResponse.Messages.ResultCode);

            var code = createResponse.Messages.Message[0].Code;
            var text = createResponse.Messages.Message[0].Text;

            Assert.Equal("E00027", code);
            Assert.Equal("The credit card has expired.", text);

            var createResult = new PaymentGatewayResponse(createResponse.ValidationDirectResponseList[0]);

            _output.WriteLine($"Account: [{createResult.AccountNumber}]; " +
                              $": [{createResult.ResponseCode}]");

            Assert.Equal("P", createResult.AVSResponseCode);
            Assert.Equal("auth_only", createResult.TransactionType);
            Assert.Equal("This transaction is an uknown state.", createResult.ResponseReasonCode);
            Assert.Equal("Visa", createResult.CardType);
            Assert.Equal(string.Empty, createResult.CardCodeResponse);
            Assert.Equal(string.Empty, createResult.AuthorizationCode);
            Assert.Equal(string.Empty, createResult.CardholderAuthenticationVerificationResponse);
            Assert.Equal(string.Empty, createResult.AuthorizationCode);
            Assert.Equal("CC", createResult.Method);
        }
コード例 #42
0
        public async Task Create_Get_Delete_Customer_Profile_With_Credit_Card_Successfully_Test()
        {
            // Arrange
            var client            = _sp.GetRequiredService <ICustomerProfileClient>();
            var paymentClient     = _sp.GetRequiredService <ICustomerPaymentProfileClient>();
            var transactionClient = _sp.GetRequiredService <ITransactionClient>();
            var options           = _sp.GetRequiredService <IOptions <AuthorizeNetOptions> >();

            // 1. Act create Customer/Payment profile
            var creditCardPaymentProfiles = new Collection <CustomerPaymentProfileType>
            {
                new CustomerPaymentProfileType
                {
                    CustomerType = CustomerTypeEnum.Business,
                    Payment      = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardNumber     = "4111111111111111",
                            ExpirationDate = "2024-12",
                            CardCode       = "900"
                        }
                    },

                    // visa requires to have the address
                    BillTo = new CustomerAddressType
                    {
                        Address = "1234 main st",
                        City    = "Washington",
                        State   = "DC",
                        Zip     = "46282"
                    },
                }
            };

            // 1a. create request
            var createProfileRequest = new CreateCustomerProfileRequest
            {
                Profile = new CustomerProfileType
                {
                    Description        = "Test Customer Account",
                    Email              = "*****@*****.**",
                    MerchantCustomerId = "CustomerId-2",
                    ProfileType        = CustomerProfileTypeEnum.Regular,
                    PaymentProfiles    = creditCardPaymentProfiles,
                },

                ValidationMode = options.Value.ValidationMode
            };

            var createResponse = await client.CreateAsync(createProfileRequest);

            // Code: E00039 Text: A duplicate record with ID 1517706258 already exists
            var code = createResponse.Messages.Message[0].Code;
            var text = createResponse.Messages.Message[0].Text;

            Assert.Equal("I00001", code);
            Assert.Equal("Successful.", text);

            var createResult = new PaymentGatewayResponse(createResponse.ValidationDirectResponseList[0]);

            Assert.Equal(MessageTypeEnum.Ok, createResponse.Messages.ResultCode);
            Assert.Equal(ResponseCodeEnum.Approved, createResult.ResponseCode);
            Assert.Equal("This transaction has been approved.", createResult.ResponseReasonCode);

            await Task.Delay(TimeSpan.FromSeconds(10));

            // 2. Act get Customer/Payment profiles by a customer email
            var getProfileResponse = await client.GetAsync(new GetCustomerProfileRequest
            {
                Email = "*****@*****.**",

                // CustomerProfileId = createResponse.CustomerProfileId,
                UnmaskExpirationDate = true,
            });

            Assert.Equal(MessageTypeEnum.Ok, getProfileResponse.Messages.ResultCode);
            _output.WriteLine($"{getProfileResponse.Profile.CustomerProfileId} - {getProfileResponse.Messages.ResultCode}");

            // 3. Act get Customer Payment profile with unmasked values prep for an update
            var getPaymentResponse = await paymentClient.GetAsync(new GetCustomerPaymentProfileRequest
            {
                CustomerPaymentProfileId = getProfileResponse.Profile.PaymentProfiles[0].CustomerPaymentProfileId,
                CustomerProfileId        = getProfileResponse.Profile.CustomerProfileId,
                UnmaskExpirationDate     = true
            });

            Assert.Equal(MessageTypeEnum.Ok, getPaymentResponse.Messages.ResultCode);

            // 4. Act update Customer Payment profile
            var exp = "2025-10";

            var updatePaymentRequest = new UpdateCustomerPaymentProfileRequest
            {
                ValidationMode = options.Value.ValidationMode,

                CustomerProfileId = getPaymentResponse.PaymentProfile.CustomerProfileId,
                PaymentProfile    = new CustomerPaymentProfileExType
                {
                    CustomerPaymentProfileId = getPaymentResponse.PaymentProfile.CustomerPaymentProfileId,
                    CustomerType             = CustomerTypeEnum.Individual,
                    Payment = new PaymentType
                    {
                        CreditCard = new CreditCardType
                        {
                            CardNumber     = getPaymentResponse.PaymentProfile.Payment.CreditCard.CardNumber,
                            ExpirationDate = exp,
                            CardCode       = "900"
                        }
                    }
                }
            };

            _output.WriteLine($"Old: {getPaymentResponse.PaymentProfile.Payment.CreditCard.ExpirationDate}; New:{exp}");

            var updatePaymentResponse = await paymentClient.UpdateAsync(updatePaymentRequest);

            var updatePaymentResult = new PaymentGatewayResponse(updatePaymentResponse.ValidationDirectResponse);

            Assert.Equal(MessageTypeEnum.Ok, updatePaymentResponse.Messages.ResultCode);
            Assert.Equal(ResponseCodeEnum.Approved, updatePaymentResult.ResponseCode);

            await Task.Delay(TimeSpan.FromSeconds(10));

            // 5. Act get an Update Customer Payment profile
            var getUpdatedProfileResponse = await client.GetAsync(new GetCustomerProfileRequest
            {
                Email = "*****@*****.**",
                UnmaskExpirationDate = true,
            });

            Assert.Equal(exp, getUpdatedProfileResponse.Profile.PaymentProfiles[0].Payment.CreditCard.ExpirationDate);

            // 5. Act Charge Customer Payment profile
            var chargeRequest = new CreateTransactionRequest
            {
                TransactionRequest = new TransactionRequestType
                {
                    Amount          = 5.05m,
                    TransactionType = Enum.GetName(typeof(TransactionTypeEnum), TransactionTypeEnum.AuthCaptureTransaction),
                    Profile         = new CustomerProfilePaymentType
                    {
                        CustomerProfileId = getUpdatedProfileResponse.Profile.CustomerProfileId,
                        PaymentProfile    = new PaymentProfile
                        {
                            PaymentProfileId = getUpdatedProfileResponse.Profile.PaymentProfiles[0].CustomerPaymentProfileId
                        }
                    },

                    Customer = new CustomerDataType
                    {
                        Id = "profile-test-56789"
                    },
                    Order = new OrderType
                    {
                        InvoiceNumber = "cp-invoice-123"
                    },

                    CustomerIP = options.Value.IpAddress,
                }
            };

            var chargeResponse = await transactionClient.CreateAsync(chargeRequest);

            Assert.Equal(MessageTypeEnum.Ok, chargeResponse.Messages.ResultCode);
            Assert.Equal("1", chargeResponse.TransactionResponse.ResponseCode);
            Assert.Equal("This transaction has been approved.", chargeResponse.TransactionResponse.Messages[0].Description);
            _output.WriteLine(chargeResponse.TransactionResponse.TransId);

            // 7. Act get an Update Customer Payment profile
            var deleteRequest = new DeleteCustomerProfileRequest
            {
                CustomerProfileId = createResponse.CustomerProfileId
            };

            var deleteResponse = await client.DeleteAsync(deleteRequest);

            Assert.Equal(MessageTypeEnum.Ok, deleteResponse.Messages.ResultCode);
        }
コード例 #43
0
        public async Task <ActionResult> Pay(CheckOutModels model, FormCollection collection)
        {
            var userId = User.Identity.GetUserId();

            //Credit Card
            var _totalAmount = Convert.ToDouble((from o in model.Cart
                                                 group o by new { product = o.Id, amount = o.Amount * o.Quantity } into g
                                                 select new
            {
                Total = g.Key.amount
            }).ToList().Sum(i => i.Total));



            var Billing = new AuthBillingAddress()
            {
                addrLine1   = model.BillingAddress.addressLine1,
                city        = model.BillingAddress.city,
                state       = model.BillingAddress.state,
                country     = model.BillingAddress.country,
                name        = model.BillingAddress.name,
                email       = User.Identity.GetUserName(),
                phoneNumber = "N/A",
                zipCode     = "0",
            };



            var _charge = new ChargeAuthorizeServiceOptions()
            {
                total           = (decimal)_totalAmount,
                currency        = "USD",
                merchantOrderId = "1",
                token           = collection["token"].ToString(),
                billingAddr     = Billing
            };


            var _paymentResult = new PaymentGatewayResponse();


            if (model.PaymentMethodId == 1)
            {
                _paymentResult = _payment.CheckOutTwoCheckOut(_charge);
            }


            model.ShippingAddress = await data.CustomerShippingAddresses.Where(i => i.AspNetUserId == userId && i.IsDefault == true).FirstOrDefaultAsync();


            if (_paymentResult.PaymentStatus != "failed")
            {
                model.PaymentRef    = _paymentResult.refNo;
                model.TotalAmount   = _paymentResult.amount ?? 0;
                model.UserId        = userId;
                model.PaymentStatus = _paymentResult.PaymentStatus;
                dataLayer.createOrder(model);
            }



            return(View(model));
        }