Ejemplo n.º 1
0
        public async Task Should_return_payment_result_from_payfort(CreditCardPaymentResult cardPaymentResult)
        {
            var processingService = new PaymentLinksProcessingService(CreatMockPayfortService(),
                                                                      Mock.Of <IPayfortResponseParser>(),
                                                                      CreateLinkStorageMock().Object,
                                                                      SignatureServiceStub,
                                                                      EmptyPayfortOptions,
                                                                      Mock.Of <IPaymentLinkNotificationService>(),
                                                                      EntityLockerMock.Object);

            var(_, isFailure, response, _) = await processingService.Pay(AnyString,
                                                                         AnyString, "::1",
                                                                         "en");

            Assert.False(isFailure);
            Assert.Equal(response.Status, cardPaymentResult.Status);
            Assert.Equal(response.Message, cardPaymentResult.Message);


            IPayfortService CreatMockPayfortService()
            {
                var service = new Mock <IPayfortService>();

                service.Setup(p => p.Pay(It.IsAny <CreditCardPaymentRequest>()))
                .Returns(Task.FromResult(Result.Success(cardPaymentResult)));

                return(service.Object);
            }
        }
Ejemplo n.º 2
0
            async Task <Result <PaymentResponse> > StorePaymentResults(CreditCardPaymentResult paymentResult)
            {
                var card = request.IsSaveCardNeeded
                    ? await _context.CreditCards.SingleOrDefaultAsync(c => c.Token == request.Token)
                    : null;

                var payment = await CreatePayment(ipAddress, servicePrice, card?.Id, paymentResult);

                var(_, isFailure, error) = await paymentCallbackService.ProcessPaymentChanges(payment);

                return(isFailure
                    ? Result.Failure <PaymentResponse>(error)
                    : Result.Success(paymentResult.ToPaymentResponse()));
            }
