Exemplo n.º 1
0
        protected virtual string CheckStatus([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");

            var          configuration    = new PaymentSettingsReader(paymentSystem);
            string       protocolInput    = configuration.GetSetting("protocol");
            const string MsgtypeInput     = "status";
            string       merchantInput    = paymentSystem.Username;
            string       ordernumberInput = paymentArgs.ShoppingCart.OrderNumber;
            string       secretInput      = paymentSystem.Password;
            string       apiUrl           = configuration.GetSetting("apiURL");

            string tohashInput   = string.Concat(protocolInput, MsgtypeInput, merchantInput, ordernumberInput, secretInput);
            string hashInput     = this.GetMD5Hash(tohashInput);
            string requestString = string.Format(
                "protocol={0}&msgtype={1}&merchant={2}&ordernumber={3}&md5check={4}",
                protocolInput,
                MsgtypeInput,
                paymentSystem.Username,
                ordernumberInput,
                hashInput);

            string information = string.Empty;

            return(this.SendRequest(apiUrl, requestString, ref information));
        }
        public static async Task Write <T>(PaymentSystem database, IEnumerable <T> dataToWrite, string tableName)
        {
            var columns = typeof(T).GetProperties().Select(x => x.Name).ToArray();

            using (var connection = Connection(database))
                using (var bulkCopy = new SqlBulkCopy(connection))
                    using (var reader = ObjectReader.Create(dataToWrite, columns))
                    {
                        bulkCopy.DestinationTableName = $"[Verification].[{tableName}]";
                        bulkCopy.BulkCopyTimeout      = 1200;
                        bulkCopy.BatchSize            = 10_000;

                        foreach (var column in columns)
                        {
                            bulkCopy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(column, column));
                        }

                        if (connection.State != ConnectionState.Open)
                        {
                            await connection.OpenAsync();
                        }

                        await bulkCopy.WriteToServerAsync(reader).ConfigureAwait(false);
                    }
        }
Exemplo n.º 3
0
 public WalletError SetPaymentWalletsBySystem(ProtectedOperationContext secCtx,
                                              PaymentSystem syst,
                                              List <UserPaymentSystem> actualPaySys,
                                              string userLogin, string walletPwrd)
 {
     if (Channel == null)
     {
         throw new Exception("WalletManagerProxy: связь не установлена");
     }
     try
     {
         return(Channel.SetPaymentWalletsBySystem(secCtx, syst, actualPaySys, userLogin, walletPwrd));
     }
     catch
     {
         RenewFactory();
         try
         {
             return(Channel.SetPaymentWalletsBySystem(secCtx, syst, actualPaySys, userLogin, walletPwrd));
         }
         catch (Exception ex2)
         {
             Logger.Error("SetPaymentWalletsBySystem() error: ", ex2);
             return(WalletError.CommonError);
         }
     }
 }
        private static string GetInclusionSqlText(PaymentSystem system, Inclusions inclusion)
        {
            var path = Path.Combine(BasePath, "SQL", "Inclusions", system.ToString(), $"{inclusion.Description()}.sql");
            var sql  = File.ReadAllText(path);

            return(UpdateTableAndSchemaNames(sql));
        }
Exemplo n.º 5
0
        /// <summary>
        /// Cancels payment reservation
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        /// <param name="reservationTicket">The reservation ticket.</param>
        public void CancelReservation([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs, [NotNull] ReservationTicket reservationTicket)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.ArgumentNotNull(reservationTicket, "reservationTicket");

            ITransactionData transactionDataProvider = Context.Entity.Resolve <ITransactionData>();

            long   accountNumber     = TypeUtil.TryParse <long>(paymentSystem.Username, 0);
            int    transactionNumber = int.Parse(reservationTicket.TransactionNumber);
            string encryptionKey     = paymentSystem.Password;

            ArrayList param = new ArrayList
            {
                accountNumber,
                transactionNumber,
                encryptionKey
            };
            string hash = this.CreateMD5Hash(param);

            PxOrder order       = new PxOrder();
            string  xmlReturn   = order.Cancel2(accountNumber, transactionNumber, hash);
            string  errorCode   = this.ParseRes(xmlReturn, "/payex/status/errorCode");
            string  description = this.ParseRes(xmlReturn, "/payex/status/description");

            if (errorCode == "OK" && description == "OK")
            {
                transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.CancelSuccess);
            }
            else
            {
                transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, string.Format("errorCode={0} description={1}", errorCode, description));
            }
        }
Exemplo n.º 6
0
        private void EnsurePaymentSystemState()
        {
            paymentSystem = CardModel.PaymentSystem;
            string state;

            switch (paymentSystem)
            {
            case PaymentSystem.Visa:
                state = "VisaState";
                break;

            case PaymentSystem.MasterCard:
                state = "MastercardState";
                break;

            case PaymentSystem.Maestro:
                state = "MaestroState";
                break;

            default:
                state = "DefaultPaymentSystemState";
                break;
            }
            VisualStateManager.GoToState(this, state, true);
        }
