/// <summary>
 /// Executes the reserve operation.
 /// </summary>
 /// <param name="paymentInfo">The payment info.</param>
 public void ExecuteReserve(PaymentInfo paymentInfo)
 {
     try
     {
         PayExExecutePaymentArgs args = new PayExExecutePaymentArgs(string.Empty, UrlConstants.PAYMENT_SUCCESS, UrlConstants.PAYMENT_CANCEL, FoundationContext.Culture.Name);
         args.PaymentMode = ExecutePaymentMode.Reserve;
         args.ExecuteScript = new PayExExecutePaymentArgs.ExecuteScriptHandler(delegate(string scriptArgs, bool redirect)
         {
             if (redirect)
                 Response.Redirect(scriptArgs, true);
         });
         args.UserHostAddress = Request.UserHostAddress;
         PayExExecutePaymentResult result = (PayExExecutePaymentResult)paymentInfo.PaymentProvider.ExecutePayment(args, FoundationContext.Token);
         if (!result.Success)
         {
             Response.Redirect(UrlConstants.VIEW_PAYMENT + "?" + ParameterConstants.ECOM_SELECTED_NAVBAR_PAGE + "="
             + ((int)Litium.Studio.UI.ECommerce.Common.Enums.FilterType.Payments).ToString() + "&"
             + ParameterConstants.FROM_PAYMENT + "=true&"
             + ParameterConstants.ECOM_ORDER_ID + "=" + paymentInfo.OrderID + "&"
             + ParameterConstants.ECOM_PAYMENT_INFO_ID + "=" + paymentInfo.ID + "&"
             + ParameterConstants.QUERY_STRING_NAVIGATE_FROM + "=2", true);
         }
     }
     catch (PaymentProviderException) { }
 }
Example #2
0
        public void PostProcessPayment(PaymentInfo order)
        {
            string PUB32 = "30819c300d06092a864886f70d010101050003818a003081860281807cd21042439755abab54981724a366a66913258fcbc6075555e973d48137e22eedd5ab5f3be57404a30795e71f6f4c8f31d4715e3e0d1985426ed51c131bee24448202f3c777558c0e5b23cac643a5bed52719fef620548c6608377d5a86fd57cb8cb67272656cbd9dd8d796dc5613400edb1905b7802a7e7bcd673c3d23d3bf020111";//公钥前30位 新接口使用
            string MERCHANTID = "105584073990057";                  //商户代码(客户号)
            string POSID = "100000631";                             //商户柜台代码
            string BRANCHID = "442000000";                          //分行代码
            string ORDERID = order.SysOrderNo;                      //定单号
            string PAYMENT = order.OrderAmount;                     //付款金额 
            string MAC = "MERCHANTID=" + MERCHANTID + "&POSID=" + POSID
                       + "&BRANCHID=" + BRANCHID + "&ORDERID=" + ORDERID
                       + "&PAYMENT=" + PAYMENT + "&CURCODE=01"
                       + "&TXCODE=520100" + "&REMARK1="
                       + "&REMARK2=";

            HttpHelper http = new HttpHelper();
            http.Url = order.PayOnlineProviderUrl;
            http.Add("INTER_FLAG", "0");                            //商户接口类型 0为旧接口,1为新接口
            http.Add("MERCHANTID", MERCHANTID);
            http.Add("POSID", POSID);
            http.Add("BRANCHID", BRANCHID);
            http.Add("PUB32", PUB32);
            http.Add("ORDERID", ORDERID);
            http.Add("PAYMENT", PAYMENT);                           //付款金额 
            http.Add("CURCODE", "01");                              //币种缺省为01-人民币 
            http.Add("TXCODE", "520100");                           //交易码
            http.Add("REMARK1", "");                                //备注1
            http.Add("REMARK2", "");                                //备注2
            http.Add("DOTYPE", "0");                                //支付类型 0为网上银行支付,1为E付卡支付
            http.Add("MAC", PayHelper.GetMD5(MAC, "").ToLower());   //MAC校验域
            http.Post();
        }
Example #3
0
        private void InsertData()
        {
            CityStateZip cityStateZip = new CityStateZip();
            cityStateZip.City = acctCity.Text;
            cityStateZip.State = acctState.Text;
            cityStateZip.ZipCode = acctZipCode.Text;
            CityStateZipLogic cszLogic = new CityStateZipLogic();
            cityStateZip = cszLogic.InsertCityStateZip(cityStateZip);

            PaymentInfo paymentInfo = new PaymentInfo();
            paymentInfo.AmazonToken = "test";
            PaymentInfoLogic piLogic = new PaymentInfoLogic();
            paymentInfo = piLogic.InsertPaymentInfo(paymentInfo);

            Client client = new Client();
            client.ClientName = acctCompanyName.Text;
            client.PhoneNumber = acctPhoneNumber.Text;
            client.Email = acctEmail.Text;
            client.Address = acctAddress.Text;
            client.CityStateZipGuid = cityStateZip.CityStateZipGuid;
            client.PaymentInfoGuid = paymentInfo.PaymentInfoGuid;
            ClientLogic clientLogic = new ClientLogic();
            client = clientLogic.InsertClient(client);

            Response.Redirect(string.Format("CreateListing.aspx?ClientGuid={0}", client.ClientGuid));
        }
        //This method is reponsible to create a paymentBill with the transaction ID and status completed == false
        public void createPaymentBill(PaymentInfo info, string transactionID)
        {
            try
            {
                using (conferenceadminContext context = new conferenceadminContext())
                {
                    double quantity = info.amount * 100;
                    paymentbill bill = new paymentbill();
                    bill.AmountPaid = info.amount;
                    bill.paymentID = info.paymentID;
                    bill.completed = false;
                    bill.transactionid = transactionID;
                    bill.quantity = (int)quantity;
                    bill.deleted = false;
                    bill.date = DateTime.Now;
                    bill.telephone = info.phone;
                    context.paymentbills.Add(bill);
                    context.SaveChanges();

                }
            }
            catch (Exception ex)
            {
                Console.Write("PaymentManager.makePayment error " + ex);

            }
        }
Example #5
0
        //BluePay stores payment methods by simply using a past transaction's ID as a token.
        //We will do an Auth for $0, and save the resulting TransactionID as a Token in the payment profile BluePayCardVaultId.
        public void StoreInVault(int peopleId, string type, string cardNumber, string expires, string cardCode,
            string routing, string account, bool giving)
        {
            var person = db.LoadPersonById(peopleId);
            var paymentInfo = person.PaymentInfo();
            if (paymentInfo == null)
            {
                paymentInfo = new PaymentInfo();
                person.PaymentInfos.Add(paymentInfo);
            }

            var first = paymentInfo.FirstName ?? person.FirstName;
            var last = paymentInfo.LastName ?? person.LastName;
            var addr = paymentInfo.Address ?? person.PrimaryAddress;
            var city = paymentInfo.City ?? person.PrimaryCity;
            var state = paymentInfo.State ?? person.PrimaryState;
            var zip = paymentInfo.Zip ?? person.PrimaryZip;
            var phone = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone;
            var email = person.EmailAddress;
            const string description = "Storing payment info in BluePay vault.";

            var gateway = createGateway();

            if (type == PaymentType.CreditCard)
            {
                gateway.setupCCTransaction(peopleId, cardNumber, expires, description, null, cardCode, email, first, last, addr, city, state, zip, phone);

                if (string.IsNullOrEmpty(paymentInfo.BluePayCardVaultId))
                    gateway.auth("0.00");
                else //send MasterId if available (this will allow for updating payment profile without re-entering card number)
                    gateway.auth("0.00", paymentInfo.BluePayCardVaultId);

                gateway.Process();
                var response = getResponse(gateway);

                if (!response.Approved)
                    throw new Exception(
                        $"BluePay failed to save the credit card info for people id: {person.PeopleId}, message: {response.Message}; transactionID: {response.TransactionId}");

                //save for future
                paymentInfo.BluePayCardVaultId = response.TransactionId;

                paymentInfo.MaskedCard = Util.MaskCC(cardNumber);
                paymentInfo.Expires = expires;
            }
            //TODO: Handle bank accounts too (not just credit cards)
            else
                throw new ArgumentException($"Type {type} not supported", nameof(type));


            if (giving)
                paymentInfo.PreferredGivingType = type;
            else
                paymentInfo.PreferredPaymentType = type;

            db.SubmitChanges();
        }
Example #6
0
        public void StoreInVault(int peopleId, string type, string cardNumber, string expires, string cardCode,
            string routing, string account, bool giving)
        {
            var person = db.LoadPersonById(peopleId);
            var paymentInfo = person.PaymentInfo();
            if (paymentInfo == null)
            {
                paymentInfo = new PaymentInfo();
                person.PaymentInfos.Add(paymentInfo);
            }

            if (type == PaymentType.CreditCard)
            {
                if (paymentInfo.TbnCardVaultId == null) // create new vault.
                    paymentInfo.TbnCardVaultId = CreateCreditCardVault(person, paymentInfo, cardNumber, expires);
                else
                {
                    // update existing vault.
                    // check for updating the entire card or only expiration.
                    if (!cardNumber.StartsWith("X"))
                        UpdateCreditCardVault(person, paymentInfo, cardNumber, expires);
                    else
                        UpdateCreditCardVault(person, paymentInfo, expires);
                }

                paymentInfo.MaskedCard = Util.MaskCC(cardNumber);
                paymentInfo.Expires = expires;
            }
            else if (type == PaymentType.Ach)
            {
                if (paymentInfo.TbnBankVaultId == null) // create new vault
                    paymentInfo.TbnBankVaultId = CreateAchVault(person, paymentInfo, account, routing);
                else
                {
                    // we can only update the ach account if there is a full account number.
                    if (!account.StartsWith("X"))
                        UpdateAchVault(person, paymentInfo, account, routing);
                    else
                        UpdateAchVault(person, paymentInfo);
                }

                paymentInfo.MaskedAccount = Util.MaskAccount(account);
                paymentInfo.Routing = Util.Mask(new StringBuilder(routing), 2);
            }
            else
                throw new ArgumentException($"Type {type} not supported", nameof(type));

            if (giving)
                paymentInfo.PreferredGivingType = type;
            else
                paymentInfo.PreferredPaymentType = type;
            db.SubmitChanges();
        }
 /// <summary>
 /// Executes the charge operation.
 /// </summary>
 /// <param name="paymentInfo">The payment info.</param>
 public void ExecuteCharge(PaymentInfo paymentInfo)
 {
     try
     {
         // If the order is already reserved, CanCompleteTransaction will be true.
         // Call complete transaction on the already reserved order, else call direct charge customer account.
         if (paymentInfo.PaymentProvider.CanCompleteCurrentTransaction)
         {
             PayPalCompletePaymentArgs completePaymentArgs =
                 new PayPalCompletePaymentArgs(
                     CompleteType.Complete,
                     paymentInfo.TotalAmountWithVAT,
                     paymentInfo.Order.Currency.CurrencyCode,
                     paymentInfo.Order.ExternalOrderID,
                     string.Empty);
             paymentInfo.PaymentProvider.CompletePayment(completePaymentArgs, FoundationContext.Token);
             //redirect to view payment.
             Response.Redirect(UrlConstants.VIEW_PAYMENT + "?" + ParameterConstants.ECOM_SELECTED_NAVBAR_PAGE + "="
             + ((int)Enums.FilterType.Payments).ToString() + "&"
             + ParameterConstants.FROM_PAYMENT + "=true&"
             + ParameterConstants.ECOM_ORDER_ID + "=" + paymentInfo.OrderID + "&"
             + ParameterConstants.ECOM_PAYMENT_INFO_ID + "=" + paymentInfo.ID + "&"
             + ParameterConstants.QUERY_STRING_NAVIGATE_FROM + "=2");
         }
         else
         {
             PayPalExecutePaymentArgs args = new PayPalExecutePaymentArgs(UrlConstants.PAYMENT_SUCCESS, UrlConstants.PAYMENT_CANCEL, FoundationContext.Culture.Name);
             args.PaymentMode = ExecutePaymentMode.Charge;
             args.UserHostAddress = Request.UserHostAddress;
             //add redirect script on success.
             args.ExecuteScript = new PayPalExecutePaymentArgs.ExecuteScriptHandler(delegate(string scriptArgs, bool redirect) { if (redirect) Response.Redirect(scriptArgs, true); });
             PayPalExecutePaymentResult result = (PayPalExecutePaymentResult)paymentInfo.PaymentProvider.ExecutePayment(args, FoundationContext.Token);
             if (!result.Success)
             {
                 Response.Redirect(UrlConstants.VIEW_PAYMENT + "?" + ParameterConstants.ECOM_SELECTED_NAVBAR_PAGE + "="
                 + ((int)Litium.Studio.UI.ECommerce.Common.Enums.FilterType.Payments).ToString() + "&"
                 + ParameterConstants.FROM_PAYMENT + "=true&"
                 + ParameterConstants.ECOM_ORDER_ID + "=" + paymentInfo.OrderID + "&"
                 + ParameterConstants.ECOM_PAYMENT_INFO_ID + "=" + paymentInfo.ID + "&"
                 + ParameterConstants.QUERY_STRING_NAVIGATE_FROM + "=2");
             }
         }
     }
     catch (PaymentProviderException) { }
 }
        static void Main(string[] args)
        {
            FlightTest test = new FlightTest();

            test.intialization();

            Console.WriteLine("Requesting list of all destinations");
            //get all the destinations
            test.proxy.getListOfDestinations();

            //get user inputs
            Console.Write("Enter the starting city code - ");
            string sStart = Console.ReadLine();
            Console.Write("Enter the destination city code - ");
            string sEnd = Console.ReadLine();

            Console.WriteLine("Requesting all the flight IDs between the cities...");
            test.proxy.getAllFlightIDs(sStart, sEnd);

            test.proxy.getListOfAllFlightsBetweenCities(sStart, sEnd);

            test.proxy.getListOfAllAvailableFlightsBetweenCitiesOnDates(sStart, sEnd, DateTime.Now, DateTime.Now.AddDays(2));

            DateTime dtFlight = DateTime.ParseExact("08 Nov 2011 20:00", "dd MMM yyyy HH:mm", null);
            test.proxy.checkIfAvailable(sStart, sEnd, dtFlight, 2);

            Console.WriteLine("Booking tickets now...");

            PassengerInfo[] lstPassengers = test.getPassengers(2).ToArray();
            PaymentInfo pInfo = new PaymentInfo();
            pInfo.cardholdername = lstPassengers[0].passengerName;
            pInfo.cardname = "VISA";
            pInfo.expiryDate = DateTime.Now.AddMonths(2);
            pInfo.cv2 = "234";

            bool bStatus = test.proxyBooking.makeReservation(sStart, sEnd, dtFlight, lstPassengers, pInfo);
            if (bStatus)
                Console.WriteLine("Seats requested have been booked!!!");
            else
                Console.WriteLine("Seats have not been booked!!! Find out why?");

            Console.WriteLine("Press <ENTER> to exit");
            Console.ReadLine();
        }