Ejemplo n.º 3
0
            async Task <Result <PaymentResponse> > StorePaymentResults(CreditCardPaymentResult paymentResult)
            {
                var card = request.IsSaveCardNeeded
                    ? await _context.CreditCards.SingleOrDefaultAsync(c => c.Token == request.Token)
                    : null;

                var payment = await CreatePayment(ipAddress, servicePrice, card?.Id, paymentResult);

                var(_, isFailure, error) = await paymentsService.ProcessPaymentChanges(payment)
                                           .Bind(() => _bookingRecordsManager.SetPaymentMethod(request.ReferenceCode, PaymentMethods.CreditCard));

                return(isFailure
                    ? Result.Failure <PaymentResponse>(error)
                    : Result.Success(paymentResult.ToPaymentResponse()));
            }
        public Task <Result <CreditCardPaymentResult> > ProcessPaymentResponse(CreditCardPaymentResult paymentResponse,
                                                                               Currencies currency,
                                                                               int agentId)
        {
            return(CheckPaymentStatusNotFailed(paymentResponse)
                   .TapIf(IsPaymentComplete, cardPaymentResult => WriteAuditLog()));


            Result <CreditCardPaymentResult> CheckPaymentStatusNotFailed(CreditCardPaymentResult payment)
            => payment.Status == CreditCardPaymentStatuses.Failed
                    ? Result.Failure <CreditCardPaymentResult>($"Payment error: {payment.Message}")
                    : Result.Success(payment);


            bool IsPaymentComplete(CreditCardPaymentResult cardPaymentResult) => cardPaymentResult.Status == CreditCardPaymentStatuses.Success;

            Task WriteAuditLog() => WriteAuthorizeAuditLog(paymentResponse, agentId, currency);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Add a new credit card by first verifying it via an AUTHORIZATION only transaction.
        /// </summary>
        /// <returns>PaymentMethodID of the newly added credit card if success. If an error occurred, the returned PaymentMethodID will be 0.</returns>
        public int AddAndVerifyNewCreditCard(string externalType, int externalID, int subscriptionID, string description, int ccType, string ccNum, DateTime expDate, string csc,
                string firstName, string lastName, string company, string email, string address1, string address2,
                string city, string state, string province, string zip, int countryID, string phone, string mobilePhone,
                string ip, string userAgent, string surferID)
        {
            decimal amount = 0;

            CreditCardPaymentResult result = new CreditCardPaymentResult();

            int paymentID = ProcessPaymentUsingActualCcNum(externalType, externalID, subscriptionID, Constants.Enumerators.TransactionType.Authorization, Constants.Enumerators.PaymentType.Verification,
                ccType, ccNum, expDate, csc, amount, description, firstName, lastName, company, email, address1, address2, city, state, province, zip, countryID, phone, mobilePhone, ip, userAgent, surferID, ref result);

            CreditCardPayment creditCardPayment = CreditCardService.GetCreditCardPaymentByID(paymentID, externalType, externalID);

            if (creditCardPayment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.Approved)
                return creditCardPayment.PaymentMethodUsed.PaymentMethodID;
            else
                return 0;
        }
Ejemplo n.º 6
0
        public static int AddCreditCardPayment(CreditCardPaymentMethod cc, CreditCardPaymentResult result)
        {
            int paymentID = 0;
            string resultFinal = "";

            DataSet ds = CommonData.ExecuteStoredProcedure(Constants.StoredProcedures.PaymentsAddCreditCardPayment,
                CommonData.SqlParam("@ExternalType", SqlDbType.VarChar, 100, cc.ExternalType),
                CommonData.SqlParam("@ExternalID", SqlDbType.Int, 4, cc.ExternalID),
                CommonData.SqlParam("@PaymentMethodID", SqlDbType.Int, 4, cc.PaymentMethodID),
                CommonData.SqlParam("@SubscriptionID", SqlDbType.Int, 4, result.SubscriptionID),
                CommonData.SqlParam("@TransactionDate", SqlDbType.DateTime, 8, DateTime.UtcNow),
                CommonData.SqlParam("@PaymentType", SqlDbType.TinyInt, 1, result.PaymentType),
                CommonData.SqlParam("@TransactionType", SqlDbType.Char, 1, result.TransactionType),
                CommonData.SqlParam("@Amount", SqlDbType.Money, 1, result.Amount),
                CommonData.SqlParam("@TransactionID", SqlDbType.VarChar, 50, result.TransactionID),
                CommonData.SqlParam("@OriginalTransactionID", SqlDbType.VarChar, 50, result.OriginalTransactionID),
                CommonData.SqlParam("@Description", SqlDbType.VarChar, 255, result.Description),
                CommonData.SqlParam("@ResultCode", SqlDbType.Int, 4, result.ResultCode),
                CommonData.SqlParam("@ResponseMessage", SqlDbType.VarChar, 255, result.ResponseMessage),
                CommonData.SqlParam("@AuthorizationCode", SqlDbType.VarChar, 10, result.AuthorizationCode),
                CommonData.SqlParam("@CscMatch", SqlDbType.VarChar, 10, result.CscMatch),
                CommonData.SqlParam("@AvsMatch", SqlDbType.VarChar, 10, result.AvsMatch),
                CommonData.SqlParam("@InternationalAvs", SqlDbType.Char, 1, result.InternationalAvs),
                CommonData.SqlParam("@Ip", SqlDbType.VarChar, 15, result.IP),
                CommonData.SqlParam("@PayflowRequestID", SqlDbType.VarChar, 50, result.PayflowRequestID),
                CommonData.SqlParam("@PaymentID", ParameterDirection.Output, SqlDbType.Int, 4, 0),
                CommonData.SqlParam("@ResultFinal", ParameterDirection.Output, SqlDbType.VarChar, 50, ""));

            if (ds != null && ds.Tables["Parameters"] != null)
            {
                DataRow[] dr = ds.Tables["Parameters"].Select("Name='@PaymentID'");
                if (dr.Length > 0)
                    paymentID = int.Parse(dr[0]["Value"].ToString());

                dr = ds.Tables["Parameters"].Select("Name='@resultFinal'");
                if (dr.Length > 0)
                    resultFinal = dr[0]["Value"].ToString();
            }

            return paymentID;
        }
Ejemplo n.º 7
0
        public static CreditCardPaymentResult DoCapture(string authTransactionID)
        {
            CreditCardPaymentResult result = new CreditCardPaymentResult();

            result.TransactionDate = DateTime.UtcNow;
            result.TransactionType = "D";
            result.PayflowRequestID = PayPal.Payments.Common.Utility.PayflowUtility.RequestId;

            // Create PayflowConnectionData object
            PayPal.Payments.DataObjects.PayflowConnectionData pfCnn = new PayPal.Payments.DataObjects.PayflowConnectionData(_payflowHost, _payflowPort, _payflowTimeout, _proxyHost, _proxyPort, _proxyLogon, _proxyPassword);

            // Prepare user credentials
            PayPal.Payments.DataObjects.UserInfo user = new PayPal.Payments.DataObjects.UserInfo(_payflowUser, _payflowMerchant, _payflowPartner, _payflowPassword);

            // Prepare delayed capture transaction
            PayPal.Payments.Transactions.CaptureTransaction captureTran = new PayPal.Payments.Transactions.CaptureTransaction(authTransactionID, user, pfCnn, result.PayflowRequestID);

            // Submit the transaction and receive the response from Payflow server
            PayPal.Payments.DataObjects.Response response = captureTran.SubmitTransaction();

            // Assign response values to the result object
            if (response != null && response.TransactionResponse != null)
            {
                result.TransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.Pnref);

                result.OriginalTransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.OrigPnref);
                if (result.OriginalTransactionID == "")
                    result.OriginalTransactionID = authTransactionID;

                result.ResultCode = response.TransactionResponse.Result;
                result.ResponseMessage = ReplaceNullWithEmptyString(response.TransactionResponse.RespMsg);

                result.AuthorizationCode = ReplaceNullWithEmptyString(response.TransactionResponse.AuthCode);
                result.AvsMatch = ReplaceNullWithEmptyString(response.TransactionResponse.AVSAddr) + ReplaceNullWithEmptyString(response.TransactionResponse.AVSZip);
                result.CscMatch = ReplaceNullWithEmptyString(response.TransactionResponse.CVV2Match);
                result.InternationalAvs = ReplaceNullWithEmptyString(response.TransactionResponse.IAVS);
            }

            return result;
        }
        private async Task WriteAuthorizeAuditLog(CreditCardPaymentResult payment, int agentId, Currencies currency)
        {
            // No need to log secure 3d request, audit log will be written when when secure 3d passes and actual authorization occurs
            if (payment.Status == CreditCardPaymentStatuses.Secure3d)
            {
                return;
            }

            var eventData = new CreditCardLogEventData($"Authorize money for the payment '{payment.ReferenceCode}'",
                                                       payment.ExternalCode,
                                                       payment.Message,
                                                       payment.MerchantReference);

            await _creditCardAuditService.Write(CreditCardEventType.Authorize,
                                                payment.CardNumber,
                                                payment.Amount,
                                                new UserInfo(agentId, UserTypes.Agent),
                                                eventData,
                                                payment.ReferenceCode,
                                                agentId,
                                                currency);
        }