Exemplo n.º 7
0
 public IParseble Parse(JSONNode purchaseNode)
 {
     if (purchaseNode.Count == 0)
     {
         return(null);
     }
     if (purchaseNode ["virtual_currency"] != null)
     {
         virtualCurrency = new VirtualCurrency().Parse(purchaseNode ["virtual_currency"]) as VirtualCurrency;
     }
     if (purchaseNode ["virtual_items"] != null)
     {
         virtualItems = new VirtualItems().Parse(purchaseNode ["virtual_items"]) as VirtualItems;
     }
     if (purchaseNode ["subscription"] != null)
     {
         subscription = new Subscription().Parse(purchaseNode ["subscription"]) as Subscription;
     }
     if (purchaseNode ["payment_system"] != null)
     {
         paymentSystem = new PaymentSystem().Parse(purchaseNode ["payment_system"]) as PaymentSystem;
     }
     if (purchaseNode ["checkout"] != null)
     {
         checkout = new Checkout().Parse(purchaseNode ["checkout"]) as Checkout;
     }
     ;
     return(this);
 }
Exemplo n.º 8
0
        /// <summary>
        /// Handles the ItemDataBound event of the repeaterPaymentMethods control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Web.UI.WebControls.RepeaterItemEventArgs"/> instance containing the event data.</param>
        protected void repeaterPaymentMethods_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            HtmlInputControl input = e.Item.FindControl("paymentMethod") as HtmlInputControl;

            PaymentSystem method = e.Item.DataItem as PaymentSystem;
            string        code   = string.Empty;

            if (method != null)
            {
                code = method.Code;
            }

            if (input != null)
            {
                input.Value = code;
            }

            if (this.ddlPaymentMethods.SelectedItem != null)
            {
                if (string.Compare(code, this.ddlPaymentMethods.SelectedItem.Value, true) != 0)
                {
                    HtmlControl container = e.Item.FindControl("paymentMethodContainer") as HtmlControl;
                    if (container != null)
                    {
                        container.Attributes["style"] = "display:none;";
                    }
                }
            }
        }
        public async Task <string> InsertRequestAsync <T>(ICashOutRequest request, PaymentSystem paymentSystem, T paymentFields, CashOutRequestTradeSystem tradeSystem)
        {
            var entity = CashOutAttemptEntity.PendingRecords.Create(request, paymentSystem, paymentFields, tradeSystem);
            await _tableStorage.InsertAsync(entity);

            return(entity.RowKey);
        }
Exemplo n.º 10
0
        public virtual Tuple <bool, string> refund(int transactionId)
        {
            if (transactionId < 0)
            {
                return(new Tuple <bool, string>(false, "Invalid TransactionId"));
            }


            Logger.logEvent(this, System.Reflection.MethodBase.GetCurrentMethod());
            if (mock)
            {
                if (work)
                {
                    if (PaymentSystemMock.CancelPayment(8, 8) > 0)
                    {
                        return(new Tuple <bool, string>(true, "Works"));
                    }
                    return(new Tuple <bool, string>(false, "not"));
                }
                if (PaymentSystemMock.CancelPayment(8, -1) > 0)
                {
                    return(new Tuple <bool, string>(false, "not"));
                }
                return(new Tuple <bool, string>(true, "Works"));
            }
            int cancel_res = PaymentSystem.CancelPayment(transactionId);

            if (cancel_res < 0)
            {
                return(new Tuple <bool, string>(false, "refund failed"));
            }

            return(new Tuple <bool, string>(true, "OK"));
        }
Exemplo n.º 11
0
        public static void MakePayment(decimal amount, string customerName)
        {
            // Some validation or logic on the customer record
            var customer = CustomerSystem.GetCustomer(customerName);

            // Submit payment for processing
            PaymentSystem.MakePayment(amount, customer);
        }
Exemplo n.º 12
0
        protected ProcessResponse Process([NotNull] PaymentSystem paymentSystem, [NotNull] ReservationTicket reservationTicket, [NotNull] string operation)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(reservationTicket, "reservationTicket");
            Assert.ArgumentNotNull(operation, "operation");

            return(this.Process(paymentSystem, reservationTicket, reservationTicket.Amount, operation));
        }
 void Awake()
 {
     prev = transform.position;
     dist_left = new List<float>();
     rs = GetComponent<RidingScript>();
     ps = GetComponent<PaymentSystem>();
     num_para = 0;
     timeEl = 0;
 }
            public static CashOutAttemptEntity Create <T>(ICashOutRequest request, PaymentSystem paymentSystem,
                                                          T paymentFields, CashOutRequestTradeSystem tradeSystem)
            {
                var entity = CreateEntity(request, paymentSystem, paymentFields, tradeSystem);

                entity.PartitionKey = GeneratePartition();

                return(entity);
            }
Exemplo n.º 15
0
 void Awake()
 {
     prev      = transform.position;
     dist_left = new List <float>();
     rs        = GetComponent <RidingScript>();
     ps        = GetComponent <PaymentSystem>();
     num_para  = 0;
     timeEl    = 0;
 }