Example #9
0
		public Order(OrderInfo orderInfo)
		{
			Name = orderInfo.Name;
			TermsAccepted = orderInfo.TermsAccepted;
			PaidDate = orderInfo.PaidDate;
		    FulfillDate = orderInfo.FulfillDate;
			ConfirmDate = orderInfo.ConfirmDate;
			OrderLines = orderInfo.OrderLines.Select(line => new OrderLine(line)).ToList();
			CouponCodes = orderInfo.CouponCodesData;
			CustomerInfo = orderInfo.CustomerInfo;
			ShippingInfo = orderInfo.ShippingInfo;
			PaymentInfo = orderInfo.PaymentInfo;
			StoreInfo = orderInfo.StoreInfo;
			CurrencyCode = orderInfo.Localization.CurrencyCode;
			// todo: onderstaand kan waarschijnlijk anders (geen check = dubbel)
			Discounts = orderInfo.Discounts.Select(discount => new OrderDiscount(orderInfo.Localization, discount, orderInfo)).ToList(); // todo: add/save used coupon code
			IncludingVAT = orderInfo.PricesAreIncludingVAT;

			VatCalculatedOverParts = orderInfo.VatCalculationStrategy is OverSmallestPartsVatCalculationStrategy;

			PaymentProviderPrice = orderInfo.PaymentProviderAmount;
			PaymentProviderOrderPercentage = orderInfo.PaymentProviderOrderPercentage;

			ShippingProviderPrice = orderInfo.ShippingProviderAmountInCents;
			RegionalVatAmount = orderInfo.RegionalVatInCents;

			VATCharged = orderInfo.VATCharged;
			ChargedAmount = orderInfo.ChargedAmountInCents;

			CorrespondingOrderDocumentId = orderInfo.OrderNodeId;

			RevalidateOrderOnLoad = orderInfo.RevalidateOrderOnLoad; // version 2.1 hack
			ReValidateSaveAction = orderInfo.ReValidateSaveAction; // version 2.1 hack

			StockUpdated = orderInfo.StockUpdated;
			CreatedInTestMode = orderInfo.CreatedInTestMode;
		}
Example #10
0
 public UInt16 createPIMDHash(PaymentInfo PI)
 {
     Util.Log(m_TAG, "creating PIMD hash");
     return 2;
 }
 /// <summary>
 /// Adds a PaymentInfo to the collection.
 /// </summary>
 /// <param name="paymentInfo">The paymentInfo to add.</param>
 public void Add(PaymentInfo paymentInfo)
 {
     //paymentInfo.Owner = this;
     List.Add(paymentInfo);
 }
Example #12
0
        private void UpdateAchVault(Person person, PaymentInfo paymentInfo, string accountNumber, string routingNumber)
        {
            var vaultId = paymentInfo.TbnBankVaultId.GetValueOrDefault();

            var updateAchVaultRequest = new UpdateAchVaultRequest(
                _userName,
                _password,
                vaultId.ToString(CultureInfo.InvariantCulture),
                new Ach
                {
                    NameOnAccount =
                        $"{paymentInfo.FirstName ?? person.FirstName} {paymentInfo.LastName ?? person.LastName}",
                    AccountNumber = accountNumber,
                    RoutingNumber = routingNumber,
                    BillingAddress = new BillingAddress
                    {
                        FirstName = paymentInfo.FirstName ?? person.FirstName,
                        LastName = paymentInfo.LastName ?? person.LastName,
                        Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                        City = paymentInfo.City ?? person.PrimaryCity,
                        State = paymentInfo.State ?? person.PrimaryState,
                        Zip = paymentInfo.Zip ?? person.PrimaryZip,
                        Email = person.EmailAddress,
                        Phone = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone
                    }
                });

            var response = updateAchVaultRequest.Execute();
            if (response.ResponseStatus != ResponseStatus.Approved)
                throw new Exception(
                    $"TransNational failed to update the ach account for people id: {person.PeopleId}, responseCode: {response.ResponseCode}, responseText: {response.ResponseText}");
        }
Example #13
0
        /// <summary>
        /// Adds the scheduled payment.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="schedule">The schedule.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialScheduledTransaction AddScheduledPayment(FinancialGateway financialGateway, PaymentSchedule schedule, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            var recurring = GetRecurring(schedule);

            if (paymentInfo is CreditCardPaymentInfo)
            {
                recurring.OptionalTrx = "A";
            }

            var ppTransaction = new RecurringAddTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), GetInvoice(paymentInfo), GetTender(paymentInfo),
                                                            recurring, PayflowUtility.RequestId);

            if (paymentInfo is ReferencePaymentInfo)
            {
                var reference = paymentInfo as ReferencePaymentInfo;
                ppTransaction.OrigId = reference.TransactionCode;
            }
            var ppResponse = ppTransaction.SubmitTransaction();

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        RecurringResponse recurringResponse = ppResponse.RecurringResponse;

                        if (recurringResponse != null)
                        {
                            var scheduledTransaction = new FinancialScheduledTransaction();
                            scheduledTransaction.TransactionCode    = recurringResponse.TrxPNRef;
                            scheduledTransaction.GatewayScheduleId  = recurringResponse.ProfileId;
                            scheduledTransaction.FinancialGatewayId = financialGateway.Id;

                            GetScheduledPaymentStatus(scheduledTransaction, out errorMessage);
                            return(scheduledTransaction);
                        }
                        else
                        {
                            errorMessage = "Invalid recurring response from the financial gateway";
                        }
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }
Example #14
0
        private void SaveECheckToProfile(string routingNumber, string accountNumber, PaymentInfo paymentInfo, Customer customer)
        {
            if (accountNumber.StartsWith("X"))
                return;

            var foundPaymentProfile = customer.PaymentProfiles.SingleOrDefault(p => p.ProfileID == paymentInfo.AuNetCustPayBankId.ToString());

            var bankAccount = new BankAccount
            {
                accountType = BankAccountType.Checking,
                nameOnAccount = customer.Description,
                accountNumber = accountNumber,
                routingNumber = routingNumber
            };

            if (foundPaymentProfile == null)
            {
                var paymentProfileId = CustomerGateway.AddECheckBankAccount(customer.ProfileID, BankAccountType.Checking, routingNumber, accountNumber, customer.Description);
                paymentInfo.AuNetCustPayBankId = paymentProfileId.ToInt();
            }
            else
            {
                foundPaymentProfile.eCheckBankAccount = bankAccount;

                var isSaved = CustomerGateway.UpdatePaymentProfile(customer.ProfileID, foundPaymentProfile);
                if (!isSaved)
                    throw new Exception($"UpdatePaymentProfile failed to save credit card for {paymentInfo.PeopleId}");
            }
        }
Example #15
0
        public PaymentModule(ITokenizer tokenizer)
            : base("/payment")
        {
            Get["/billerror"] = parameters =>
            {
                return Response.AsRedirect("http://136.145.116.238/#/PaymentError");
            };

               Post["/reentry"] = parameters =>
            {
                var xml = this.Request.Form["xml"];

                /*store on db the payment information*/
                XMLReceiptInfo receipt = paymentManager.parseReceiptInfo(xml);

                if (receipt.error == "0")
                {
                    long paymentID = paymentManager.storePaymentBill(receipt);
                    if (paymentID == 0 || paymentID ==-1)
                    {
                        //error storing Payment
                        string link = "http://136.145.116.238/#/PaymentError";
                        return "<URL>"+link+"<URL>";
                    }

                    else{
                        string link = "http://136.145.116.238/#/PaymentBill/" + paymentID;
                         return "<URL> " + link + "<URL>";

                    }

                }
                else {
                    string link = "http://136.145.116.238/#/PaymentError";
                    return "<URL>"+link+"<URL>";
                }

            };
              //
            Put["/SponsorPayment"] = parameters =>
                {   string sponsorProductID = "RECA0185";//sponsor

                    var sponsor = this.Bind<NancyService.Modules.SponsorManager.SponsorQuery>();
                    var temp = this.Bind<PaymentXML>();
                    temp.productID = sponsorProductID;
                    temp.IP =this.Request.UserHostAddress;

                    PaymentInfo payInfo = new PaymentInfo();
                    payInfo.phone=sponsor.phone;
                    payInfo.amount = sponsor.newAmount;
                    payInfo.paymentID =sponsorManager.getPaymentID(sponsor.sponsorID);
                    payInfo.isUser = false;
                    xmlTransacctionID action = paymentManager.MakeWebServiceCall(temp);
                    if (action.error == "000")
                        {

                           if (payInfo.paymentID != 0) { //dont exist a sponsor
                                paymentManager.createPaymentBill(payInfo,action.transactionID);
                                string secureLink = "https://secure2.uprm.edu/payment/index.php?id=" + action.transactionID;
                                return Response.AsJson(secureLink);
                           }
                            else
                           {
                                return HttpStatusCode.Conflict;
                            }
                        }
                     else
                        {
                            string errorLink = null;
                            return Response.AsJson(errorLink);
                        }

                };

            Put["/userPayment"] = parameters =>
            {
                string userProductID = "RECA0186";//registro
                var user = this.Bind<UserInfo>();
                var temp = this.Bind<PaymentXML>();
                temp.line1 = user.addressLine1;
                temp.line2 = user.addressLine2;
                temp.phone=user.phone;
                temp.productID = userProductID;
                temp.IP = this.Request.UserHostAddress;
                if (user.amount == 0)
                {
                    if( profileInfoManager.makePaymentFree(user))
                        return Response.AsJson("billCreated");
                    else
                    {
                        return HttpStatusCode.Conflict;
                    }

                }
                PaymentInfo payInfo = profileInfoManager.userPayment(user);
                payInfo.phone = user.phone;
                payInfo.isUser = true;
                if (payInfo != null)
                {
                    temp.quantity = (payInfo.amount * 100).ToString();
                    xmlTransacctionID action = paymentManager.MakeWebServiceCall(temp);

                    if (action.error == "000")
                    {
                        paymentManager.createPaymentBill(payInfo, action.transactionID);
                        string secureLink = "https://secure2.uprm.edu/payment/index.php?id=" + action.transactionID;
                        return Response.AsJson(secureLink);
                    }
                    else
                    {
                        string errorLink = null;
                        return Response.AsJson(errorLink);
                    }
                }
                else
                {
                    return HttpStatusCode.Conflict;
                }

            };

                Get["/getUserPriceInDeadline/{id:int}"] = parameters =>
            {
                int id = parameters.id;

                AmountSatusRegistration result = paymentManager.getUserPriceInDeadline(id);

                if(result!=null){
                        return Response.AsJson(result);
                }

                else
                {
                    return HttpStatusCode.Conflict;
                }

            };
            Get["/getUserPayment/{id:long}"] = parameters =>
            {
                long id = parameters.id;

                PaymentQuery result = paymentManager.getUserPayment(id);

                if (result != null)
                {
                    if(result.paymentBillID!=-1){
                        return Response.AsJson(result);
                    }
                    else
                    {
                        return Response.AsJson("");
                    }

                }

                else
                {
                    return HttpStatusCode.Conflict;
                }

            };

            Get["/GetPayment/{id:long}"] = parameters =>
            {
                long id = parameters.id;

                PaymentQuery result = paymentManager.getPayment(id);

                if (result != null)
                {
                    return Response.AsJson(result);
                }

                else
                {
                    return HttpStatusCode.Conflict;
                }

            };

            Get["/getsponsorpayments/{id:long}"] = parameters =>
            {
                long id = parameters.id;

                List<PaymentQuery> result = paymentManager.getSponsorPayments(id);

                if (result != null)
                {
                    return Response.AsJson(result);
                }

                else
                {
                    return HttpStatusCode.Conflict;
                }

            };
        }