Ejemplo n.º 9
0
 Task SaveCard(CreditCardPaymentResult _)
 => _creditCardsManagementService.Save(request.CardInfo, request.Token, agent);
Ejemplo n.º 10
0
 bool IsSaveCardNeeded(CreditCardPaymentResult response)
 => request.IsSaveCardNeeded && response.Status != CreditCardPaymentStatuses.Failed;
Ejemplo n.º 11
0
 public static PaymentResponse ToPaymentResponse(this CreditCardPaymentResult result) => new PaymentResponse(result.Secure3d, result.Status, result.Message);
Ejemplo n.º 12
0
        public static CreditCardPaymentResult DoSaleByReference(CreditCardPaymentMethod cc, decimal amount, string description, string comment1, string comment2, string ip, string userAgent)
        {
            CreditCardPaymentResult result = new CreditCardPaymentResult();

            result.TransactionDate = DateTime.UtcNow;
            result.TransactionType = "S";
            result.Amount = amount;
            result.PayflowRequestID = PayPal.Payments.Common.Utility.PayflowUtility.RequestId;
            result.IP = ip;

            // Create PayflowConnectionData object
            PayPal.Payments.DataObjects.PayflowConnectionData pfCnn = new PayPal.Payments.DataObjects.PayflowConnectionData(_payflowHost, _payflowPort, _payflowTimeout, _proxyHost, _proxyPort, _proxyLogon, _proxyPassword);

            // Prepare user credentials
            PayPal.Payments.DataObjects.UserInfo user = new PayPal.Payments.DataObjects.UserInfo(_payflowUser, _payflowMerchant, _payflowPartner, _payflowPassword);

            // Prepare invoice
            PayPal.Payments.DataObjects.Invoice invoice = new PayPal.Payments.DataObjects.Invoice();

            invoice.Amt = new PayPal.Payments.DataObjects.Currency((decimal)amount);
            invoice.Comment1 = comment1;
            invoice.Comment2 = comment2;
            invoice.Desc = description;

            invoice.CustomerInfo = new PayPal.Payments.DataObjects.CustomerInfo();
            invoice.CustomerInfo.CustId = cc.ExternalType + "-" + cc.ExternalID;
            invoice.CustomerInfo.CustIP = cc.IP;
            invoice.CustomerInfo.CustCode = cc.ExternalType + "-" + cc.ExternalID;

            invoice.BrowserInfo = new PayPal.Payments.DataObjects.BrowserInfo();
            invoice.BrowserInfo.BrowserUserAgent = userAgent;

            invoice.BillTo = new PayPal.Payments.DataObjects.BillTo();
            invoice.BillTo.FirstName = cc.FirstName;
            invoice.BillTo.LastName = cc.LastName;
            invoice.BillTo.Street = cc.Address1;
            invoice.BillTo.BillToStreet2 = cc.Address2;
            invoice.BillTo.City = cc.City;
            invoice.BillTo.State = cc.State;
            invoice.BillTo.Zip = cc.Zip;
            invoice.BillTo.BillToCountry = cc.CountryID.ToString();
            invoice.BillTo.Email = cc.Email;
            invoice.BillTo.BillToPhone2 = cc.MobilePhone;

            invoice.ShipTo = invoice.BillTo.Copy();

            // Prepare credit card information
            PayPal.Payments.DataObjects.CreditCard creditCard = new PayPal.Payments.DataObjects.CreditCard("", cc.CcExpDate.ToString("MMyy"));
            creditCard.Name = (invoice.BillTo.FirstName + " " + invoice.BillTo.LastName).Trim();

            PayPal.Payments.DataObjects.CardTender cardTender = new PayPal.Payments.DataObjects.CardTender(creditCard);

            // Prepare reference transaction
            PayPal.Payments.Transactions.ReferenceTransaction refTran = new PayPal.Payments.Transactions.ReferenceTransaction("S", cc.LastApprovedTransactionID, user, pfCnn, invoice, cardTender, result.PayflowRequestID);

            // Submit the transaction and receive the response from Payflow server
            PayPal.Payments.DataObjects.Response response = refTran.SubmitTransaction();

            // Assign response values to the result object
            if (response != null && response.TransactionResponse != null)
            {
                result.TransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.Pnref);
                result.OriginalTransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.OrigPnref);
                result.ResultCode = response.TransactionResponse.Result;
                result.ResponseMessage = ReplaceNullWithEmptyString(response.TransactionResponse.RespMsg);

                result.AuthorizationCode = ReplaceNullWithEmptyString(response.TransactionResponse.AuthCode);
                result.AvsMatch = ReplaceNullWithEmptyString(response.TransactionResponse.AVSAddr) + ReplaceNullWithEmptyString(response.TransactionResponse.AVSZip);
                result.CscMatch = ReplaceNullWithEmptyString(response.TransactionResponse.CVV2Match);
                result.InternationalAvs = ReplaceNullWithEmptyString(response.TransactionResponse.IAVS);
            }

            return result;
        }