Exemplo n.º 16
0
        /// <summary>
        /// Captures the payment
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        /// <param name="reservationTicket">The reservation ticket.</param>
        /// <param name="amount">The amount.</param>
        public void Capture([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs, [NotNull] ReservationTicket reservationTicket, decimal amount)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.ArgumentNotNull(reservationTicket, "reservationTicket");

            Assert.ArgumentCondition((amount > 0), "amount", "An amount should be greater than zero");
            Assert.ArgumentCondition((amount <= reservationTicket.Amount), "amount", "An amount should not be greater than the original reserved one");

            var configuration = new PaymentSettingsReader(paymentSystem);
            ITransactionData transactionDataProvider = Context.Entity.Resolve <ITransactionData>();

            string       protocolInput = configuration.GetSetting("protocol");
            const string MsgtypeInput  = "capture";
            string       merchantInput = paymentSystem.Username;
            string       amountInput   = amount.ToCents();
            string       transaction   = reservationTicket.TransactionNumber;
            string       secretInput   = paymentSystem.Password;
            string       apiUrl        = configuration.GetSetting("apiURL");

            string tohashInput   = string.Concat(protocolInput, MsgtypeInput, merchantInput, amountInput, transaction, secretInput);
            string hashInput     = this.GetMD5Hash(tohashInput);
            string requestString = string.Format(
                "protocol={0}&msgtype={1}&merchant={2}&amount={3}&transaction={4}&md5check={5}",
                protocolInput,
                MsgtypeInput,
                paymentSystem.Username,
                amountInput,
                transaction,
                hashInput);

            string message     = "UnCaptured: ";
            string information = string.Empty;
            string xmlReturn   = this.SendRequest(apiUrl, requestString, ref information);

            if (!string.IsNullOrEmpty(xmlReturn))
            {
                var    quickPayResponse = this.ParseResult(xmlReturn);
                string secret           = paymentSystem.Password;
                string tohash           = string.Join(string.Empty, quickPayResponse.Where(x => x.Key != "md5check").Select(x => x.Value).ToArray()) + secret;
                string md5Check         = this.GetMD5Hash(tohash);

                if (md5Check.Equals(quickPayResponse["md5check"]) && quickPayResponse["qpstat"].Equals("000"))
                {
                    transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.CaptureSuccess);
                    return;
                }

                message += string.Format("qpstat={0}", quickPayResponse["qpstat"]);
            }
            else
            {
                message += information;
            }

            transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, message);
        }
Exemplo n.º 17
0
        public WalletError SetPaymentWalletsBySystem(ProtectedOperationContext secCtx,
                                                     PaymentSystem syst,
                                                     List <UserPaymentSystem> actualPaySys,
                                                     string userLogin, string walletPwrd)
        {
            if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false))
            {
                return(WalletError.InsufficientRights);
            }

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                    {
                        return(WalletError.AuthenticationError);
                    }

                    // уничтожить старые записи того же типа
                    var existRecs =
                        ctx.USER_PAYMENT_SYSTEM.Where(r => r.UserId == user.ID && r.SystemPayment == (int)syst).ToList();
                    foreach (var rec in existRecs)
                    {
                        ctx.USER_PAYMENT_SYSTEM.Remove(rec);
                    }
                    ctx.SaveChanges();

                    // добавить новые записи
                    foreach (var paySyst in actualPaySys)
                    {
                        paySyst.UserId        = user.ID;
                        paySyst.SystemPayment = syst;
                        ctx.USER_PAYMENT_SYSTEM.Add(LinqToEntity.UndecorateUserPaymentSystem(paySyst));
                    }
                    ctx.SaveChanges();
                    return(WalletError.OK);
                }
            }
            catch (DbUpdateException ex)
            {
                if (ex.InnerException.InnerException is SqlException)
                {
                    Logger.Error("SetPaymentWalletsBySystem() error: возможно, запись с таким RootId и PurseId уже есть в таблице USER_PAYMENT_SYSTEM", ex);
                    return(WalletError.ServerSqlError);
                }
                Logger.Error("SetPaymentWalletsBySystem() error", ex);
                return(WalletError.ServerError);
            }
            catch (Exception ex)
            {
                Logger.Error("SetPaymentWalletsBySystem() error", ex);
                return(WalletError.ServerError);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Performs the completion of the conversation with PayPal.
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="orderRef">The order ref.</param>
        /// <param name="accountNumber">The account number.</param>
        /// <param name="hash">The hash.</param>
        /// <param name="transactionDataProvider">The transaction data provider.</param>
        protected void CompleteCallback(PaymentSystem paymentSystem, string orderRef, long accountNumber, string hash, ITransactionData transactionDataProvider)
        {
            PaymentSettingsReader configuration = new PaymentSettingsReader(paymentSystem);
            string        purchaseOperation     = configuration.GetSetting("purchaseOperation");
            PaymentStatus paymentStatusResult   = PaymentStatus.Failure;

            PxOrder payexOrder = new PxOrder();
            string  xmlReturn  = payexOrder.Complete(accountNumber, orderRef, hash);

            string transactionNumber = this.ParseRes(xmlReturn, "/payex/transactionNumber");
            string orderNumber       = this.ParseRes(xmlReturn, "/payex/orderId");
            string transactionAmount = this.ParseRes(xmlReturn, "/payex/amount");
            string errorCode         = this.ParseRes(xmlReturn, "/payex/status/errorCode");
            int    transactionStatus = int.Parse(this.ParseRes(xmlReturn, "/payex/transactionStatus"));

            if (errorCode == "OK")
            {
                switch (transactionStatus)
                {
                case (int)TransactionStatus.Sale:
                case (int)TransactionStatus.Authorize:
                {
                    paymentStatusResult = PaymentStatus.Succeeded;
                    transactionDataProvider.SaveCallBackValues(orderNumber, paymentStatusResult.ToString(), transactionNumber, transactionAmount, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);

                    if (string.Compare(purchaseOperation, this.ReservableTransactionType, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        decimal           amount            = transactionAmount.FromCents();
                        ReservationTicket reservationTicket = new ReservationTicket
                        {
                            InvoiceNumber     = orderNumber,
                            AuthorizationCode = PaymentConstants.EmptyAuthorizationCode,
                            TransactionNumber = transactionNumber,
                            Amount            = amount
                        };
                        transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.ReservationTicket, reservationTicket);
                    }

                    break;
                }

                default:
                {
                    string transactionErrorCode = this.ParseRes(xmlReturn, "/payex/errorDetails/transactionErrorCode");
                    if (transactionErrorCode == OperationCanceledError)
                    {
                        paymentStatusResult = PaymentStatus.Canceled;
                    }

                    break;
                }
                }
            }

            this.PaymentStatus = paymentStatusResult;
        }
Exemplo n.º 19
0
        /// <summary>
        /// Processes the callback in terms of the HttpRequest and extracts either hidden form fields, or querystring parameters
        /// that is returned from the payment provider.
        /// Determines the payment status and saves that indication for later, could be in session, in db, or other storage.
        /// This information is important and used in the GetPaymentStatus().
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        public override void ProcessCallback([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.IsNotNull(paymentArgs.ShoppingCart, "Shopping cart is null");

            this.PaymentStatus = PaymentStatus.Failure;

            HttpRequest           request = HttpContext.Current.Request;
            ITransactionData      transactionDataProvider = Context.Entity.Resolve <ITransactionData>();
            PaymentSettingsReader configuration           = new PaymentSettingsReader(paymentSystem);
            string autocapture = configuration.GetSetting("autocapture");

            if (request.QueryString[PaymentConstants.ActionKey] != PaymentConstants.CancelResponse)
            {
                string xmlReturn = this.CheckStatus(paymentSystem, paymentArgs);
                if (!string.IsNullOrEmpty(xmlReturn))
                {
                    var    quickPayResponse = this.ParseResult(xmlReturn);
                    string secret           = paymentSystem.Password;
                    string tohash           = string.Join(string.Empty, quickPayResponse.Where(x => x.Key != "md5check").Select(x => x.Value).ToArray()) + secret;

                    string md5Check = this.GetMD5Hash(tohash);
                    if (md5Check.Equals(quickPayResponse["md5check"]) && quickPayResponse["qpstat"].Equals("000"))
                    {
                        this.PaymentStatus = PaymentStatus.Succeeded;
                        transactionDataProvider.SaveCallBackValues(paymentArgs.ShoppingCart.OrderNumber, this.PaymentStatus.ToString(), quickPayResponse["transaction"], quickPayResponse["amount"], quickPayResponse["currency"], string.Empty, string.Empty, string.Empty, quickPayResponse["cardtype"]);
                        if (string.Compare(autocapture, this.ReservableBehavior, StringComparison.OrdinalIgnoreCase) == 0)
                        {
                            string transactionAmount = transactionDataProvider.GetPersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.TotalAmount) as string;
                            string orderNumber       = paymentArgs.ShoppingCart.OrderNumber;
                            string transactionNumber = transactionDataProvider.GetPersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.TransactionNumber) as string;

                            decimal           amount            = transactionAmount.FromCents();
                            ReservationTicket reservationTicket = new ReservationTicket
                            {
                                InvoiceNumber     = orderNumber,
                                AuthorizationCode = PaymentConstants.EmptyAuthorizationCode,
                                TransactionNumber = transactionNumber,
                                Amount            = amount
                            };
                            transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.ReservationTicket, reservationTicket);
                        }
                    }
                }
            }
            else
            {
                this.PaymentStatus = PaymentStatus.Canceled;
            }

            if (this.PaymentStatus != PaymentStatus.Succeeded)
            {
                transactionDataProvider.SavePersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.PaymentStatus, this.PaymentStatus.ToString());
            }
        }