Example #16
0
        private SetExpressCheckoutRequestType populateRequestObject(FinancialGateway financialGateway, PaymentInfo paymentInfo, List <GatewayAccountItem> selectedAccounts)
        {
            SetExpressCheckoutRequestType        request   = new SetExpressCheckoutRequestType();
            SetExpressCheckoutRequestDetailsType ecDetails = new SetExpressCheckoutRequestDetailsType();
            String host      = GlobalAttributesCache.Value("PublicApplicationRoot");
            int    lastSlash = host.LastIndexOf('/');

            host = (lastSlash > -1) ? host.Substring(0, lastSlash) : host;
            if (financialGateway.GetAttributeValue("ReturnPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("ReturnPage"));
                ecDetails.ReturnURL = host + pageReference.BuildUrl();
            }
            if (financialGateway.GetAttributeValue("CancelPage") != string.Empty)
            {
                PageReference pageReference = new PageReference(financialGateway.GetAttributeValue("CancelPage"));
                ecDetails.CancelURL = host + pageReference.BuildUrl();
            }

            /*
             * // (Optional) Email address of the buyer as entered during checkout. PayPal uses this value to pre-fill the PayPal membership sign-up portion on the PayPal pages.
             * if (buyerEmail.Value != string.Empty)
             * {
             *
             * }*/
            ecDetails.BuyerEmail = paymentInfo.Email;

            /* Populate payment requestDetails.
             * SetExpressCheckout allows parallel payments of upto 10 payments.
             * This samples shows just one payment.
             */
            PaymentDetailsType paymentDetails = new PaymentDetailsType();

            ecDetails.PaymentDetails.Add(paymentDetails);
            // (Required) Total cost of the transaction to the buyer. If shipping cost and tax charges are known, include them in this value. If not, this value should be the current sub-total of the order. If the transaction includes one or more one-time purchases, this field must be equal to the sum of the purchases. Set this field to 0 if the transaction does not include a one-time purchase such as when you set up a billing agreement for a recurring payment that is not immediately charged. When the field is set to 0, purchase-specific fields are ignored.
            double orderTotal = 0.0;
            // Sum of cost of all items in this order. For digital goods, this field is required.
            double           itemTotal = Convert.ToDouble(paymentInfo.Amount);
            CurrencyCodeType currency  = CurrencyCodeType.USD;

            //(Optional) Description of items the buyer is purchasing.
            paymentDetails.OrderDescription = "Contribution";

            // We do a authorization then complete the sale in the "Charge" phase
            paymentDetails.PaymentAction = PaymentActionCodeType.AUTHORIZATION;
            foreach (GatewayAccountItem item in selectedAccounts)
            {
                if (item.Amount > 0)
                {
                    PaymentDetailsItemType itemDetails = new PaymentDetailsItemType();

                    itemDetails.Name        = item.Name;
                    itemDetails.Amount      = new BasicAmountType(currency, item.Amount.ToString());
                    itemDetails.Quantity    = 1;
                    itemDetails.Description = item.PublicName;
                    itemDetails.Number      = item.Id.ToString();
                    paymentDetails.PaymentDetailsItem.Add(itemDetails);
                }
            }

            orderTotal += itemTotal;
            paymentDetails.ItemTotal  = new BasicAmountType(currency, itemTotal.ToString());
            paymentDetails.OrderTotal = new BasicAmountType(currency, orderTotal.ToString());

            //(Optional) Your URL for receiving Instant Payment Notification (IPN)
            //about this transaction. If you do not specify this value in the request,
            //the notification URL from your Merchant Profile is used, if one exists.
            //Important:
            //The notify URL applies only to DoExpressCheckoutPayment.
            //This value is ignored when set in SetExpressCheckout or GetExpressCheckoutDetails.
            //Character length and limitations: 2,048 single-byte alphanumeric characters
            paymentDetails.NotifyURL = "";
            // ipnNotificationUrl.Value.Trim();

            //(Optional) Locale of pages displayed by PayPal during Express Checkout.

            /*if (localeCode.SelectedIndex != 0)
             * {
             *  ecDetails.LocaleCode = localeCode.SelectedValue;
             * }
             *
             * // (Optional) Name of the Custom Payment Page Style for payment pages associated with this button or link. It corresponds to the HTML variable page_style for customizing payment pages. It is the same name as the Page Style Name you chose to add or edit the page style in your PayPal Account profile.
             * if (pageStyle.Value != string.Empty)
             * {
             *  ecDetails.PageStyle = pageStyle.Value;
             * }*/
            //(Optional) 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 displays.
            if (financialGateway.GetAttributeValue("PayPalLogoImage") != string.Empty)
            {
                ecDetails.cppHeaderImage = financialGateway.GetAttributeValue("PayPalLogoImage");
            }

            /*// (Optional) 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.
             * if (cppheaderbordercolor.Value != string.Empty)
             * {
             *  ecDetails.cppHeaderBorderColor = cppheaderbordercolor.Value;
             * }
             * // (Optional) Sets the background color for the header of the payment page. By default, the color is white.
             * if (cppheaderbackcolor.Value != string.Empty)
             * {
             *  ecDetails.cppHeaderBackColor = cppheaderbackcolor.Value;
             * }
             * // (Optional) Sets the background color for the payment page. By default, the color is white.
             * if (cpppayflowcolor.Value != string.Empty)
             * {
             *  ecDetails.cppPayflowColor = cpppayflowcolor.Value;
             * }
             * // (Optional) A label that overrides the business name in the PayPal account on the PayPal hosted checkout pages.
             */
            if (financialGateway.GetAttributeValue("PayPalBrandName") != string.Empty)
            {
                ecDetails.BrandName = financialGateway.GetAttributeValue("PayPalBrandName");
            }

            request.SetExpressCheckoutRequestDetails = ecDetails;

            return(request);
        }
        private void btnBookRoom_Click(object sender, EventArgs e)
        {
            if (_dictPassengers.Count > 0)
            {
                Package packageInfo = (Package)cmbPackage.SelectedItem;

                string from = packageInfo.From;
                string to = packageInfo.To;
                DateTime flightDepartureDate = (DateTime)dgvFlightInformation["DepartureTime", dgvFlightInformation.CurrentRow.Index].Value;
                DateTime end = flightDepartureDate.AddDays(packageInfo.Duration);

                PassengerInfo[] passengers = new PassengerInfo[_dictPassengers.Count];
                int i = 0;
                Dictionary<string, PassengerInfo>.Enumerator enumerator = _dictPassengers.GetEnumerator();
                while (enumerator.MoveNext())
                    passengers[i++] = enumerator.Current.Value;

                PaymentInfo payment = new PaymentInfo();
                payment.cardholdername = txtHolderName.Text;
                payment.cardname = txtCardName.Text;
                payment.cv2 = txtCardPin.Text;
                payment.expiryDate = dtpCardExpiry.Value;

                FBooking.FlightBookingServiceClient flightBooking = new FlightBookingServiceClient();

                using (TransactionScope ts = new TransactionScope())
                {
                    try
                    {
                        if (flightBooking.checkAvailability(from, to, flightDepartureDate, passengers.Length))
                        {
                            MessageBox.Show("Flight Seats Available...");

                            if (flightBooking.makeReservation(from, to, flightDepartureDate, passengers, payment))
                                MessageBox.Show("Flight Reservation Successful...");
                            else
                                throw new Exception("Flight Reservation unsuccessful...");
                        }
                        else
                            throw new Exception("Seats Unavailable...");

                        string cartType = txtCardType.Text;
                        string guestAccount = txtGuestAccount.Text;
                        string guestName = txtGuestName.Text;
                        string guestPassport = txtGuestPassport.Text;
                        int duration = packageInfo.Duration;
                        int numberOfGuest = _dictPassengers.Count;
                        string roomNo = (string)dgvRoomDetails["roomNo", dgvRoomDetails.CurrentRow.Index].Value;
                        if (_hotelBooking.checkRoomAvailability(roomNo, dtpStartDate.Value.ToString(), duration))
                        {
                            MessageBox.Show("Hotel Room Available...");

                            MessageBox.Show(_hotelBooking.makeRoomReservation(cartType, guestAccount, guestName, guestPassport, duration, numberOfGuest, roomNo, dtpStartDate.Value.ToString(), ""));
                        }
                        else
                            throw new Exception("Hotel Room Unavailable..");

                        ts.Complete();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                        return;
                    }
                }
            }
        }
Example #18
0
        private TransactionResponse ChargeCreditCardVault(Guid vaultGuid, Person person, PaymentInfo paymentInfo, decimal amount, int tranid)
        {
            var creditCardVaultSaleRequest = new CreditCardVaultSaleRequest(_id,
                                                                            _key,
                                                                            vaultGuid,
                                                                            $"{paymentInfo.FirstName ?? person.FirstName} {paymentInfo.LastName ?? person.LastName}",
                                                                            new BillingAddress
            {
                Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                City     = paymentInfo.City ?? person.PrimaryCity,
                State    = paymentInfo.State ?? person.PrimaryState,
                Zip      = paymentInfo.Zip ?? person.PrimaryZip,
                Email    = person.EmailAddress,
                Phone    = paymentInfo.Phone ?? person.HomePhone
            },
                                                                            amount, tranid.ToString(CultureInfo.InvariantCulture),
                                                                            person.PeopleId.ToString(CultureInfo.InvariantCulture));

            var response = creditCardVaultSaleRequest.Execute();

            return(new TransactionResponse
            {
                Approved = response.ApprovalIndicator == ApprovalIndicator.Approved,
                AuthCode = response.Code,
                Message = response.Message,
                TransactionId = response.Reference
            });
        }
Example #19
0
        public void StoreInVault(int peopleId, string type, string cardNumber, string expires, string cardCode, string routing, string account, bool giving)
        {
            var person      = db.LoadPersonById(peopleId);
            var paymentInfo = person.PaymentInfo();

            if (paymentInfo == null)
            {
                paymentInfo = new PaymentInfo();
                person.PaymentInfos.Add(paymentInfo);
            }

            if (type == PaymentType.CreditCard)
            {
                if (paymentInfo.SageCardGuid == null) // create new vault.
                {
                    paymentInfo.SageCardGuid = CreateCreditCardVault(person, cardNumber, expires);
                }
                else
                {
                    // update existing vault.
                    // check for updating the entire card or only expiration.
                    if (!cardNumber.StartsWith("X"))
                    {
                        UpdateCreditCardVault(paymentInfo.SageCardGuid.GetValueOrDefault(), person, cardNumber, expires);
                    }
                    else
                    {
                        UpdateCreditCardVault(paymentInfo.SageCardGuid.GetValueOrDefault(), person, expires);
                    }
                }

                paymentInfo.MaskedCard = Util.MaskCC(cardNumber);
                paymentInfo.Expires    = expires;
            }
            else if (type == PaymentType.Ach)
            {
                if (paymentInfo.SageBankGuid == null) // create new vault
                {
                    paymentInfo.SageBankGuid = CreateAchVault(person, account, routing);
                }
                else
                {
                    // we can only update the ach account if there is a full account number.
                    if (!account.StartsWith("X"))
                    {
                        UpdateAchVault(paymentInfo.SageBankGuid.GetValueOrDefault(), person, account, routing);
                    }
                }

                paymentInfo.MaskedAccount = Util.MaskAccount(account);
                paymentInfo.Routing       = Util.Mask(new StringBuilder(routing), 2);
            }
            else
            {
                throw new ArgumentException($"Type {type} not supported", nameof(type));
            }

            if (giving)
            {
                paymentInfo.PreferredGivingType = type;
            }
            else
            {
                paymentInfo.PreferredPaymentType = type;
            }
            db.SubmitChanges();
        }
Example #20
0
 protected void btnok_Click(object sender, System.EventArgs e)
 {
     if (base.Action.Equals(ActionType.Add.ToString()) && !base.IsAuthorizedOp(ActionType.Add.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else if (base.Action.Equals(ActionType.Modify.ToString()) && !base.IsAuthorizedOp(ActionType.Modify.ToString()))
     {
         base.ShowMsg("Không có thẩm quyền");
     }
     else
     {
         PaymentInfo paymentInfo = new PaymentInfo();
         if (base.IsEdit)
         {
             paymentInfo = Payment.GetDataById(base.OpID);
         }
         System.Text.StringBuilder stringBuilder = new System.Text.StringBuilder();
         string[] array = base.Request.Form["p-key"].Split(new char[]
         {
             ','
         });
         string[] array2 = base.Request.Form["p-value"].Split(new char[]
         {
             ','
         });
         for (int i = 0; i < array.Length; i++)
         {
             if (!string.IsNullOrEmpty(array[i]))
             {
                 stringBuilder.Append(array[i] + ":\"" + array2[i] + "\",");
             }
         }
         paymentInfo.ParametersValue = "{" + stringBuilder.ToString().Trim().TrimEnd(new char[]
         {
             ','
         }) + "}";
         if (base.Action.Equals(ActionType.Add.ToString()))
         {
             paymentInfo.PayCode       = this.DropDownList1.SelectedValue;
             paymentInfo.AutoTimeStamp = System.DateTime.Now;
             if (Payment.Exists(paymentInfo.PayCode))
             {
                 base.ShowMsg("支付方式已存在!");
             }
             else if (Payment.Add(paymentInfo) > 0)
             {
                 PageBase.log.AddEvent(base.LoginAccount.AccountName, "添加支付[" + paymentInfo.DisplayName + "] thành công");
                 base.Response.Redirect(string.Concat(new object[]
                 {
                     "MobilePaySet.aspx?CatalogID=",
                     base.CurrentCatalogID,
                     "&Module=",
                     base.CurrentModuleCode,
                     "&action=View"
                 }));
             }
             else
             {
                 base.ShowMsg("Thao tác thất bại");
             }
         }
         if (base.Action.Equals(ActionType.Modify.ToString()))
         {
             if (Payment.Update(paymentInfo))
             {
                 PageBase.log.AddEvent(base.LoginAccount.AccountName, "修改支付[" + paymentInfo.DisplayName + "] thành công");
                 base.Response.Redirect(string.Concat(new object[]
                 {
                     "MobilePaySet.aspx?CatalogID=",
                     base.CurrentCatalogID,
                     "&Module=",
                     base.CurrentModuleCode,
                     "&action=View"
                 }));
             }
             else
             {
                 base.ShowMsg("Thao tác thất bại");
             }
         }
     }
 }
Example #21
0
        /// <summary>
        /// Authorizes the specified payment info.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Authorize(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;
            Response ppResponse = null;

            var invoice = GetInvoice(paymentInfo);

            BrowserInfo browser = new BrowserInfo();

            browser.ButtonSource = "SparkDevelopmentNetwork_SP";
            invoice.BrowserInfo  = browser;

            var tender = GetTender(paymentInfo);

            if (tender != null)
            {
                if (paymentInfo is ReferencePaymentInfo)
                {
                    var reference     = paymentInfo as ReferencePaymentInfo;
                    var ppTransaction = new ReferenceTransaction("Authorization", reference.TransactionCode, GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
                else
                {
                    var ppTransaction = new AuthorizationTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
            }
            else
            {
                errorMessage = "Could not create tender from PaymentInfo";
            }

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        var transaction = new FinancialTransaction();
                        transaction.TransactionCode = txnResponse.Pnref;
                        return(transaction);
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }
Example #22
0
        /// <summary>
        /// Updates the scheduled payment.
        /// </summary>
        /// <param name="transaction">The transaction.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override bool UpdateScheduledPayment(FinancialScheduledTransaction transaction, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            RecurringModifyTransaction ppTransaction = null;
            var financialGateway = GetFinancialGateway(transaction);

            if (paymentInfo != null)
            {
                ppTransaction = new RecurringModifyTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), GetRecurring(transaction), GetInvoice(paymentInfo), GetTender(paymentInfo), PayflowUtility.RequestId);
            }
            else
            {
                ppTransaction = new RecurringModifyTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), GetRecurring(transaction), PayflowUtility.RequestId);
            }

            var ppResponse = ppTransaction.SubmitTransaction();

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        RecurringResponse recurringResponse = ppResponse.RecurringResponse;
                        if (recurringResponse != null)
                        {
                            return(true);
                        }
                        else
                        {
                            errorMessage = "Invalid recurring response from the financial gateway";
                        }
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(false);
        }