Ejemplo n.º 13
0
        public static CreditCardPaymentResult DoVoid(string originalTransactionID, string externalType, int externalID, string description, string comment1, string comment2, string ip, string userAgent)
        {
            CreditCardPaymentResult result = new CreditCardPaymentResult();

            result.TransactionDate = DateTime.UtcNow;
            result.TransactionType = "V";
            result.PayflowRequestID = PayPal.Payments.Common.Utility.PayflowUtility.RequestId;
            result.IP = ip;

            // Create PayflowConnectionData object
            PayPal.Payments.DataObjects.PayflowConnectionData pfCnn = new PayPal.Payments.DataObjects.PayflowConnectionData(_payflowHost, _payflowPort, _payflowTimeout, _proxyHost, _proxyPort, _proxyLogon, _proxyPassword);

            // Prepare user credentials
            PayPal.Payments.DataObjects.UserInfo user = new PayPal.Payments.DataObjects.UserInfo(_payflowUser, _payflowMerchant, _payflowPartner, _payflowPassword);

            // Prepare invoice
            PayPal.Payments.DataObjects.Invoice invoice = new PayPal.Payments.DataObjects.Invoice();

            invoice.Comment1 = comment1;
            invoice.Comment2 = comment2;
            invoice.Desc = description;

            invoice.CustomerInfo = new PayPal.Payments.DataObjects.CustomerInfo();
            invoice.CustomerInfo.CustId = externalType + "-" + externalID;
            invoice.CustomerInfo.CustIP = ip;
            invoice.CustomerInfo.CustCode = externalType + "-" + externalID;

            invoice.BrowserInfo = new PayPal.Payments.DataObjects.BrowserInfo();
            invoice.BrowserInfo.BrowserUserAgent = userAgent;

            invoice.BillTo = new PayPal.Payments.DataObjects.BillTo();

            // Prepare void transaction
            PayPal.Payments.Transactions.VoidTransaction voidTran = new PayPal.Payments.Transactions.VoidTransaction(originalTransactionID, user, pfCnn, invoice, result.PayflowRequestID);

            // Submit the transaction and receive the response from Payflow server
            PayPal.Payments.DataObjects.Response response = voidTran.SubmitTransaction();

            // Assign response values to the result object
            if (response != null && response.TransactionResponse != null)
            {
                result.TransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.Pnref);

                result.OriginalTransactionID = ReplaceNullWithEmptyString(response.TransactionResponse.OrigPnref);
                if (result.OriginalTransactionID == "")
                    result.OriginalTransactionID = originalTransactionID;

                result.ResultCode = response.TransactionResponse.Result;
                result.ResponseMessage = ReplaceNullWithEmptyString(response.TransactionResponse.RespMsg);

                result.AuthorizationCode = ReplaceNullWithEmptyString(response.TransactionResponse.AuthCode);
                result.AvsMatch = ReplaceNullWithEmptyString(response.TransactionResponse.AVSAddr) + ReplaceNullWithEmptyString(response.TransactionResponse.AVSZip);
                result.CscMatch = ReplaceNullWithEmptyString(response.TransactionResponse.CVV2Match);
                result.InternationalAvs = ReplaceNullWithEmptyString(response.TransactionResponse.IAVS);
            }

            return result;
        }