Exemplo n.º 20
0
        public ActionResult Post([FromBody] PaymentSystem paymentSystem)
        {
            if (paymentSystemsList.Any(p => p.Id == paymentSystem.Id))
            {
                return(this.StatusCode((int)HttpStatusCode.Conflict));
            }
            paymentSystemsList.Add(paymentSystem);

            return(this.Ok());
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            CourierSystem          editor   = new CourierSystem();
            PackageSystem          spelling = new PackageSystem();
            PaymentSystem          post     = new PaymentSystem();
            FacadePostClientSystem facade   = new FacadePostClientSystem(editor, spelling, post);

            ClientPost.ClientCode(facade);
            Console.ReadLine();
        }
Exemplo n.º 22
0
        /// <summary>
        /// Processes the callback in terms of the HttpRequest and extracts either hidden form fields, or querystring parameters
        /// that is returned from the payment provider.
        /// Determines the payment status and saves that indication for later, could be in session, in db, or other storage.
        /// This information is important and used in the GetPaymentStatus().
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        public override void ProcessCallback([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.IsNotNull(paymentArgs.ShoppingCart, "Shopping cart is null");

            this.PaymentStatus = PaymentStatus.Failure;

            HttpRequest           request                 = HttpContext.Current.Request;
            PaymentSettingsReader configuration           = new PaymentSettingsReader(paymentSystem);
            ITransactionData      transactionDataProvider = Context.Entity.Resolve <ITransactionData>();
            string instantcapture = configuration.GetSetting("instantcapture");

            if (request.QueryString[PaymentConstants.ActionKey] != PaymentConstants.CancelResponse)
            {
                string transactionNumber = request.QueryString["tid"];
                string cardid            = request.QueryString["cardid"];
                string currency          = request.QueryString["cur"];
                string orderid           = request.QueryString["orderid"];
                string amount            = request.QueryString["amount"];
                string hashString        = request.QueryString["eKey"];
                string date = request.QueryString["date"];

                if (!this.CallBackIsvalid(paymentSystem, paymentArgs, currency, transactionNumber, amount, orderid, hashString, date))
                {
                    Log.Error("Callback parameters are invalid.", this);
                }
                else
                {
                    this.PaymentStatus = PaymentStatus.Succeeded;
                    transactionDataProvider.SaveCallBackValues(orderid, this.PaymentStatus.ToString(), transactionNumber, amount, currency, string.Empty, string.Empty, string.Empty, cardid);

                    if (string.Compare(instantcapture, this.ReservableBehavior, StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ReservationTicket reservationTicket = new ReservationTicket
                        {
                            InvoiceNumber     = orderid,
                            AuthorizationCode = hashString,
                            TransactionNumber = transactionNumber,
                            Amount            = amount.FromCents()
                        };
                        transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.ReservationTicket, reservationTicket);
                    }
                }
            }
            else
            {
                this.PaymentStatus = PaymentStatus.Canceled;
            }

            if (this.PaymentStatus != PaymentStatus.Succeeded)
            {
                transactionDataProvider.SavePersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.PaymentStatus, this.PaymentStatus.ToString());
            }
        }
            public static CashOutAttemptEntity Create <T>(ICashOutRequest request, PaymentSystem paymentSystem, T paymentFields, CashOutRequestTradeSystem tradeSystem)
            {
                var reqId  = Guid.NewGuid().ToString("N");
                var entity = CreateEntity(request, paymentSystem, paymentFields, tradeSystem);

                entity.PartitionKey = GeneratePartition(request.ClientId);
                entity.RowKey       = GenerateRowKey(reqId);
                entity.Status       = request.Status;

                return(entity);
            }