Example #23
0
 public Checkout()
 {
     BillingInfo = new BillingInfo();
     PaymentInfo = new PaymentInfo();
 }
        /// <summary>
        /// 诊所提现审核
        /// </summary>
        /// <param name="Id">审核ID</param>
        /// <param name="status">审核状态</param>
        /// <param name="Remark">平台备注</param>
        /// <param name="IpAddress">操作IP</param>
        /// <param name="UserName">操作人名称</param>
        /// <returns></returns>
        public static bool ShopApplyWithDraw(long Id, Himall.CommonModel.WithdrawStaus status, string Remark, string IpAddress = "", string UserName = "")
        {
            var model = _iBillingService.GetShopWithDrawInfo(Id);

            if (status == Himall.CommonModel.WithdrawStaus.Refused)//拒绝
            {
                model.Status     = status;
                model.PlatRemark = Remark;
                model.DealTime   = DateTime.Now;
                _iBillingService.UpdateShopWithDraw(model);

                lock (obj)
                {
                    //处理余额
                    var mShopAccountInfo = _iBillingService.GetShopAccount(model.ShopId);
                    mShopAccountInfo.Balance += model.CashAmount;
                    _iBillingService.UpdateShopAccount(mShopAccountInfo);
                }


                //操作日志
                OperationLogApplication.AddPlatformOperationLog(
                    new LogInfo
                {
                    Date        = DateTime.Now,
                    Description = string.Format("诊所提现拒绝,诊所Id={0},状态为:{1}, 说明是:{2}", model.ShopId,
                                                status, Remark),
                    IPAddress = IpAddress,
                    PageUrl   = "/Admin/ShopWithDraw/Management",
                    UserName  = UserName,
                    ShopId    = 0
                });
                return(true);
            }
            else if (model.CashType == Himall.CommonModel.WithdrawType.BankCard)//银行卡
            {
                model.Status     = status;
                model.PlatRemark = Remark;
                model.DealTime   = DateTime.Now;
                _iBillingService.UpdateShopWithDraw(model);
                //资金处理
                UpdateAccount(model.ShopId, model.CashAmount, Himall.CommonModel.ShopAccountType.WithDraw, DateTime.Now.ToString("yyyyMMddHHmmssffff"), "银行卡提现", Id);


                //操作日志
                OperationLogApplication.AddPlatformOperationLog(
                    new LogInfo
                {
                    Date        = DateTime.Now,
                    Description = string.Format("诊所银行卡提现审核成功,诊所Id={0},状态为:{1}, 说明是:{2}", model.ShopId,
                                                status, Remark),
                    IPAddress = IpAddress,
                    PageUrl   = "/Admin/ShopWithDraw/Management",
                    UserName  = UserName,
                    ShopId    = 0
                });
                return(true);
            }
            else
            {
                var plugins = PluginsManagement.GetPlugins <IPaymentPlugin>(true).Where(e => e.PluginInfo.PluginId.ToLower().Contains("weixin")).FirstOrDefault();
                if (plugins != null)
                {
                    try
                    {
                        var shopModel          = ShopApplication.GetShop(model.ShopId);
                        EnterprisePayPara para = new EnterprisePayPara()
                        {
                            amount       = model.CashAmount,
                            check_name   = false,
                            openid       = shopModel.WeiXinOpenId,
                            out_trade_no = model.CashNo.ToString(),
                            desc         = "提现"
                        };
                        PaymentInfo result = plugins.Biz.EnterprisePay(para);

                        model.SerialNo   = result.TradNo;
                        model.DealTime   = DateTime.Now;
                        model.Status     = WithdrawStaus.Succeed;
                        model.PlatRemark = Remark;
                        _iBillingService.UpdateShopWithDraw(model);
                        //资金处理
                        UpdateAccount(model.ShopId, model.CashAmount, Himall.CommonModel.ShopAccountType.WithDraw, result.TradNo, "微信提现", Id);

                        //操作日志
                        OperationLogApplication.AddPlatformOperationLog(
                            new LogInfo
                        {
                            Date        = DateTime.Now,
                            Description = string.Format("诊所微信提现审核成功,诊所Id={0},状态为:{1}, 说明是:{2}", model.ShopId,
                                                        status, Remark),
                            IPAddress = IpAddress,
                            PageUrl   = "/Admin/ShopWithDraw/Management",
                            UserName  = UserName,
                            ShopId    = 0
                        });

                        return(true);
                    }
                    catch (Exception ex)
                    {
                        Log.Error("调用企业付款接口异常:" + ex.Message);
                        model.Status     = WithdrawStaus.Fail;
                        model.PlatRemark = Remark;
                        model.DealTime   = DateTime.Now;
                        _iBillingService.UpdateShopWithDraw(model);

                        //操作日志
                        OperationLogApplication.AddPlatformOperationLog(
                            new LogInfo
                        {
                            Date        = DateTime.Now,
                            Description = string.Format("诊所微信提现审核失败,诊所Id={0},状态为:{1}, 说明是:{2}", model.ShopId,
                                                        status, Remark),
                            IPAddress = IpAddress,
                            PageUrl   = "/Admin/ShopWithDraw/Management",
                            UserName  = UserName,
                            ShopId    = 0
                        });
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
        }
Example #25
0
        private TransactionResponse ChargeAchVault(Guid vaultGuid, Person person, PaymentInfo paymentInfo, decimal amount, int tranid)
        {
            var achVaultSaleRequest = new AchVaultSaleRequest(_id,
                _key,
                _originatorId,
                vaultGuid,
                paymentInfo.FirstName ?? person.FirstName,
                (paymentInfo.MiddleInitial ?? person.MiddleName).Truncate(1) ?? "",
                paymentInfo.LastName ?? person.LastName,
                paymentInfo.Suffix ?? person.SuffixCode,
                new BillingAddress
                {
                    Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                    City = paymentInfo.City ?? person.PrimaryCity,
                    State = paymentInfo.State ?? person.PrimaryState,
                    Zip = paymentInfo.Zip ?? person.PrimaryZip,
                    Email = person.EmailAddress,
                    Phone = paymentInfo.Phone ?? person.HomePhone
                },
                amount, tranid.ToString(CultureInfo.InvariantCulture));

            var response = achVaultSaleRequest.Execute();

            return new TransactionResponse
            {
                Approved = response.ApprovalIndicator == ApprovalIndicator.Approved,
                AuthCode = response.Code,
                Message = response.Message,
                TransactionId = response.Reference
            };
        }
Example #26
0
 /// <summary>
 /// Process recurring payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NotImplementedException();
 }
Example #27
0
        private void SaveAccount(ClientLogic clientLogic, AccountViewModel account, MembershipUser user, bool insert)
        {
            // Call business logic to insert the data.
            // todo: move to mapping
            CityStateZip cityStateZip = new CityStateZip
            {
                City = account.City,
                State = account.State,
                ZipCode = account.ZipCode
            };
            this.AddCityStateZipToAccount(account, cityStateZip);

            PaymentInfo paymentInfo = new PaymentInfo
            {
                AmazonToken = User.Identity.Name
            };
            this.AddPaymentInfoToAccount(account, paymentInfo);

            Client client = new Client();
            client.ClientName = account.ClientName;
            client.PhoneNumber = account.PhoneNumber;
            client.Email = user.UserName;
            client.Address = account.Address;
            client.CityStateZipGuid = account.CityStateZipGuid;
            client.PaymentInfoGuid = account.PaymentInfoGuid;
            // pause account - in create view is always false
            client.AccountPaused = account.PauseAccount;
            if (insert)
            {
                if (SessionHandler.Current.GitAssertion != null)
                {
                    GitAssertion assertion = SessionHandler.Current.GitAssertion;
                    client.FederatedIDProvider = assertion.Authority;
                    client.FederatedID = assertion.Identifier;
                    client.FederatedKey = user.ProviderUserKey.ToString();
                }

                client = clientLogic.InsertClient(client);
                account.ClientGuid = client.ClientGuid;
                account.ClientID = client.ClientID;
            }
            else
            {
                client.IsWaiverd = account.IsWaiverd;
                client.FreeDays = account.FreeDays;
                client.Credits = account.AccountBalance;
                client.IsSuspended = account.IsSuspended;
                client.IsActive = account.IsActive;
                client.ClientGuid = account.ClientGuid; // Had to add this......
                clientLogic.UpdateClient(client);
            }
        }
Example #28
0
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     processPaymentResult.PaymentStatus = PaymentStatusEnum.Pending;
 }
Example #29
0
        public void StoreInVault(int peopleId, string type, string cardNumber, string expires, string cardCode,
            string routing, string account, bool giving)
        {
            var person = db.LoadPersonById(peopleId);
            var paymentInfo = person.PaymentInfo();
            if (paymentInfo == null)
            {
                paymentInfo = new PaymentInfo();
                person.PaymentInfos.Add(paymentInfo);
            }

            var billToAddress = new AuthorizeNet.Address
            {
                First = paymentInfo.FirstName ?? person.FirstName,
                Last = paymentInfo.LastName ?? person.LastName,
                Street = paymentInfo.Address ?? person.PrimaryAddress,
                City = paymentInfo.City ?? person.PrimaryCity,
                State = paymentInfo.State ?? person.PrimaryState,
                Country = paymentInfo.Country ?? person.PrimaryCountry,
                Zip = paymentInfo.Zip ?? person.PrimaryZip,
                Phone = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone
            };

            Customer customer;

            if (paymentInfo.AuNetCustId == null) // create a new profilein Authorize.NET CIM
            {
                // NOTE: this can throw an error if the email address already exists...
                // TODO: Authorize.net needs to release a new Nuget package, because they don't have a clean way to pass in customer ID (aka PeopleId) yet... the latest code has a parameter for this, though
                //       - we could call UpdateCustomer after the fact to do this if we wanted to
                customer = CustomerGateway.CreateCustomer(person.EmailAddress, person.Name);
                customer.ID = peopleId.ToString();

                paymentInfo.AuNetCustId = customer.ProfileID.ToInt();
            }
            else
            {
                customer = CustomerGateway.GetCustomer(paymentInfo.AuNetCustId.ToString());
            }

            customer.BillingAddress = billToAddress;
            var isSaved = CustomerGateway.UpdateCustomer(customer);
            if (!isSaved)
                throw new Exception($"UpdateCustomer failed to save for {peopleId}");

            if (type == PaymentType.Ach)
            {
                SaveECheckToProfile(routing, account, paymentInfo, customer);

                paymentInfo.MaskedAccount = Util.MaskAccount(account);
                paymentInfo.Routing = Util.Mask(new StringBuilder(routing), 2);
            }
            else if (type == PaymentType.CreditCard)
            {
                var normalizeExpires = DbUtil.NormalizeExpires(expires);
                if (normalizeExpires == null)
                    throw new ArgumentException($"Can't normalize date {expires}", nameof(expires));

                var expiredDate = normalizeExpires.Value;

                SaveCreditCardToProfile(cardNumber, cardCode, expiredDate, paymentInfo, customer);

                paymentInfo.MaskedCard = Util.MaskCC(cardNumber);
                paymentInfo.Expires = expires;
            }
            else
                throw new ArgumentException($"Type {type} not supported", nameof(type));

            if (giving)
                paymentInfo.PreferredGivingType = type;
            else
                paymentInfo.PreferredPaymentType = type;

            db.SubmitChanges();
        }
Example #30
0
        protected override IProcessPathGenerator Build(Hw1Model model, Market market, PaymentInfo probaMeasure, DateTime[] simulatedDates)
        {
            var dates             = model.Time[simulatedDates];
            var drift             = Drift(model, probaMeasure);
            var ornsteinUhlenbeck = new OrnsteinUhlenbeck(model.MeanReversion, drift, model.Sigma, 0.0);

            return(OrnsteinUhlenbeck1DGeneratorFactory.Build(dates, ornsteinUhlenbeck));
        }
Example #31
0
        public String SubmitRechargeInfo(String paymentId, String amount, String paymentTime)
        {
            OAuthTokenCredential oa = new OAuthTokenCredential("AQmW6s0chChHeblhmaIYQda6Bn1gmfSSUnvUCHNCLZM_7BiLOb5BMrINuIxUswdG8Prb8K3ktHQpZuho", "ENQKqkutUnKuTGBWiNDvJ_sA131lwCU4c1eaJwFcn58M88LtjHJd9TLgvjT4nuXkruuSkD0OF0u_XP_W");


            PayPal.Api.APIContext apiContext = new PayPal.Api.APIContext(oa.GetAccessToken());

            try
            {
                Payment payment = PayPal.Api.Payment.Get(apiContext, paymentId);

                if (payment == null || String.IsNullOrEmpty(payment.id))
                {
                    return("11");
                }
            }
            catch (Exception ex)
            {
                return("11");
            }

            LoginViewModel user = Utils.GetUserInfo();

            PaymentInfo pInfo = null;

            using (DSLEntities entity = new DSLEntities())
            {
                pInfo = entity.PaymentInfo.Where(a => a.UserId.ToString() == user.UserId && a.PaymentId == paymentId).ToList().FirstOrDefault();
            }

            if (pInfo != null)
            {
                return("1");
            }



            UserInfo existingData = null;


            using (DSLEntities entity = new DSLEntities())
            {
                existingData = entity.UserInfo.Where(a => a.UserId.ToString() == user.UserId).ToList().FirstOrDefault();
            }

            if (existingData != null)
            {
                using (DSLEntities entity = new DSLEntities())
                {
                    existingData.Balance            += decimal.Parse(amount);
                    entity.Entry(existingData).State = System.Data.Entity.EntityState.Modified;
                    entity.SaveChanges();
                }
            }

            PaymentInfo addPayInfo = new PaymentInfo();

            addPayInfo.Amount       = Decimal.Parse(amount);
            addPayInfo.PaymentId    = paymentId;
            addPayInfo.PaymentState = "Approval";
            addPayInfo.PaymentType  = "PayPal";
            addPayInfo.UserId       = int.Parse(user.UserId);
            addPayInfo.PaymentTime  = DateTime.Parse(paymentTime);



            using (DSLEntities entity = new DSLEntities())
            {
                entity.PaymentInfo.Add(addPayInfo);
                entity.SaveChanges();
            }


            return("0");
        }
 /// <summary>
 /// Process payment
 /// </summary>
 /// <param name="paymentInfo">Payment info required for an order processing</param>
 /// <param name="customer">Customer</param>
 /// <param name="orderGuid">Unique order identifier</param>
 /// <param name="processPaymentResult">Process payment result</param>
 public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid orderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     DoExpressCheckout(paymentInfo, orderGuid, processPaymentResult);
 }