Ejemplo n.º 14
0
        public static CreditCardPayment ConvertToCreditCardPayment(DataRow dr)
        {
            CreditCardPayment payment = new CreditCardPayment();

            payment.PaymentID = Convert.ToInt32(dr["PaymentID"]);
            payment.ExternalType = Convert.ToString(dr["ExternalType"]);
            payment.ExternalID = Convert.ToInt32(dr["ExternalID"]);

            CreditCardPaymentMethod cc = new CreditCardPaymentMethod();

            cc.ExternalType = payment.ExternalType;
            cc.ExternalID = payment.ExternalID;

            cc.PaymentMethodID = Convert.ToInt32(dr["PaymentMethodID"]);
            try { cc.FirstName = dr["FirstName"].ToString(); }
            catch { }

            try { cc.LastName = dr["LastName"].ToString(); }
            catch { }

            try { cc.Company = dr["Company"].ToString(); }
            catch { }

            try { cc.Email = dr["Email"].ToString(); }
            catch { }

            try { cc.Address1 = dr["Address1"].ToString(); }
            catch { }

            try { cc.Address2 = dr["Address2"].ToString(); }
            catch { }

            try { cc.City = dr["City"].ToString(); }
            catch { }

            try { cc.State = dr["State"].ToString(); }
            catch { }

            try { cc.Province = dr["Province"].ToString(); }
            catch { }

            try { cc.Zip = dr["Zip"].ToString(); }
            catch { }

            try { cc.CountryID = Convert.ToInt32(dr["CountryID"]); }
            catch { }

            try { cc.Country = dr["Country"].ToString(); }
            catch { }

            try { cc.Phone = dr["Phone"].ToString(); }
            catch { }

            try { cc.MobilePhone = dr["MobilePhone"].ToString(); }
            catch { }

            payment.PaymentMethodUsed = cc;

            CreditCardPaymentResult ctr = new CreditCardPaymentResult();

            try { ctr.TransactionDate = Convert.ToDateTime(dr["TransactionDate"]); }
            catch { }
            try { ctr.PaymentType = Convert.ToInt32(dr["PaymentType"]); }
            catch { }

            try { ctr.TransactionType = dr["TransactionType"].ToString(); }
            catch { }

            try { ctr.Amount = Convert.ToDecimal(dr["Amount"]); }
            catch { }

            try { ctr.TransactionID = dr["TransactionID"].ToString(); }
            catch { }

            try { ctr.ResultFinal = (Constants.Enumerators.PaymentResultFinal)Enum.Parse(typeof(Constants.Enumerators.PaymentResultFinal), dr["ResultFinal"].ToString(), true); }
            catch { }

            try { ctr.SubscriptionID = Convert.ToInt32(dr["SubscriptionID"]); }
            catch { }

            try { ctr.Description = dr["Description"].ToString(); }
            catch { }

            try { ctr.CscMatch = dr["CscMatch"].ToString(); }
            catch { }

            try { ctr.AvsMatch = dr["AvsMatch"].ToString(); }
            catch { }

            try { ctr.InternationalAvs = dr["InternationalAvs"].ToString(); }
            catch { }

            try { ctr.IP = dr["IP"].ToString(); }
            catch { }

            try { ctr.IPCountry = dr["IPCountry"].ToString(); }
            catch { }

            try { payment.TransactionResult = ctr; }
            catch { }

            try { payment.CaptureTransactionID = dr["CaptureTransactionID"].ToString(); }
            catch { }

            try { payment.CaptureTransactionDate = Convert.ToDateTime(dr["CaptureTransactionDate"]); }
            catch { }

            return payment;
        }