Exemplo n.º 24
0
        private void PaySysButtonClick(PaymentSystem paymentSystem)
        {
            var panel = panelWebMoney;

            if (paymentSystem == PaymentSystem.WebMoney)
            {
                panel.Visible = true;
                panelPaymentSystems.Visible = false;
                GetUserWalletsWebMoney();
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Calls the back isvalid.
        /// </summary>
        /// <param name="paymentSystem">The payment System.</param>
        /// <param name="paymentArgs">The payment Args.</param>
        /// <param name="currency">The currency.</param>
        /// <param name="transactionNumber">The transaction number.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="hashString">The hash string.</param>
        /// <param name="date">The current date.</param>
        /// <returns>
        /// the back is valid.
        /// </returns>
        protected bool CallBackIsvalid(PaymentSystem paymentSystem, PaymentArgs paymentArgs, string currency, string transactionNumber, string amount, string orderId, string hashString, string date)
        {
            if (string.IsNullOrEmpty(currency) || string.IsNullOrEmpty(transactionNumber) || string.IsNullOrEmpty(amount) || string.IsNullOrEmpty(orderId))
            {
                return(false);
            }

            string currentData = DateTime.Now.ToString("yyyyMMdd");

            return(orderId.Contains(paymentArgs.ShoppingCart.OrderNumber) && currentData.Equals(date));
        }
        private static string GetSqlText(PaymentSystem system, Script script)
        {
            var scriptPath = Path.Combine(BasePath, "SQL", system.ToString(), $"{script.ToString()}.sql");
            var fileSql    = File.ReadAllText(scriptPath);
            var sql        = UpdateTableAndSchemaNames(fileSql);

            var result = new StringBuilder();

            result.AppendLine();
            result.AppendLine();
            result.Append(sql);
            return(result.ToString());
        }
Exemplo n.º 27
0
        public void RegisterPaymentSystemTest_ValidInput_ExpectSuccess()
        {
            PaymentSystem system = new PaymentSystem
            {
                Password          = "******",
                PaymentSystemCode = "SBU",
                SecretKey         = "T3rr16132016"
            };
            TcmpCore core   = new TcmpCore();
            Result   result = core.RegisterPaymentSystem(system);

            Assert.AreEqual(result.StatusDesc, SharedCommonsGlobals.SUCCESS_STATUS_TEXT);
        }
Exemplo n.º 28
0
        /// <summary>
        /// Begins the payment.
        /// </summary>
        /// <param name="paymentSystem">The payment System.</param>
        /// <param name="paymentArgs">The payment arguments.</param>
        public override void Invoke([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");

            PaymentSettingsReader configuration = new PaymentSettingsReader(paymentSystem);

            string protocol    = configuration.GetSetting("protocol");
            string msgtype     = configuration.GetSetting("msgtype");
            string merchant    = paymentSystem.Username;
            string language    = this.Language(Sitecore.Context.Language.Name);
            string ordernumber = paymentArgs.ShoppingCart.OrderNumber;
            string amount      = paymentArgs.ShoppingCart.Totals.TotalPriceIncVat.ToCents();
            string callbackurl = paymentArgs.PaymentUrls.ReturnPageUrl;
            string currency    = this.Currency(paymentArgs.ShoppingCart.Currency.Code);
            string continueurl = paymentArgs.PaymentUrls.ReturnPageUrl;
            string cancelurl   = continueurl + PaymentConstants.CancelQueryString;
            string description = paymentArgs.Description;
            string ipaddress   = HttpContext.Current.Request.UserHostAddress;
            string testmode    = configuration.GetSetting("testmode");
            string autocapture = configuration.GetSetting("autocapture");
            string secret      = paymentSystem.Password;

            string tohash = string.Concat(protocol, msgtype, merchant, language, ordernumber, amount, currency, continueurl, cancelurl, callbackurl, autocapture, description, ipaddress, testmode, secret);
            string hash   = this.GetMD5Hash(tohash);

            ITransactionData transactionDataProvider = Context.Entity.Resolve <ITransactionData>();

            transactionDataProvider.SaveStartValues(ordernumber, amount, currency, paymentSystem.Code);

            NameValueCollection data = new NameValueCollection
            {
                { "protocol", protocol },
                { "msgtype", msgtype },
                { "merchant", merchant },
                { "language", language },
                { "ordernumber", ordernumber },
                { "amount", amount },
                { "currency", currency },
                { "continueurl", continueurl },
                { "cancelurl", cancelurl },
                { "callbackurl", callbackurl },
                { "autocapture", autocapture },
                { "description", description },
                { "ipaddress", ipaddress },
                { "testmode", testmode },
                { "md5check", hash },
            };

            this.PostData(paymentSystem.PaymentUrl, data);
        }
Exemplo n.º 29
0
        /// <summary>
        /// Cancels the payment reservation
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        /// <param name="reservationTicket">The reservation ticket.</param>
        public void CancelReservation([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs, [NotNull] ReservationTicket reservationTicket)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.ArgumentNotNull(reservationTicket, "reservationTicket");

            ITransactionData transactionDataProvider = Context.Entity.Resolve <ITransactionData>();

            Payment payment      = new Payment();
            int     pbsResponse  = 0;
            bool    deleteResult = payment.delete(int.Parse(paymentSystem.Username), long.Parse(reservationTicket.TransactionNumber), string.Empty, paymentSystem.Password, ref pbsResponse);

            transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, deleteResult ? PaymentConstants.CancelSuccess : string.Format("pbsResponse={0}", pbsResponse));
        }
Exemplo n.º 30
0
 public IParseble Parse(JSONNode purchaseNode)
 {
     if (purchaseNode.Count == 0)
         return null;
     if(purchaseNode ["virtual_currency"] != null)
         virtualCurrency = new VirtualCurrency ().Parse (purchaseNode ["virtual_currency"]) as VirtualCurrency;
     if(purchaseNode ["virtual_items"] != null)
         virtualItems = new VirtualItems().Parse(purchaseNode ["virtual_items"]) as VirtualItems;
     if(purchaseNode ["subscription"] != null)
         subscription = new Subscription ().Parse (purchaseNode ["subscription"]) as Subscription;
     if(purchaseNode ["payment_system"] != null)
         paymentSystem = new PaymentSystem().Parse(purchaseNode ["payment_system"]) as PaymentSystem;
     if (purchaseNode ["checkout"] != null)
         checkout = new Checkout ().Parse(purchaseNode ["checkout"]) as Checkout;;
     return this;
 }
Exemplo n.º 31
0
        /// <summary>
        /// Processes the callback in terms of the HttpRequest and extracts either hidden form fields, or querystring parameters
        /// that is returned from the payment provider.
        /// Determines the payment status and saves that indication for later, could be in session, in db, or other storage.
        /// This information is important and used in the GetPaymentStatus().
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="paymentArgs">The payment args.</param>
        public override void ProcessCallback([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs)
        {
            Assert.ArgumentNotNull(paymentSystem, "paymentSystem");
            Assert.ArgumentNotNull(paymentArgs, "paymentArgs");
            Assert.IsNotNull(paymentArgs.ShoppingCart, "Shopping cart is null");

            this.PaymentStatus = PaymentStatus.Failure;

            HttpRequest      request = HttpContext.Current.Request;
            ITransactionData transactionDataProvider = Context.Entity.Resolve <ITransactionData>();

            if (request.QueryString[PaymentConstants.ActionKey] != PaymentConstants.CancelResponse)
            {
                string orderRef      = request["orderRef"];
                long   accountNumber = TypeUtil.TryParse <long>(paymentSystem.Username, 0);
                string secretKey     = paymentSystem.Password;

                if (!string.IsNullOrEmpty(orderRef) && accountNumber > 0)
                {
                    ArrayList param = new ArrayList
                    {
                        accountNumber,
                        orderRef,
                        secretKey
                    };
                    string hash = this.CreateMD5Hash(param);
                    try
                    {
                        this.CompleteCallback(paymentSystem, orderRef, accountNumber, hash, transactionDataProvider);
                    }
                    catch (Exception exception)
                    {
                        Log.Warn(exception.Message, exception, this);
                    }
                }
            }
            else
            {
                this.PaymentStatus = PaymentStatus.Canceled;
            }

            if (this.PaymentStatus != PaymentStatus.Succeeded)
            {
                transactionDataProvider.SavePersistentValue(paymentArgs.ShoppingCart.OrderNumber, TransactionConstants.PaymentStatus, this.PaymentStatus.ToString());
            }
        }
Exemplo n.º 32
0
        public virtual Tuple <bool, string> pay(string paymentDetails, double amount, bool Failed = false)
        {
            if (!PaymentSystem.IsAlive(Failed))
            {
                return(new Tuple <bool, string>(false, "Not Connected"));
            }
            string[] parsedDetails   = paymentDetails.Split('&');
            int      transaction_num = PaymentSystem.Pay(parsedDetails[0], parsedDetails[1].ToInt32(), parsedDetails[2].ToInt32(), parsedDetails[3], parsedDetails[4], parsedDetails[5]);

            if (transaction_num < 0)
            {
                return(new Tuple <bool, string>(false, "Payment Failed"));
            }

            Logger.logEvent(this, System.Reflection.MethodBase.GetCurrentMethod());
            return(new Tuple <bool, string>(true, "OK"));
        }
Exemplo n.º 33
0
 public WalletError SetPaymentWalletsBySystem(ProtectedOperationContext secCtx,
                                              PaymentSystem syst,
                                              List<UserPaymentSystem> actualPaySys,
                                              string userLogin, string walletPwrd)
 {
     if (Channel == null)
         throw new Exception("WalletManagerProxy: связь не установлена");
     try
     {
         return Channel.SetPaymentWalletsBySystem(secCtx, syst, actualPaySys, userLogin, walletPwrd);
     }
     catch
     {
         RenewFactory();
         try
         {
             return Channel.SetPaymentWalletsBySystem(secCtx, syst, actualPaySys, userLogin, walletPwrd);
         }
         catch (Exception ex2)
         {
             Logger.Error("SetPaymentWalletsBySystem() error: ", ex2);
             return WalletError.CommonError;
         }
     }
 }
Exemplo n.º 34
0
        public WalletError SetPaymentWalletsBySystem(ProtectedOperationContext secCtx,
            PaymentSystem syst,
            List<UserPaymentSystem> actualPaySys,
            string userLogin, string walletPwrd)
        {
            if (!UserSessionStorage.Instance.PermitUserOperation(secCtx, false, false))
                return WalletError.InsufficientRights;

            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    var user = ctx.PLATFORM_USER.FirstOrDefault(u => u.Login == userLogin);
                    if (user == null)
                        return WalletError.AuthenticationError;

                    // уничтожить старые записи того же типа
                    var existRecs =
                        ctx.USER_PAYMENT_SYSTEM.Where(r => r.UserId == user.ID && r.SystemPayment == (int)syst).ToList();
                    foreach (var rec in existRecs)
                        ctx.USER_PAYMENT_SYSTEM.Remove(rec);
                    ctx.SaveChanges();

                    // добавить новые записи
                    foreach (var paySyst in actualPaySys)
                    {
                        paySyst.UserId = user.ID;
                        paySyst.SystemPayment = syst;
                        ctx.USER_PAYMENT_SYSTEM.Add(LinqToEntity.UndecorateUserPaymentSystem(paySyst));
                    }
                    ctx.SaveChanges();
                    return WalletError.OK;
                }
            }
            catch (DbUpdateException ex)
            {
                if (ex.InnerException.InnerException is SqlException)
                {
                    Logger.Error("SetPaymentWalletsBySystem() error: возможно, запись с таким RootId и PurseId уже есть в таблице USER_PAYMENT_SYSTEM", ex);
                    return WalletError.ServerSqlError;
                }
                Logger.Error("SetPaymentWalletsBySystem() error", ex);
                return WalletError.ServerError;
            }
            catch (Exception ex)
            {
                Logger.Error("SetPaymentWalletsBySystem() error", ex);
                return WalletError.ServerError;
            }
        }
 void Awake()
 {
     ps = GetComponent<PaymentSystem>();
     da = GetComponent<DistanceAccumulator>();
 }
Exemplo n.º 36
0
 /// <summary>
 /// Получение универсального идентификатора кошелька T# по реквизитам, полученным из платёжной системы
 /// </summary>
 protected int? GetTradeSharpeWalletIdByPaySysRequisite(PaymentSystem systemPayment, string rootId, string purseId)
 {
     try
     {
         using (var ctx = DatabaseContext.Instance.Make())
         {
             var userPaySys =
                 ctx.USER_PAYMENT_SYSTEM.SingleOrDefault(
                     x => x.SystemPayment == (byte) systemPayment && x.RootId == rootId && x.PurseId == purseId);
             if (userPaySys == null) return null;
             return userPaySys.UserId;
         }
     }
     catch (Exception ex)
     {
         Logger.Error("GetTradeSharpeWalletIdByPaySysRequisite()", ex);
         return null;
     }
 }
Exemplo n.º 37
0
        /// <summary>
        /// Уведомление о потереном платеже. 
        /// </summary>
        /// <param name="currency">Валюта кошелька в платёжной системе</param>
        /// <param name="amount"></param>
        /// <param name="data"></param>
        /// <param name="paymentSystem"></param>
        /// <param name="requisites"></param>
        protected void ReportOnFailPayment(string currency, decimal amount, DateTime data, PaymentSystem paymentSystem, string requisites)
        {
            #region messageFail
            var messageFail = string.Format(
                            "ReportOnFailPayment() - Не удалось внести в базу данных запись о потерянном платеже на кошелёк платёжной системы {0}. \r\n" +
                            "Админисратор базы данных должен обязательно внести эту информацию врчную. Реквизиты платежа: валюта (currency) - {1}, \r\n" +
                            "размер внесённых средств (amount) {2}, дата (data) {3}. Дополнительные сведения: {4}",
                            paymentSystem, currency, amount,
                            data, requisites);
            #endregion

            var dictionary = ParsRequisites(requisites);
            try
            {
                using (var ctx = DatabaseContext.Instance.Make())
                {
                    ctx.PAYMENT_SYSTEM_TRANSFER.Add(new PAYMENT_SYSTEM_TRANSFER
                        {
                            Ammount = amount,
                            Currency = currency,
                            DateProcessed = DateTime.Now,
                            DateValue = data,
                            UserPaymentSys = (int)paymentSystem,
                            SourcePaySysAccount = dictionary.ContainsKey(RequisitesDictionaryKey.SourcePaySysAccount)
                                                      ? dictionary[RequisitesDictionaryKey.SourcePaySysAccount]
                                                      : string.Empty,
                            SourcePaySysPurse = dictionary.ContainsKey(RequisitesDictionaryKey.SourcePaySysPurse)
                                                    ? dictionary[RequisitesDictionaryKey.SourcePaySysPurse]
                                                    : string.Empty,
                            Comment = dictionary.ContainsKey(RequisitesDictionaryKey.Comment)
                                          ? dictionary[RequisitesDictionaryKey.Comment]
                                          : string.Empty
                        });

                    try
                    {
                        ctx.SaveChanges();
                        Logger.Info("Платёж оформлен как неопознанный.");
                    }
                    catch (Exception ex)
                    {

                        Logger.Error(messageFail, ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(messageFail, ex);
            }
        }
        /// <summary>
        /// Performs the completion of the conversation with PayPal.
        /// </summary>
        /// <param name="paymentSystem">The payment system.</param>
        /// <param name="orderRef">The order ref.</param>
        /// <param name="accountNumber">The account number.</param>
        /// <param name="hash">The hash.</param>
        /// <param name="transactionDataProvider">The transaction data provider.</param>
        protected void CompleteCallback(PaymentSystem paymentSystem, string orderRef, long accountNumber, string hash, ITransactionData transactionDataProvider)
        {
            PaymentSettingsReader configuration = new PaymentSettingsReader(paymentSystem);
              string purchaseOperation = configuration.GetSetting("purchaseOperation");
              PaymentStatus paymentStatusResult = PaymentStatus.Failure;

              PxOrder payexOrder = new PxOrder();
              string xmlReturn = payexOrder.Complete(accountNumber, orderRef, hash);

              string transactionNumber = this.ParseRes(xmlReturn, "/payex/transactionNumber");
              string orderNumber = this.ParseRes(xmlReturn, "/payex/orderId");
              string transactionAmount = this.ParseRes(xmlReturn, "/payex/amount");
              string errorCode = this.ParseRes(xmlReturn, "/payex/status/errorCode");
              int transactionStatus = int.Parse(this.ParseRes(xmlReturn, "/payex/transactionStatus"));

              if (errorCode == "OK")
              {
            switch (transactionStatus)
            {
              case (int)TransactionStatus.Sale:
              case (int)TransactionStatus.Authorize:
              {
            paymentStatusResult = PaymentStatus.Succeeded;
            transactionDataProvider.SaveCallBackValues(orderNumber, paymentStatusResult.ToString(), transactionNumber, transactionAmount, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);

            if (string.Compare(purchaseOperation, this.ReservableTransactionType, StringComparison.OrdinalIgnoreCase) == 0)
            {
              decimal amount = transactionAmount.FromCents();
              ReservationTicket reservationTicket = new ReservationTicket
              {
                InvoiceNumber = orderNumber,
                AuthorizationCode = PaymentConstants.EmptyAuthorizationCode,
                TransactionNumber = transactionNumber,
                Amount = amount
              };
              transactionDataProvider.SavePersistentValue(reservationTicket.InvoiceNumber, PaymentConstants.ReservationTicket, reservationTicket);
            }

            break;
              }

              default:
              {
            string transactionErrorCode = this.ParseRes(xmlReturn, "/payex/errorDetails/transactionErrorCode");
            if (transactionErrorCode == OperationCanceledError)
            {
              paymentStatusResult = PaymentStatus.Canceled;
            }

            break;
              }
            }
              }

              this.PaymentStatus = paymentStatusResult;
        }
Exemplo n.º 39
0
        /// <summary>
        /// Calls the back isvalid.
        /// </summary>
        /// <param name="paymentSystem">The payment System.</param>
        /// <param name="paymentArgs">The payment Args.</param>
        /// <param name="currency">The currency.</param>
        /// <param name="transactionNumber">The transaction number.</param>
        /// <param name="amount">The amount.</param>
        /// <param name="orderId">The order id.</param>
        /// <param name="hashString">The hash string.</param>
        /// <param name="date">The current date.</param>
        /// <returns>
        /// the back is valid.
        /// </returns>
        protected bool CallBackIsvalid(PaymentSystem paymentSystem, PaymentArgs paymentArgs, string currency, string transactionNumber, string amount, string orderId, string hashString, string date)
        {
            if (string.IsNullOrEmpty(currency) || string.IsNullOrEmpty(transactionNumber) || string.IsNullOrEmpty(amount) || string.IsNullOrEmpty(orderId))
              {
            return false;
              }

              string currentData = DateTime.Now.ToString("yyyyMMdd");
              return orderId.Contains(paymentArgs.ShoppingCart.OrderNumber) && currentData.Equals(date);
        }
Exemplo n.º 40
0
 private void PaySysButtonClick(PaymentSystem paymentSystem)
 {
     var panel = panelWebMoney;
     if (paymentSystem == PaymentSystem.WebMoney)
     {
         panel.Visible = true;
         panelPaymentSystems.Visible = false;
         GetUserWalletsWebMoney();
     }
 }
Exemplo n.º 41
0
 /// <summary>
 /// Processes the callback in terms of the HttpRequest and extracts either hidden form fields, or querystring parameters
 /// that is returned from the payment provider.
 /// Determines the payment status and saves that indication for later, could be in session, in db, or other storage.
 /// This information is important and used in the PaymentStatus.
 /// </summary>
 /// <param name="paymentSystem">The payment system.</param>
 /// <param name="paymentArgs">The payment arguments.</param>
 public abstract void ProcessCallback(PaymentSystem paymentSystem, PaymentArgs paymentArgs);
Exemplo n.º 42
0
 /// <summary>
 /// Invokes the payment.
 /// </summary>
 /// <param name="paymentSystem">The payment system.</param>
 /// <param name="paymentArgs">The payment args.</param>
 public abstract void Invoke(PaymentSystem paymentSystem, PaymentArgs paymentArgs);