Example #33
0
        private int CreateCreditCardVault(Person person, PaymentInfo paymentInfo, string cardNumber, string expiration)
        {
            var createCreditCardVaultRequest = new CreateCreditCardVaultRequest(
                _userName,
                _password,
                new CreditCard
                {
                    CardNumber = cardNumber,
                    Expiration = expiration,
                    BillingAddress = new BillingAddress
                    {
                        FirstName = paymentInfo.FirstName ?? person.FirstName,
                        LastName = paymentInfo.LastName ?? person.LastName,
                        Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                        City = paymentInfo.City ?? person.PrimaryCity,
                        State = paymentInfo.State ?? person.PrimaryState,
                        Zip = paymentInfo.Zip ?? person.PrimaryZip,
                        Email = person.EmailAddress,
                        Phone = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone
                    }
                });

            var response = createCreditCardVaultRequest.Execute();
            if (response.ResponseStatus != ResponseStatus.Approved)
                throw new Exception(
                    $"TransNational failed to create the credit card for people id: {person.PeopleId}, responseCode: {response.ResponseCode}, responseText: {response.ResponseText}");

            return response.VaultId.ToInt();
        }
Example #34
0
 public override IInstructionHandler Create(PaymentInfo pay, IDataService service) => new FaxInstructionHandlerManager(pay, service);
Example #35
0
 /// <summary>
 /// Adds the scheduled payment.
 /// </summary>
 /// <param name="financialGateway">The financial gateway.</param>
 /// <param name="schedule">The schedule.</param>
 /// <param name="paymentInfo">The payment info.</param>
 /// <param name="errorMessage">The error message.</param>
 /// <returns></returns>
 public override FinancialScheduledTransaction AddScheduledPayment(FinancialGateway financialGateway, PaymentSchedule schedule, PaymentInfo paymentInfo, out string errorMessage)
 {
     // Just do nothing here.  It's not supported!
     errorMessage = "";
     return(null);
 }
Example #36
0
 public FlavorChoice(PaymentInfo payment, string selection) : base(payment, selection)
 {
 }
 /// <summary>
 /// Removes PaymentInfo from the collection.
 /// </summary>
 /// <param name="paymentInfo">The paymentInfo to remove.</param>
 public void Remove(PaymentInfo paymentInfo)
 {
     List.Remove(paymentInfo);
 }
Example #38
0
 public void ProcessRecurringPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
 {
     throw new NopException("Recurring payments not supported");
 }
Example #39
0
 public void decrypt(int DS, PaymentInfo PI, int OIMD)
 {
 }
Example #40
0
        /// <summary>
        /// Process payment
        /// </summary>
        /// <param name="paymentInfo">Payment info required for an order processing</param>
        /// <param name="customer">Customer</param>
        /// <param name="OrderGuid">Unique order identifier</param>
        /// <param name="processPaymentResult">Process payment result</param>
        public void ProcessPayment(PaymentInfo paymentInfo, Customer customer, Guid OrderGuid, ref ProcessPaymentResult processPaymentResult)
        {
            TransactMode transactionMode = GetCurrentTransactionMode();

            var usaepay = new USAePayAPI.USAePay();

            usaepay.SourceKey = sourceKey;
            usaepay.Pin       = pin;

            usaepay.OrderID        = OrderGuid.ToString();
            usaepay.Amount         = paymentInfo.OrderTotal;
            usaepay.CardNumber     = paymentInfo.CreditCardNumber;
            usaepay.CardHolder     = paymentInfo.CreditCardName;
            usaepay.CardExp        = GetCardExp(paymentInfo.CreditCardExpireMonth, paymentInfo.CreditCardExpireYear);
            usaepay.BillingStreet  = paymentInfo.BillingAddress.Address1;
            usaepay.BillingStreet2 = paymentInfo.BillingAddress.Address2;
            usaepay.BillingCity    = paymentInfo.BillingAddress.City;
            if (paymentInfo.BillingAddress.StateProvince != null)
            {
                usaepay.BillingState = paymentInfo.BillingAddress.StateProvince.Abbreviation;
            }
            usaepay.BillingZip       = paymentInfo.BillingAddress.ZipPostalCode;
            usaepay.BillingFirstName = paymentInfo.BillingAddress.FirstName;
            usaepay.BillingLastName  = paymentInfo.BillingAddress.LastName;
            usaepay.BillingCompany   = paymentInfo.BillingAddress.Company;

            if (paymentInfo.ShippingAddress != null)
            {
                usaepay.ShippingFirstName = paymentInfo.ShippingAddress.FirstName;
                usaepay.ShippingLastName  = paymentInfo.ShippingAddress.LastName;
                usaepay.ShippingStreet    = paymentInfo.ShippingAddress.Address1;
                usaepay.ShippingStreet2   = paymentInfo.ShippingAddress.Address2;
                usaepay.ShippingCity      = paymentInfo.ShippingAddress.City;
                if (paymentInfo.ShippingAddress.StateProvince != null)
                {
                    usaepay.ShippingState = paymentInfo.ShippingAddress.StateProvince.Abbreviation;
                }
                usaepay.ShippingZip     = paymentInfo.ShippingAddress.ZipPostalCode;
                usaepay.ShippingCompany = paymentInfo.ShippingAddress.Company;
            }

            try
            {
                if (transactionMode == TransactMode.Authorize)
                {
                    usaepay.AuthOnly();
                }
                else
                {
                    usaepay.Sale();
                }


                switch (usaepay.ResultCode)
                {
                case "A":
                    processPaymentResult.PaymentStatus = transactionMode == TransactMode.Authorize ? PaymentStatusEnum.Authorized : PaymentStatusEnum.Paid;
                    processPaymentResult.AVSResult     = usaepay.AvsResult;
                    processPaymentResult.AuthorizationTransactionCode = usaepay.AuthCode;
                    processPaymentResult.AuthorizationTransactionId   = usaepay.RefNum;
                    break;

                case "D":
                    processPaymentResult.Error     = "Declined: " + usaepay.ErrorMesg;
                    processPaymentResult.FullError = "Declined : " + usaepay.ErrorMesg;
                    break;

                default:
                    processPaymentResult.Error     = "Error during checkout";
                    processPaymentResult.FullError = "Error during checkout: " + usaepay.ErrorMesg;
                    break;
                }
            }
            catch (Exception)
            {
                processPaymentResult.Error     = "Error during checkout";
                processPaymentResult.FullError = "Error during checkout";
            }
        }
Example #41
0
        private TransactionResponse ChargeCreditCardVault(Guid vaultGuid, Person person, PaymentInfo paymentInfo, decimal amount, int tranid)
        {
            var creditCardVaultSaleRequest = new CreditCardVaultSaleRequest(_id,
                _key,
                vaultGuid,
                $"{paymentInfo.FirstName ?? person.FirstName} {paymentInfo.LastName ?? person.LastName}",
                new BillingAddress
                {
                    Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                    City = paymentInfo.City ?? person.PrimaryCity,
                    State = paymentInfo.State ?? person.PrimaryState,
                    Zip = paymentInfo.Zip ?? person.PrimaryZip,
                    Email = person.EmailAddress,
                    Phone = paymentInfo.Phone ?? person.HomePhone
                },
                amount, tranid.ToString(CultureInfo.InvariantCulture),
                person.PeopleId.ToString(CultureInfo.InvariantCulture));

            var response = creditCardVaultSaleRequest.Execute();

            return new TransactionResponse
            {
                Approved = response.ApprovalIndicator == ApprovalIndicator.Approved,
                AuthCode = response.Code,
                Message = response.Message,
                TransactionId = response.Reference
            };
        }
    /// <summary>
    /// Executes the reserve operation.
    /// </summary>
    /// <param name="paymentInfo">The payment info.</param>
    public void ExecuteReserve(PaymentInfo paymentInfo)
    {
        m_orderID.Value = paymentInfo.OrderID;
        m_paymentInfoID.Value = paymentInfo.ID;
        m_paymentMode.Value = ExecutePaymentMode.Reserve;

        c_commit.Text = ReserveTranslation;

        InitAddress(paymentInfo.Order, paymentInfo);
        c_textboxSSN.Text = string.Empty;

        PaymentMethod paymentMethod = (PaymentMethod)Enum.Parse(typeof(PaymentMethod), paymentInfo.PaymentMethod); ;

        if (paymentMethod == PaymentMethod.KLARNASE || paymentMethod == PaymentMethod.SVEAWPSE || paymentMethod == PaymentMethod.SHBPFINFA)
        {
            AurigaDialog.Visible = true;
        }
        else
        {
            Complete(this, null);
        }
    }