Ejemplo n.º 15
0
        public static UserSubscriptionResult ProcessUserSubscriptionRequest(UserSubscriptionRequest req)
        {
            UserSubscriptionResult result = new UserSubscriptionResult();
            List<UserSubscription> subscriptions = GetUserSubscriptions(req.UserID);

            if (subscriptions.Count > 0)
            {
                result.ErrorMessages.Add(UserMessages.AlreadyHaveActiveSubscription);
                return result;
            }

            UserSubscriptionType subscriptionType = GetUserSubscriptionType(req.UserSubscriptionTypeID);

            if (subscriptionType.SubscriptionTypeID == 0)
            {
                result.ErrorMessages.Add(UserMessages.ErrorProcessingRequest);
                return result;
            }

            List<UserSubscription> existingSubscriptions = GetUserSubscriptions(req.UserID);
            if (existingSubscriptions.Count > 0)
            {
                result.ErrorMessages.Add(UserMessages.AlreadyHaveActiveSubscription);
                return result;
            }

            DateTime dateStart = DateTime.UtcNow.Date;
            DateTime dateEnd = subscriptionType.GetDateEnd(dateStart);

            int subscriptionID = AddUserSubscription(req.UserID, req.UserSubscriptionTypeID, dateStart, dateEnd, 0);

            if (subscriptionID == 0)
            {
                result.ErrorMessages.Add(UserMessages.ErrorProcessingRequest);
                return result;
            }

            PayflowPaymentService ccs = new PayflowPaymentService();
            int paymentID = 0;

            CreditCardPaymentResult creditCardTransactionResult = new CreditCardPaymentResult();
            if (req.PaymentMethodID == 0)
                paymentID = ccs.ProcessPaymentUsingActualCcNum(Constants.ExternalTypes.Users, req.UserID, subscriptionID, req.TransactionType, req.PaymentType, req.CcType, req.CcNum, req.ExpDate, req.Csc, subscriptionType.Amount, subscriptionType.Description, req.FirstName, req.LastName, "", req.Email, req.Address1, req.Address2, req.City, req.State, "", req.Zip, req.CountryID, req.Phone, req.MobilePhone, req.IP, req.UserAgent, req.SurferID, ref creditCardTransactionResult);
            else
            {

            }
            if (paymentID == 0)
            {
                AddSubscriptionError(req, subscriptionType);
                result.ErrorMessages.Add(UserMessages.ErrorProcessingRequest);
                return result;
            }

            CreditCardPayment payment = CreditCardService.GetCreditCardPaymentByID(paymentID, Constants.ExternalTypes.Users, req.UserID);

            if (payment.PaymentID == 0)
            {
                AddSubscriptionError(req, subscriptionType);
                result.ErrorMessages.Add(UserMessages.ErrorProcessingRequest);
                return result;
            }

            // Hard Decline
            if (payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.AVSFailed ||
                payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.CSCFailed ||
                payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.Declined)
            {
                result.ErrorMessages.Add(UserMessages.TransactionDeclined);
                return result;
            }
            else if (payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.CommError)
            {
                result.ErrorMessages.Add(UserMessages.ErrorProcessingRequest);
                return result;
            }

            result.PaymentID = paymentID;

            // Create Transaction Register "Debit" with Order Total Price

            // Update user subscription status
            UpdateUserSubscriptionStatus(subscriptionID, req.UserID, Constants.Enumerators.SubscriptionStatus.Active);

            return result;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Process SALE transaction using reference transaction and the last approved transaction id.
        /// </summary>
        /// <returns>PaymentID which can be used to lookup the detailed results in the Payments table. If an error occurred, the returned PaymentID will be 0.</returns>
        public int ProcessPaymentUsingReferenceTransaction(string externalType, int externalID, int subscriptionID, Constants.Enumerators.PaymentType paymentType, int paymentMethodID, decimal amount, string description, string ip, string userAgent, string surferID, ref CreditCardPaymentResult result)
        {
            try
            {
                // Validate input data
                if (amount < MIN_AMOUNT || amount >= MAX_AMOUNT)
                    throw new CreditCardServiceException("Invalid deposit amount.");

                CreditCardPaymentMethod existingCc = CreditCardService.GetCreditCardByID(paymentMethodID, externalType, externalID);

                // Credit card must exist (status=3 means deleted)
                if (existingCc.PaymentMethodID == 0 || existingCc.Status == Constants.Enumerators.PaymentMethodStatus.Deleted)
                    throw new CreditCardServiceException("Credit card does not exist.");

                // LastApprovedTransactionID must be present and must have taken place within the last 11 months
                if (existingCc.LastApprovedTransactionID == "" || existingCc.LastApprovedTransactionDate < DateTime.Now.AddMonths(-11))
                    throw new CreditCardServiceException("This credit card was not used for a while and the actual credit card number must be provided anew.");

                // Expiration date must be valid
                if (existingCc.CcExpDate < DateTime.Now)
                    throw new CreditCardServiceException("Invalid expiration date.");

                // Velocity limit to prevent brute forcing
                int velocityLimitCode = GetVelocityLimitCode(externalType, externalID, existingCc.CcNumHash, ip, userAgent, surferID);
                if (velocityLimitCode != 0)
                    throw new CreditCardServiceException(string.Format("Transaction cannot be processed. Please contact Customer Support and reference code [{0}].", velocityLimitCode));

                // Pass externalID to Payflow in comment1 field
                string comment1 = externalType + "-" + externalID;
                string comment2 = subscriptionID.ToString();

                // Perform sale transaction using the lastApprovedTransactionID
                result = PayflowHelper.DoSaleByReference(existingCc, amount, "", comment1, comment2, ip, userAgent);

                // Set current IP
                existingCc.IP = ip;

                // Assign the appropriate payment type
                result.PaymentType = (int)paymentType;

                // Add credit card payment and determine the ResultFinal of this payment
                // This call will save the payment result and insert register record, etc.
                result.SubscriptionID = subscriptionID;
                result.Description = description;

                result.PaymentID = CreditCardService.AddCreditCardPayment(existingCc, result);

                // Check the ResultFinal and void the transaction (both Sale and Auth) if it was AVSFailed or CSCFailed
                VoidInvalidApprovedPayment(result, externalType, externalID, ip, userAgent);

                // Return paymentID
                return result.PaymentID;
            }
            catch (CreditCardServiceException e)
            {
                throw (Exception)e;
            }
            catch (Exception e)
            {
                LogError("ProcessPaymentUsingReferenceTransaction", e);
                throw new Exception("Error processing transaction.");
            }
        }
Ejemplo n.º 17
0
 public static bool MarkCreditCardPaymentAsVoided(int paymentID, string externalType, int externalID, CreditCardPaymentResult result)
 {
     return CreditCardData.MarkCreditCardPaymentAsVoided(paymentID, externalType, externalID, result);
 }
Ejemplo n.º 18
0
 public static int AddCreditCardPayment(CreditCardPaymentMethod cc, CreditCardPaymentResult result)
 {
     return CreditCardData.AddCreditCardPayment(cc, result);
 }
Ejemplo n.º 19
0
        public static bool MarkCreditCardPaymentAsVoided(int paymentID, string externalType, int externalID, CreditCardPaymentResult result)
        {
            bool success = false;

            DataSet ds = CommonData.ExecuteStoredProcedure(Constants.StoredProcedures.PaymentsUpdateVoidTransactionID,
                CommonData.SqlParam("@ExternalType", SqlDbType.VarChar, 100, externalType),
                CommonData.SqlParam("@ExternalID", SqlDbType.Int, 4, externalID),
                CommonData.SqlParam("@PaymentID", SqlDbType.Int, 4, paymentID),
                CommonData.SqlParam("@VoidTransactionID", SqlDbType.VarChar, 50, result.TransactionID),
                CommonData.SqlParam("@ResultCode", ParameterDirection.Output, SqlDbType.Int, 4, 0));

            if (ds != null && ds.Tables["Parameters"] != null)
            {
                DataRow[] dr = ds.Tables["Parameters"].Select("Name='@ResultCode'");
                if (dr.Length > 0)
                    success = (Convert.ToInt32(dr[0]["Value"]) == 0);
            }

            return success;
        }
Ejemplo n.º 20
0
        private void VoidInvalidApprovedPayment(CreditCardPaymentResult result, string externalType, int externalID, string ip, string userAgent)
        {
            // Verification transactions cannot be voided
            if (result.PaymentType == (int)Constants.Enumerators.PaymentType.Verification)
                return;

            // Check the ResultFinal and void the transaction (both Sale and Auth) if it was AVSFailed or CSCFailed
            CreditCardPayment payment = CreditCardService.GetCreditCardPaymentByID(result.PaymentID, externalType, externalID);

            if (payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.AVSFailed || payment.TransactionResult.ResultFinal == Constants.Enumerators.PaymentResultFinal.CSCFailed)
            {
                string errorMessage = "";

                // Perform the void transaction
                CreditCardPaymentResult voidResult = PayflowHelper.DoVoid(payment.TransactionResult.TransactionID, externalType, externalID, "", externalType + "-" + externalID, "VOID " + payment.TransactionResult.ResultFinal.ToString(), ip, userAgent);

                // If void transaction succeeded, mark the original payment as voided
                if (voidResult.ResultCode == 0)
                {
                    if (!CreditCardService.MarkCreditCardPaymentAsVoided(result.PaymentID, externalType, externalID, voidResult))
                        errorMessage = string.Format("Void succeeded but was not marked properly in the database; (PaymentID={0}; TranID={1}; Amount={2}; VoidTranID={3}; ExternalType={4}; ExternalID={5})", result.PaymentID, result.TransactionID, result.Amount, voidResult.TransactionID, externalType, externalID);
                }
                else
                {
                    // Void failed
                    errorMessage = string.Format("Void failed; (PaymentID={0}; TranID={1}; Amount={2}; VoidTranID={3}; VoidResultCode={4}; VoidResponseMessage={5}; ExternalType={6}; ExternalID={7})", result.PaymentID, result.TransactionID, result.Amount, voidResult.TransactionID, voidResult.ResultCode, voidResult.ResponseMessage, externalType, externalID);
                }

                // Log the error message
                if (errorMessage != "")
                    LogError(errorMessage, null);
                else
                    LogInfo(string.Format("Void succeeded; (PaymentID={0}; TranID={1}; Amount={2}; VoidTranID={3}; ExternalType={4}; ExternalID={5})", result.PaymentID, result.TransactionID, result.Amount, voidResult.TransactionID, externalType, externalID), null);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Process AUTHORIZATION or SALE transaction using new credit card number by checking ccNumHash of previous cards used by the same customer.
        /// </summary>
        /// <returns>PaymentID which can be used to lookup the detailed results in the Payments table. If an error occurred, the returned PaymentID will be 0.</returns>
        public int ProcessPaymentUsingActualCcNum(string externalType, int externalID, int subscriptionID, Constants.Enumerators.TransactionType transactionType, Constants.Enumerators.PaymentType paymentType, int ccType, string ccNum, DateTime expDate, string csc,
                decimal amount, string description, string firstName, string lastName, string company, string email, string address1, string address2,
                string city, string state, string province, string zip, int countryID, string phone, string mobilePhone,
                string ip, string userAgent, string surferID, ref CreditCardPaymentResult result)
        {
            try
            {
                // Validate input data
                if (ccType != 1 && ccType != 2 && ccType != 3)
                    throw new CreditCardServiceException("Invalid credit card type.");

                if (!Regex.IsMatch(ccNum, @"^\d{13,19}$"))
                    throw new CreditCardServiceException("Invalid credit card number format.");

                if (expDate < DateTime.UtcNow)
                    throw new CreditCardServiceException("Invalid expiration date.");

                if (!Regex.IsMatch(csc, @"^\d{3,4}$"))
                    throw new CreditCardServiceException("Invalid card security code format.");

                if (amount < MIN_AMOUNT || amount >= MAX_AMOUNT)
                    throw new CreditCardServiceException("Invalid deposit amount.");

                // Calculate brute-force-resistant ccNumHash using  SHA256 with long secret salt
                // and large number of iterations
                string ccNumHash = GetCreditCardNumberHash(ccNum);
                string ccLast4 = ccNum.Substring(ccNum.Length - 4);
                string ccFirst6 = ccNum.Substring(0, 6);

                // Velocity limit to prevent brute forcing
                int velocityLimitCode = GetVelocityLimitCode(externalType, externalID, ccNumHash, ip, userAgent, surferID);
                if (velocityLimitCode != 0)
                    throw new CreditCardServiceException(string.Format("Transaction cannot be processed. Please contact Customer Support and reference code [{0}].", velocityLimitCode));

                CreditCardPaymentMethod existingCc = CreditCardService.GetCreditCardByCcNumHash(externalType, externalID, ccNumHash);

                // Pass externalType and externalID to Payflow in comment1 field
                string comment1 = externalType + "-" + externalID;
                string comment2 = subscriptionID.ToString();

                CreditCardPaymentMethod updatedCc = new CreditCardPaymentMethod(externalType, externalID, ccType, ccNumHash, ccLast4, expDate,
                    firstName, lastName, company, email, address1, address2,
                    city, state, province, zip, countryID, phone, mobilePhone, ip);

                updatedCc.PaymentMethodID = existingCc.PaymentMethodID;

                // Current ccNum is NOT yet associated with the current externalID
                if (existingCc.PaymentMethodID == 0)
                {
                    // Create new credit card record with AuthPending status

                    // Save credit card information
                    updatedCc.PaymentMethodID = CreditCardService.AddCreditCard(updatedCc);

                    if (updatedCc.PaymentMethodID == 0)
                        throw new CreditCardServiceException("Provided credit card could not be added to your account. Please contact Customer Support.");
                }
                else
                {
                    // Update credit card payment method information
                    CreditCardService.UpdateCreditCard(updatedCc);
                }

                if (transactionType == Constants.Enumerators.TransactionType.Sale)
                {
                    // Perform sale transaction using the actual ccNum
                    result = StripePaymentHelper.DoSale(ccNum, csc, updatedCc, amount, description, comment1, comment2, ip, userAgent);
                }
                else
                {
                    // Perform authorization transaction using the actual ccNum
                    result = StripePaymentHelper.DoAuthorization(ccNum, csc, updatedCc, amount, description, comment1, comment2, ip, userAgent);
                }

                result.PaymentType = (int)paymentType;

                // Add credit card payment
                // This call will save the payment result and insert register record, etc.
                result.SubscriptionID = subscriptionID;
                result.Description = description;
                result.PaymentID = CreditCardService.AddCreditCardPayment(updatedCc, result);

                // Check the ResultFinal and void the transaction (both Sale and Auth) if it was AVSFailed or CSCFailed
                VoidInvalidApprovedPayment(result, externalType, externalID, ip, userAgent);

                // Return paymentID
                return result.PaymentID;
            }
            catch (CreditCardServiceException e)
            {
                throw (Exception)e;
            }
            catch (Exception e)
            {
                LogError("ProcessPaymentUsingActualCcNum", e);
                throw new Exception("Error processing transaction.");
            }
        }