Example #43
0
        /// <summary>
        /// Charges the specified payment info.
        /// </summary>
        /// <param name="financialGateway">The financial gateway.</param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;

            if (!(paymentInfo is PayPalExpress.PayPalPaymentInfo))
            {
                errorMessage = "PaymentInfo object must be of type PayPalPaymentInfo in order to charge a PayPal Express transaction.";
                return(null);
            }
            PayPalPaymentInfo payPalPaymentInfo = (PayPalPaymentInfo)paymentInfo;

            // Create the DoExpressCheckoutPaymentResponseType object
            DoExpressCheckoutPaymentResponseType responseDoExpressCheckoutPaymentResponseType = new DoExpressCheckoutPaymentResponseType();

            try
            {
                // Create the DoExpressCheckoutPaymentReq object
                DoExpressCheckoutPaymentReq doExpressCheckoutPayment = new DoExpressCheckoutPaymentReq();

                DoExpressCheckoutPaymentRequestDetailsType doExpressCheckoutPaymentRequestDetails = new DoExpressCheckoutPaymentRequestDetailsType();

                // The timestamped token value that was returned in the
                // `SetExpressCheckout` response and passed in the
                // `GetExpressCheckoutDetails` request.
                doExpressCheckoutPaymentRequestDetails.Token = payPalPaymentInfo.Token;

                // Unique paypal buyer account identification number as returned in
                // `GetExpressCheckoutDetails` Response
                doExpressCheckoutPaymentRequestDetails.PayerID = payPalPaymentInfo.PayerId;

                // # Payment Information
                // list of information about the payment
                List <PaymentDetailsType> paymentDetailsList = new List <PaymentDetailsType>();

                // information about the first payment
                PaymentDetailsType paymentDetails = new PaymentDetailsType();

                BasicAmountType orderTotal = new BasicAmountType(CurrencyCodeType.USD, paymentInfo.Amount.ToString());
                paymentDetails.OrderTotal = orderTotal;

                // We are actually capturing this payment now.
                paymentDetails.PaymentAction = PaymentActionCodeType.SALE;

                // Unique identifier for the merchant. For parallel payments, this field
                // is required and must contain the Payer Id or the email address of the
                // merchant.
                String            apiUsername   = Encryption.DecryptString(financialGateway.GetAttributeValue("PayPalAPIUsername"));
                SellerDetailsType sellerDetails = new SellerDetailsType();
                sellerDetails.PayPalAccountID = apiUsername;

                paymentDetailsList.Add(paymentDetails);
                doExpressCheckoutPaymentRequestDetails.PaymentDetails = paymentDetailsList;

                DoExpressCheckoutPaymentRequestType doExpressCheckoutPaymentRequest = new DoExpressCheckoutPaymentRequestType(doExpressCheckoutPaymentRequestDetails);
                doExpressCheckoutPayment.DoExpressCheckoutPaymentRequest = doExpressCheckoutPaymentRequest;

                // Create the service wrapper object to make the API call
                PayPalAPIInterfaceServiceService service = new PayPalAPIInterfaceServiceService(GetCredentials(financialGateway));

                // # API call
                // Invoke the DoExpressCheckoutPayment method in service wrapper object
                responseDoExpressCheckoutPaymentResponseType = service.DoExpressCheckoutPayment(doExpressCheckoutPayment);

                if (responseDoExpressCheckoutPaymentResponseType != null)
                {
                    // # Success values
                    if (responseDoExpressCheckoutPaymentResponseType.Ack.ToString().Trim().ToUpper().Equals("SUCCESS"))
                    {
                        // Transaction identification number of the transaction that was
                        // created.
                        // This field is only returned after a successful transaction
                        // for DoExpressCheckout has occurred.
                        if (responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo != null)
                        {
                            IEnumerator <PaymentInfoType> paymentInfoIterator = responseDoExpressCheckoutPaymentResponseType.DoExpressCheckoutPaymentResponseDetails.PaymentInfo.GetEnumerator();
                            while (paymentInfoIterator.MoveNext())
                            {
                                PaymentInfoType ppPaymentInfo = paymentInfoIterator.Current;

                                var transaction = new FinancialTransaction();
                                transaction.TransactionCode = ppPaymentInfo.TransactionID;
                                return(transaction);
                            }
                        }
                    }
                    // # Error Values
                    else
                    {
                        List <ErrorType> errorMessages = responseDoExpressCheckoutPaymentResponseType.Errors;
                        foreach (ErrorType error in errorMessages)
                        {
                            errorMessage += "API Error Message : " + error.LongMessage + "\n";
                        }
                    }
                }
            }
            // # Exception log
            catch (System.Exception ex)
            {
                errorMessage += "Error Message : " + ex.Message;
            }

            return(null);
        }
    private void InitAddress(Order order, PaymentInfo paymentInfo)
    {
        // Fill Delivery Data
        if (order.Deliveries[0] != null)
        {
            c_labelDeliveryFirstName.Text = order.Deliveries[0].Address.FirstName;
            c_labelDeliveryLastName.Text = order.Deliveries[0].Address.LastName;
            c_labelDeliveryAddressRow1.Text = order.Deliveries[0].Address.Address1;
            c_labelDeliveryAddressRow2.Text = order.Deliveries[0].Address.Address2;
            c_labelDeliveryZip.Text = order.Deliveries[0].Address.Zip;
            c_labelDeliveryCity.Text = order.Deliveries[0].Address.City;
            c_labelDeliveryCountry.Text = Litium.Studio.UI.ECommerce.Common.Countries.
                GetCountryNameByKey(order.Deliveries[0].Address.Country);
            c_labelDeliveryPhone.Text = order.Deliveries[0].Address.Phone;
        }
        if (paymentInfo != null)
        {
            c_labelBillingFirstName.Text = paymentInfo.BillingAddress.FirstName;
            c_labelBillingLastName.Text = paymentInfo.BillingAddress.LastName;
            c_labelBillingAddressRow1.Text = paymentInfo.BillingAddress.Address1;
            c_labelBillingAddressRow2.Text = paymentInfo.BillingAddress.Address2;
            c_labelBillingZip.Text = paymentInfo.BillingAddress.Zip;
            c_labelBillingCity.Text = paymentInfo.BillingAddress.City;
            c_labelBillingCountry.Text = Litium.Studio.UI.ECommerce.Common.Countries.GetCountryNameByKey(order.PaymentInfo[0].BillingAddress.Country);
            c_labelBillingPhone.Text = paymentInfo.BillingAddress.Phone;

            // Fill Payment Data
            c_labelAmount.Text = paymentInfo.TotalAmountWithVAT.ToString(ParameterConstants.DECIMAL_FORMAT_STRING);
            c_commit.Text = (m_paymentMode.HasValue && m_paymentMode.Value == ExecutePaymentMode.Reserve) ? ReserveTranslation : ChargeTranslation;
        }
    }
Example #45
0
        private void AddPaymentInfoToAccount(AccountViewModel account, PaymentInfo paymentInfo)
        {
            Common.ValidateArgument<AccountViewModel>(account, "account");
            Common.ValidateArgument<PaymentInfo>(paymentInfo, "paymentInfo");

            PaymentInfoLogic piLogic = new PaymentInfoLogic();
            PaymentInfo existingPaymentInfo = piLogic.GetPaymentInfoByPaymentInfoGuid(paymentInfo.PaymentInfoGuid);
            if (existingPaymentInfo == null || existingPaymentInfo.PaymentInfoGuid == Guid.Empty)
            {
                paymentInfo = piLogic.InsertPaymentInfo(paymentInfo);
            }
            else
            {
                paymentInfo.PaymentInfoGuid = existingPaymentInfo.PaymentInfoGuid;
                piLogic.UpdatePaymentInfo(paymentInfo);
                paymentInfo = piLogic.GetPaymentInfoByPaymentInfoGuid(paymentInfo.PaymentInfoGuid);
            }

            account.PaymentInfoGuid = paymentInfo.PaymentInfoGuid;
        }
Example #46
0
        public PaymentInfo GetUserPaymentInfo(int id)
        {
            PaymentInfo payment = _dbContext.PaymentInfos.Find(id);

            return(payment);
        }
Example #47
0
 private EMKServise.PaymentInfo ConvertPaymentInfo(PaymentInfo c)
 {
     if ((object)c != null)
     {
         EMKServise.PaymentInfo ep = new EMKServise.PaymentInfo();
         ep.HealthCareUnit = c.HealthCareUnit;
         ep.IdPaymentType = c.IdPaymentType;
         ep.PaymentState = c.PaymentState;
         ep.Quantity = c.Quantity;
         ep.Tariff = c.Tariff;
         return ep;
     }
     else
         return null;
 }
Example #48
0
        protected async Task setPaymentInfo()
        {
            Console.WriteLine("SetPaymentInfo Func Started!");
            PaymentInfo newPayment = new PaymentInfo();

            Item item1 = new Item();

            item1.name     = Preferences.Get("item_name", "");
            item1.price    = Preferences.Get("price", "00.00");
            item1.qty      = "1";
            item1.item_uid = Preferences.Get("item_uid", "");;
            List <Item> itemsList = new List <Item> {
                item1
            };

            Preferences.Set("unitNum", AptEntry.Text);

            string userID = (string)Application.Current.Properties["user_id"];

            Console.WriteLine("YOUR userID is " + userID);
            newPayment.customer_uid = userID;
            //newPayment.customer_uid = "100-000082";
            newPayment.business_uid = "200-000001";
            newPayment.items        = itemsList;
            //newPayment.salt = "64a7f1fb0df93d8f5b9df14077948afa1b75b4c5028d58326fb801d825c9cd24412f88c8b121c50ad5c62073c75d69f14557255da1a21e24b9183bc584efef71";
            //newPayment.salt = "cec35d4fc0c5e83527f462aeff579b0c6f098e45b01c8b82e311f87dc6361d752c30293e27027653adbb251dff5d03242c8bec68a3af1abd4e91c5adb799a01b";
            //newPayment.salt = "2020-09-22 21:55:17";
            newPayment.salt = "";
            newPayment.delivery_first_name   = FNameEntry.Text;
            newPayment.delivery_last_name    = LNameEntry.Text;
            newPayment.delivery_email        = emailEntry.Text;
            newPayment.delivery_phone        = PhoneEntry.Text;
            newPayment.delivery_address      = AddressEntry.Text;
            newPayment.delivery_unit         = Preferences.Get("unitNum", "");
            newPayment.delivery_city         = CityEntry.Text;
            newPayment.delivery_state        = StateEntry.Text;
            newPayment.delivery_zip          = ZipEntry.Text;
            newPayment.delivery_instructions = DeliveryEntry.Text;
            newPayment.delivery_longitude    = "";
            newPayment.delivery_latitude     = "";
            newPayment.order_instructions    = "slow";
            newPayment.purchase_notes        = "new purch";
            newPayment.amount_due            = Preferences.Get("price", "00.00");
            newPayment.amount_discount       = "00.00";
            newPayment.amount_paid           = Preferences.Get("price", "00.00");
            newPayment.cc_num = CCEntry.Text;
            //newPayment.cc_exp_year = YearPicker.Items[YearPicker.SelectedIndex];
            newPayment.cc_exp_year = "2022";
            //newPayment.cc_exp_month = MonthPicker.Items[MonthPicker.SelectedIndex];
            newPayment.cc_exp_month = "11";
            newPayment.cc_cvv       = CVVEntry.Text;
            newPayment.cc_zip       = ZipCCEntry.Text;

            //itemsList.Add("1"); //{ "1", "5 Meal Plan", "59.99" };
            var newPaymentJSONString = JsonConvert.SerializeObject(newPayment);
            // Console.WriteLine("newPaymentJSONString" + newPaymentJSONString);
            var content = new StringContent(newPaymentJSONString, Encoding.UTF8, "application/json");

            Console.WriteLine("Content: " + content);

            /*var request = new HttpRequestMessage();
             * request.RequestUri = new Uri("https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/checkout");
             * request.Method = HttpMethod.Post;
             * request.Content = content;*/
            var client   = new HttpClient();
            var response = client.PostAsync("https://ht56vci4v9.execute-api.us-west-1.amazonaws.com/dev/api/v2/checkout", content);

            // HttpResponseMessage response = await client.SendAsync(request);
            Console.WriteLine("RESPONSE TO CHECKOUT   " + response.Result);
            Console.WriteLine("CHECKOUT JSON OBJECT BEING SENT: " + newPaymentJSONString);
            Console.WriteLine("SetPaymentInfo Func ENDED!");
        }
Example #49
0
        private void SaveCreditCardToProfile(string cardNumber, string cardCode, DateTime expires, PaymentInfo paymentInfo, Customer customer)
        {
            var foundPaymentProfile = customer.PaymentProfiles.SingleOrDefault(p => p.ProfileID == paymentInfo.AuNetCustPayId.ToString());

            if (foundPaymentProfile == null)
            {
                var paymentProfileId = CustomerGateway.AddCreditCard(customer.ProfileID, cardNumber,
                    expires.Month, expires.Year, cardCode, customer.BillingAddress);

                paymentInfo.AuNetCustPayId = paymentProfileId.ToInt();
            }
            else
            {
                if (!cardNumber.StartsWith("X"))
                    foundPaymentProfile.CardNumber = cardNumber;

                if (cardCode != null && !cardCode.StartsWith("X"))
                    foundPaymentProfile.CardCode = cardCode;

                foundPaymentProfile.CardExpiration = expires.ToString("MMyy");

                var isSaved = CustomerGateway.UpdatePaymentProfile(customer.ProfileID, foundPaymentProfile);
                if (!isSaved)
                    throw new Exception($"UpdatePaymentProfile failed to save echeck for {paymentInfo.PeopleId}");
            }
        }
Example #50
0
 /// <summary>
 /// Updates the scheduled payment.
 /// </summary>
 /// <param name="transaction">The transaction.</param>
 /// <param name="paymentInfo">The payment info.</param>
 /// <param name="errorMessage">The error message.</param>
 /// <returns></returns>
 public override bool UpdateScheduledPayment(FinancialScheduledTransaction transaction, PaymentInfo paymentInfo, out string errorMessage)
 {
     // Just do nothing here.  It's not supported!
     errorMessage = "";
     return(false);
 }
        private void button4_Click(object sender, EventArgs e)
        {
            if (_dictPassengers.Count > 0)
            {
                DateTime flightDepartureDate = (DateTime)dgvFlightInformation["DepartureTime", dgvFlightInformation.CurrentRow.Index].Value;

                string from = (string)cmbFrom.SelectedValue;
                string to = (string)cmbTo.SelectedValue;

                PassengerInfo[] passengers = new PassengerInfo[_dictPassengers.Count];
                int i = 0;
                Dictionary<string, PassengerInfo>.Enumerator enumerator = _dictPassengers.GetEnumerator();
                while (enumerator.MoveNext())
                    passengers[i++] = enumerator.Current.Value;

                PaymentInfo payment = new PaymentInfo();
                payment.cardholdername = txtHolderName.Text;
                payment.cardname = txtCardName.Text;
                payment.cv2 = txtCardPin.Text;
                payment.expiryDate = dtpCardExpiry.Value;

                FBooking.FlightBookingServiceClient flightBooking = new FlightBookingServiceClient();

                try
                {
                    if (flightBooking.checkAvailability(from, to, flightDepartureDate, passengers.Length))
                    {
                        MessageBox.Show("Seats Available...");

                        if (flightBooking.makeReservation(from, to, flightDepartureDate, passengers, payment))
                            MessageBox.Show("Successfully reserved...");
                        else
                            MessageBox.Show("Reservation unsuccessful...");
                    }
                    else
                        MessageBox.Show("Seats Unavailable...");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    if (flightBooking.State == CommunicationState.Faulted)
                        flightBooking = new FlightBookingServiceClient();

                    flightBooking.Close();
                }
            }
            else
            {
                MessageBox.Show("Please atleast one passenger...");
            }
        }
Example #52
0
        /// <summary>
        /// Gets the person.
        /// </summary>
        /// <param name="paymentInfo">The paymentInfo object to use as the base.</param>
        /// <param name="create">if set to <c>true</c> [create].</param>
        /// <returns></returns>
        private Person GetPerson(PaymentInfo paymentInfo, bool create)
        {
            Person person        = null;
            var    rockContext   = new RockContext();
            var    personService = new PersonService(rockContext);

            Group familyGroup = null;

            int personId = ViewState["PersonId"] as int? ?? 0;

            if (personId == 0 && _targetPerson != null)
            {
                personId = _targetPerson.Id;
            }

            if (personId != 0)
            {
                person = personService.Get(personId);
            }

            if (create)
            {
                if (person == null)
                {
                    // Check to see if there's only one person with same email, first name, and last name
                    if (!string.IsNullOrWhiteSpace(paymentInfo.Email) &&
                        !string.IsNullOrWhiteSpace(paymentInfo.FirstName) &&
                        !string.IsNullOrWhiteSpace(paymentInfo.LastName))
                    {
                        // Same logic as CreatePledge.ascx.cs
                        var personMatches = personService.FindPersons(paymentInfo.FirstName, paymentInfo.LastName, paymentInfo.Email);
                        if (personMatches.Count() == 1)
                        {
                            person = personMatches.FirstOrDefault();
                        }
                        else
                        {
                            person = null;
                        }
                    }

                    if (person == null)
                    {
                        DefinedValueCache dvcConnectionStatus = DefinedValueCache.Get(GetAttributeValue("ConnectionStatus").AsGuid());
                        DefinedValueCache dvcRecordStatus     = DefinedValueCache.Get(GetAttributeValue("RecordStatus").AsGuid());

                        // Create Person
                        person                   = new Person();
                        person.FirstName         = paymentInfo.FirstName;
                        person.LastName          = paymentInfo.LastName;
                        person.IsEmailActive     = true;
                        person.EmailPreference   = EmailPreference.EmailAllowed;
                        person.RecordTypeValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.PERSON_RECORD_TYPE_PERSON.AsGuid()).Id;
                        if (dvcConnectionStatus != null)
                        {
                            person.ConnectionStatusValueId = dvcConnectionStatus.Id;
                        }

                        if (dvcRecordStatus != null)
                        {
                            person.RecordStatusValueId = dvcRecordStatus.Id;
                        }

                        // Create Person/Family
                        familyGroup = PersonService.SaveNewPerson(person, rockContext, null, false);
                    }

                    ViewState["PersonId"] = person != null ? person.Id : 0;
                }
            }

            if (create && person != null)   // person should never be null at this point
            {
                person.Email = paymentInfo.Email;

                if (GetAttributeValue("DisplayPhone").AsBooleanOrNull() ?? false && !String.IsNullOrEmpty(paymentInfo.Phone))
                {
                    var numberTypeId = DefinedValueCache.Get(new Guid(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_HOME)).Id;
                    var phone        = person.PhoneNumbers.FirstOrDefault(p => p.NumberTypeValueId == numberTypeId);
                    if (phone == null)
                    {
                        phone = new PhoneNumber();
                        person.PhoneNumbers.Add(phone);
                        phone.NumberTypeValueId = numberTypeId;
                    }
                    phone.Number = paymentInfo.Phone;
                }

                if (familyGroup == null)
                {
                    var groupLocationService = new GroupLocationService(rockContext);
                    if (GroupLocationId.HasValue)
                    {
                        familyGroup = groupLocationService.Queryable()
                                      .Where(gl => gl.Id == GroupLocationId.Value)
                                      .Select(gl => gl.Group)
                                      .FirstOrDefault();
                    }
                    else
                    {
                        familyGroup = personService.GetFamilies(person.Id).FirstOrDefault();
                    }
                }

                rockContext.SaveChanges();

                if (familyGroup != null)
                {
                    GroupService.AddNewGroupAddress(
                        rockContext,
                        familyGroup,
                        GetAttributeValue("AddressType"),
                        paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country,
                        true);
                }
            }

            return(person);
        }
Example #53
0
        public void Update()
        {
            // first check for total amount greater than zero.
            // if so we skip everything except updating the amounts.
            var chosenFunds = FundItemsChosen().ToList();

            if (chosenFunds.Sum(f => f.amt) > 0)
            {
                var pi = person.PaymentInfo();
                if (pi == null)
                {
                    pi = new PaymentInfo();
                    person.PaymentInfos.Add(pi);
                }
                pi.SetBillingAddress(FirstName, Middle, LastName, Suffix, Address, Address2, City, State, Country, Zip, Phone);

                // first need to do a $1 auth if it's a credit card and throw any errors we get back
                // from the gateway.
                var vaultSaved = false;
                var gateway    = DbUtil.Db.Gateway(testing);
                if (Type == PaymentType.CreditCard)
                {
                    // perform $1 auth.
                    // need to randomize the $1 amount because some gateways will reject same auth amount
                    // subsequent times per user.
                    var random    = new Random();
                    var dollarAmt = (decimal)random.Next(100, 199) / 100;

                    TransactionResponse transactionResponse;
                    if (CreditCard.StartsWith("X"))
                    {
//                        // store payment method in the gateway vault first before doing the auth.
//                          If it starts with X, we should not be storing it in the vault.
//                        gateway.StoreInVault(pid, Type, CreditCard, Expires, CVV, Routing, Account, giving: true);
                        vaultSaved          = true; // prevent it from saving later
                        transactionResponse = gateway.AuthCreditCardVault(pid, dollarAmt, "Recurring Giving Auth", 0);
                    }
                    else
                    {
                        var pf = new PaymentForm()
                        {
                            CreditCard = CreditCard,
                            First      = FirstName,
                            Last       = LastName
                        };
                        if (IsCardTester(pf, "ManagedGiving"))
                        {
                            throw new Exception("Found Card Tester");
                        }
                        transactionResponse = gateway.AuthCreditCard(pid, dollarAmt, CreditCard, Expires,
                                                                     "Recurring Giving Auth", 0, CVV, string.Empty,
                                                                     FirstName, LastName, Address, Address2, City, State, Country, Zip, Phone);
                    }

                    if (!transactionResponse.Approved)
                    {
                        throw new Exception(transactionResponse.Message);
                    }

                    // if we got this far that means the auth worked so now let's do a void for that auth.
                    var voidResponse = gateway.VoidCreditCardTransaction(transactionResponse.TransactionId);
                }

                // store payment method in the gateway vault if not already saved.
                if (!vaultSaved)
                {
                    gateway.StoreInVault(pid, Type, CreditCard, Expires, CVV, Routing, Account, giving: true);
                }

                // save all the managed giving data.
                var mg = person.ManagedGiving();
                if (mg == null)
                {
                    mg = new ManagedGiving();
                    person.ManagedGivings.Add(mg);
                }
                mg.SemiEvery = SemiEvery;
                mg.Day1      = Day1;
                mg.Day2      = Day2;
                mg.EveryN    = EveryN;
                mg.Period    = Period;
                mg.StartWhen = StartWhen;
                mg.StopWhen  = StopWhen;
                mg.NextDate  = mg.FindNextDate(DateTime.Today);
            }

            DbUtil.Db.RecurringAmounts.DeleteAllOnSubmit(person.RecurringAmounts);
            DbUtil.Db.SubmitChanges();

            person.RecurringAmounts.AddRange(chosenFunds.Select(c => new RecurringAmount {
                FundId = c.fundid, Amt = c.amt
            }));
            DbUtil.Db.SubmitChanges();
        }
 public void GivenFollowingDetailsAboutAnOrder(Table table)
 {
     paymentInfo = table.CreateInstance <PaymentInfo>();
 }
Example #55
0
        private void UpdateCreditCardVault(Person person, PaymentInfo paymentInfo, string expiration)
        {
            var vaultId = paymentInfo.TbnCardVaultId.GetValueOrDefault();

            var updateCreditCardVaultRequest = new UpdateCreditCardVaultRequest(
                _userName,
                _password,
                vaultId.ToString(CultureInfo.InvariantCulture),
                expiration,
                new BillingAddress
                {
                    FirstName = paymentInfo.FirstName ?? person.FirstName,
                    LastName = paymentInfo.LastName ?? person.LastName,
                    Address1 = paymentInfo.Address ?? person.PrimaryAddress,
                    City = paymentInfo.City ?? person.PrimaryCity,
                    State = paymentInfo.State ?? person.PrimaryState,
                    Zip = paymentInfo.Zip ?? person.PrimaryZip,
                    Email = person.EmailAddress,
                    Phone = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone
                });

            var response = updateCreditCardVaultRequest.Execute();
            if (response.ResponseStatus != ResponseStatus.Approved)
                throw new Exception(
                    $"TransNational failed to update the credit card expiration date for people id: {person.PeopleId}, responseCode: {response.ResponseCode}, responseText: {response.ResponseText}");
        }
Example #56
0
        private void SaveCreditCardToProfile(string cardNumber, string cardCode, DateTime expires, PaymentInfo paymentInfo, Customer customer)
        {
            var foundPaymentProfile = customer.PaymentProfiles.SingleOrDefault(p => p.ProfileID == paymentInfo.AuNetCustPayId.ToString());

            if (foundPaymentProfile == null)
            {
                var paymentProfileId = CustomerGateway.AddCreditCard(customer.ProfileID, cardNumber,
                                                                     expires.Month, expires.Year, cardCode, customer.BillingAddress);

                paymentInfo.AuNetCustPayId = paymentProfileId.ToInt();
            }
            else
            {
                if (!cardNumber.StartsWith("X"))
                {
                    foundPaymentProfile.CardNumber = cardNumber;
                }

                if (cardCode != null && !cardCode.StartsWith("X"))
                {
                    foundPaymentProfile.CardCode = cardCode;
                }

                foundPaymentProfile.CardExpiration = expires.ToString("MMyy");

                var isSaved = CustomerGateway.UpdatePaymentProfile(customer.ProfileID, foundPaymentProfile);
                if (!isSaved)
                {
                    throw new Exception($"UpdatePaymentProfile failed to save echeck for {paymentInfo.PeopleId}");
                }
            }
        }
Example #57
0
        /// <summary>
        /// Sets any payment information that the <seealso cref="GatewayComponent">paymentGateway</seealso> didn't set
        /// </summary>
        /// <param name="paymentInfo">The payment information.</param>
        /// <param name="paymentGateway">The payment gateway.</param>
        /// <param name="rockContext">The rock context.</param>
        public void SetFromPaymentInfo(PaymentInfo paymentInfo, GatewayComponent paymentGateway, RockContext rockContext)
        {
            /* 2020-08-27 MDP
             * This method should only update values haven't been set yet. So
             *  1) Make sure paymentInfo has the data (isn't null or whitespace)
             *  2) Don't overwrite data in this (FinancialPaymentDetail) that already has the data set.
             */

            if (AccountNumberMasked.IsNullOrWhiteSpace() && paymentInfo.MaskedNumber.IsNotNullOrWhiteSpace())
            {
                AccountNumberMasked = paymentInfo.MaskedNumber;
            }

            if (paymentInfo is ReferencePaymentInfo referencePaymentInfo)
            {
                if (GatewayPersonIdentifier.IsNullOrWhiteSpace())
                {
                    GatewayPersonIdentifier = referencePaymentInfo.GatewayPersonIdentifier;
                }

                if (!FinancialPersonSavedAccountId.HasValue)
                {
                    FinancialPersonSavedAccountId = referencePaymentInfo.FinancialPersonSavedAccountId;
                }
            }

            if (!CurrencyTypeValueId.HasValue && paymentInfo.CurrencyTypeValue != null)
            {
                CurrencyTypeValueId = paymentInfo.CurrencyTypeValue.Id;
            }

            if (!CreditCardTypeValueId.HasValue && paymentInfo.CreditCardTypeValue != null)
            {
                CreditCardTypeValueId = paymentInfo.CreditCardTypeValue.Id;
            }

            if (paymentInfo is CreditCardPaymentInfo)
            {
                var ccPaymentInfo = ( CreditCardPaymentInfo )paymentInfo;

                string nameOnCard  = paymentGateway.SplitNameOnCard ? ccPaymentInfo.NameOnCard + " " + ccPaymentInfo.LastNameOnCard : ccPaymentInfo.NameOnCard;
                var    newLocation = new LocationService(rockContext).Get(
                    ccPaymentInfo.BillingStreet1, ccPaymentInfo.BillingStreet2, ccPaymentInfo.BillingCity, ccPaymentInfo.BillingState, ccPaymentInfo.BillingPostalCode, ccPaymentInfo.BillingCountry);

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(nameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(ccPaymentInfo.ExpirationDate.Year.ToString());
                }

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
            else if (paymentInfo is SwipePaymentInfo)
            {
                var swipePaymentInfo = ( SwipePaymentInfo )paymentInfo;

                if (NameOnCard.IsNullOrWhiteSpace() && NameOnCard.IsNotNullOrWhiteSpace())
                {
                    NameOnCardEncrypted = Encryption.EncryptString(swipePaymentInfo.NameOnCard);
                }

                if (!ExpirationMonth.HasValue)
                {
                    ExpirationMonthEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Month.ToString());
                }

                if (!ExpirationYear.HasValue)
                {
                    ExpirationYearEncrypted = Encryption.EncryptString(swipePaymentInfo.ExpirationDate.Year.ToString());
                }
            }
            else
            {
                var newLocation = new LocationService(rockContext).Get(
                    paymentInfo.Street1, paymentInfo.Street2, paymentInfo.City, paymentInfo.State, paymentInfo.PostalCode, paymentInfo.Country);

                if (!BillingLocationId.HasValue && newLocation != null)
                {
                    BillingLocationId = newLocation.Id;
                }
            }
        }
Example #58
0
        public void StoreInVault(int peopleId, string type, string cardNumber, string expires, string cardCode,
                                 string routing, string account, bool giving)
        {
            var person      = db.LoadPersonById(peopleId);
            var paymentInfo = person.PaymentInfo();

            if (paymentInfo == null)
            {
                paymentInfo = new PaymentInfo();
                person.PaymentInfos.Add(paymentInfo);
            }

            var billToAddress = new AuthorizeNet.Address
            {
                First   = paymentInfo.FirstName ?? person.FirstName,
                Last    = paymentInfo.LastName ?? person.LastName,
                Street  = paymentInfo.Address ?? person.PrimaryAddress,
                City    = paymentInfo.City ?? person.PrimaryCity,
                State   = paymentInfo.State ?? person.PrimaryState,
                Country = paymentInfo.Country ?? person.PrimaryCountry,
                Zip     = paymentInfo.Zip ?? person.PrimaryZip,
                Phone   = paymentInfo.Phone ?? person.HomePhone ?? person.CellPhone
            };

            Customer customer;

            if (paymentInfo.AuNetCustId == null) // create a new profilein Authorize.NET CIM
            {
                // NOTE: this can throw an error if the email address already exists...
                // TODO: Authorize.net needs to release a new Nuget package, because they don't have a clean way to pass in customer ID (aka PeopleId) yet... the latest code has a parameter for this, though
                //       - we could call UpdateCustomer after the fact to do this if we wanted to
                customer    = CustomerGateway.CreateCustomer(person.EmailAddress, person.Name);
                customer.ID = peopleId.ToString();

                paymentInfo.AuNetCustId = customer.ProfileID.ToInt();
            }
            else
            {
                customer = CustomerGateway.GetCustomer(paymentInfo.AuNetCustId.ToString());
            }

            customer.BillingAddress = billToAddress;
            var isSaved = CustomerGateway.UpdateCustomer(customer);

            if (!isSaved)
            {
                throw new Exception($"UpdateCustomer failed to save for {peopleId}");
            }

            if (type == PaymentType.Ach)
            {
                SaveECheckToProfile(routing, account, paymentInfo, customer);

                paymentInfo.MaskedAccount = Util.MaskAccount(account);
                paymentInfo.Routing       = Util.Mask(new StringBuilder(routing), 2);
            }
            else if (type == PaymentType.CreditCard)
            {
                var normalizeExpires = DbUtil.NormalizeExpires(expires);
                if (normalizeExpires == null)
                {
                    throw new ArgumentException($"Can't normalize date {expires}", nameof(expires));
                }

                var expiredDate = normalizeExpires.Value;

                SaveCreditCardToProfile(cardNumber, cardCode, expiredDate, paymentInfo, customer);

                paymentInfo.MaskedCard = Util.MaskCC(cardNumber);
                paymentInfo.Expires    = expires;
            }
            else
            {
                throw new ArgumentException($"Type {type} not supported", nameof(type));
            }

            if (giving)
            {
                paymentInfo.PreferredGivingType = type;
            }
            else
            {
                paymentInfo.PreferredPaymentType = type;
            }

            db.SubmitChanges();
        }
Example #59
0
        private void SaveTransaction(FinancialGateway financialGateway, GatewayComponent gateway, Person person, PaymentInfo paymentInfo, FinancialTransaction transaction, RockContext rockContext)
        {
            transaction.AuthorizedPersonAliasId = person.PrimaryAliasId;
            if (RockTransactionEntry != null)
            {
                RockCheckBox cbGiveAnonymouslyControl = (( RockCheckBox )(RockTransactionEntry.FindControl("cbGiveAnonymously")));
                if (cbGiveAnonymouslyControl != null)
                {
                    transaction.ShowAsAnonymous = cbGiveAnonymouslyControl.Checked;
                }
            }
            transaction.TransactionDateTime = RockDateTime.Now;
            transaction.FinancialGatewayId  = financialGateway.Id;

            var txnType = DefinedValueCache.Get(this.GetAttributeValue("TransactionType").AsGuidOrNull() ?? Rock.SystemGuid.DefinedValue.TRANSACTION_TYPE_CONTRIBUTION.AsGuid());

            transaction.TransactionTypeValueId = txnType.Id;

            transaction.Summary = paymentInfo.Comment1;

            if (transaction.FinancialPaymentDetail == null)
            {
                transaction.FinancialPaymentDetail = new FinancialPaymentDetail();
            }
            transaction.FinancialPaymentDetail.SetFromPaymentInfo(paymentInfo, gateway, rockContext);

            Guid sourceGuid = Guid.Empty;

            if (Guid.TryParse(GetAttributeValue("Source"), out sourceGuid))
            {
                var source = DefinedValueCache.Get(sourceGuid);
                if (source != null)
                {
                    transaction.SourceTypeValueId = source.Id;
                }
            }

            var transactionEntity = this.GetTransactionEntity();

            foreach (var account in GetSelectedAccounts().Where(a => a.Amount > 0))
            {
                var transactionDetail = new FinancialTransactionDetail();
                transactionDetail.Amount    = account.Amount;
                transactionDetail.AccountId = account.Id;
                if (transactionEntity != null)
                {
                    transactionDetail.EntityTypeId = transactionEntity.TypeId;
                    transactionDetail.EntityId     = transactionEntity.Id;
                }

                transaction.TransactionDetails.Add(transactionDetail);
            }

            var batchService = new FinancialBatchService(rockContext);

            // Get the batch
            var batch = batchService.Get(
                GetAttributeValue("BatchNamePrefix"),
                paymentInfo.CurrencyTypeValue,
                paymentInfo.CreditCardTypeValue,
                transaction.TransactionDateTime.Value,
                financialGateway.GetBatchTimeOffset());

            var batchChanges = new History.HistoryChangeList();

            if (batch.Id == 0)
            {
                batchChanges.AddCustom("Add", "Record", "Generated the batch");
                History.EvaluateChange(batchChanges, "Batch Name", string.Empty, batch.Name);
                History.EvaluateChange(batchChanges, "Status", null, batch.Status);
                History.EvaluateChange(batchChanges, "Start Date/Time", null, batch.BatchStartDateTime);
                History.EvaluateChange(batchChanges, "End Date/Time", null, batch.BatchEndDateTime);
            }

            decimal newControlAmount = batch.ControlAmount + transaction.TotalAmount;

            History.EvaluateChange(batchChanges, "Control Amount", batch.ControlAmount.FormatAsCurrency(), newControlAmount.FormatAsCurrency());
            batch.ControlAmount = newControlAmount;

            transaction.BatchId = batch.Id;
            transaction.LoadAttributes(rockContext);

            var allowedTransactionAttributes = GetAttributeValue("AllowedTransactionAttributesFromURL").Split(',').AsGuidList().Select(x => AttributeCache.Get(x).Key);

            foreach (KeyValuePair <string, AttributeValueCache> attr in transaction.AttributeValues)
            {
                if (PageParameters().ContainsKey("Attribute_" + attr.Key) && allowedTransactionAttributes.Contains(attr.Key))
                {
                    attr.Value.Value = Server.UrlDecode(PageParameter("Attribute_" + attr.Key));
                }
            }

            batch.Transactions.Add(transaction);

            rockContext.SaveChanges();
            transaction.SaveAttributeValues();

            HistoryService.SaveChanges(
                rockContext,
                typeof(FinancialBatch),
                Rock.SystemGuid.Category.HISTORY_FINANCIAL_BATCH.AsGuid(),
                batch.Id,
                batchChanges
                );

            SendReceipt(transaction.Id);

            TransactionCode = transaction.TransactionCode;
        }
Example #60
0
        /// <summary>
        /// Charges the specified payment info.
        /// </summary>
        /// <param name="financialGateway"></param>
        /// <param name="paymentInfo">The payment info.</param>
        /// <param name="errorMessage">The error message.</param>
        /// <returns></returns>
        public override FinancialTransaction Charge(FinancialGateway financialGateway, PaymentInfo paymentInfo, out string errorMessage)
        {
            errorMessage = string.Empty;
            Response ppResponse = null;

            var invoice = GetInvoice(paymentInfo);

            // add in spark reference code
            BrowserInfo browser = new BrowserInfo();

            browser.ButtonSource = "SparkDevelopmentNetwork_SP";
            invoice.BrowserInfo  = browser;

            var tender = GetTender(paymentInfo);

            if (tender != null)
            {
                if (paymentInfo is ReferencePaymentInfo)
                {
                    var reference     = paymentInfo as ReferencePaymentInfo;
                    var ppTransaction = new ReferenceTransaction("Sale", reference.TransactionCode, GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
                else
                {
                    var ppTransaction = new SaleTransaction(GetUserInfo(financialGateway), GetConnection(financialGateway), invoice, tender, PayflowUtility.RequestId);
                    ppResponse = ppTransaction.SubmitTransaction();
                }
            }
            else
            {
                errorMessage = "Could not create tender from PaymentInfo";
            }

            if (ppResponse != null)
            {
                TransactionResponse txnResponse = ppResponse.TransactionResponse;
                if (txnResponse != null)
                {
                    if (txnResponse.Result == 0)   // Success
                    {
                        var transaction = new FinancialTransaction();
                        transaction.TransactionCode = txnResponse.Pnref;

                        // Get the stored payment method that was used so we can update it
                        //  with the latest transaction code.  We do this because Paypal
                        //  will only let us use the same transaction code in reference
                        //  transactions for up to 12 months.
                        if (paymentInfo is ReferencePaymentInfo)
                        {
                            var reference    = paymentInfo as ReferencePaymentInfo;
                            var rockContext  = new RockContext();
                            var savedAccount = new FinancialPersonSavedAccountService(rockContext)
                                               .Queryable()
                                               .Where(s =>
                                                      s.TransactionCode == reference.TransactionCode &&
                                                      s.FinancialGatewayId.HasValue &&
                                                      s.FinancialGatewayId.Value == financialGateway.Id)
                                               .FirstOrDefault();
                            if (savedAccount != null)
                            {
                                savedAccount.TransactionCode = txnResponse.Pnref;
                                rockContext.SaveChanges();
                            }
                        }

                        return(transaction);
                    }
                    else
                    {
                        errorMessage = string.Format("[{0}] {1}", txnResponse.Result, txnResponse.RespMsg);
                    }
                }
                else
                {
                    errorMessage = "Invalid transaction response from the financial gateway";
                }
            }
            else
            {
                errorMessage = "Invalid response from the financial gateway.";
            }

            return(null);
        }