public ActionResult resetBalance()
        {
            int playToken = 0;
            Int32.TryParse(Request.Params["play_token"], out playToken);
            int freePlayToken = 0;
            Int32.TryParse(Request.Params["free_play_token"], out freePlayToken);

            var diffPlayToken = playToken - CurrentUser.play_token;

            coin_transaction transaction = new coin_transaction();
            transaction.order_id = Guid.NewGuid().ToString();
            transaction.customer_account_id = CurrentUser.Id;
            transaction.amount = diffPlayToken;
            transaction.description = GoPlayConstantValues.S_RESETBALANCE_DESCRIPTION;
            transaction.status = Helper.GetDescription(TransactionStatus.Success);

            var diffFreePlayToken = freePlayToken - CurrentUser.free_play_token;
            free_coin_transaction freeTransaction = new free_coin_transaction();
            freeTransaction.order_id = Guid.NewGuid().ToString();
            freeTransaction.customer_account_id = CurrentUser.Id;
            freeTransaction.amount = diffFreePlayToken;
            freeTransaction.description = GoPlayConstantValues.S_RESETBALANCE_DESCRIPTION;
            freeTransaction.status = Helper.GetDescription(TransactionStatus.Success);

            var api = GoPlayApi.Instance;
            if (api.CreateCoinTransaction(transaction).Data != null
                && api.CreateFreeCoinTransaction(freeTransaction) > 0)
                this.Flash(string.Format(GoPlayConstantValues.S_RESETBALANCE_SUCCESS, freePlayToken, playToken), FlashLevel.Success);
            else
                this.Flash("Account balance was reset fail", FlashLevel.Error);

            return RedirectToAction("profile", "account");
        }
        public Result<customer_account> UpdateProfile(GtokenAPILoginModel gtokenProfile, int? game_id = null)
        {
            try
            {
                var repo = Repo.Instance;
                var profile = gtokenProfile.profile;
                var inviterUsername = profile.inviter;
                customer_account user = null;
                int inviterId = 0;
                int userId = -1;
                using (var db = repo.OpenConnectionFromPool())
                {
                    var inviter = repo.GetCustomerByUserName(db, inviterUsername).Data;

                    if (!string.IsNullOrEmpty(inviterUsername) && inviter == null)
                    {
                        var gtokenProfileData = GTokenAPIAccount(new GtokenModelAccountAction
                        {
                            enumAction = EGtokenAction.Profile,
                            username = inviterUsername,
                            session = gtokenProfile.session
                        }).Result;

                        if (!gtokenProfileData.HasData)
                        {
                            return Result<customer_account>.Make(null, ErrorCodes.InvalidSession);
                        }

                        var profileData = gtokenProfileData.Data;
                        var newId = repo.CreateCustomerAccount(db,
                            profileData.profile.email,
                            profileData.profile.account,
                            profileData.profile.country_code,
                            profileData.profile.country_name);

                        if (newId > 0)
                        {
                            inviterId = newId;
                            CreateFreeCoinTransaction(new free_coin_transaction
                            {
                                order_id = Guid.NewGuid().ToString(),
                                customer_account_id = newId,
                                status = ConstantValues.S_SUCCESS,
                                description = ConstantValues.S_DESCRIPTION_CREATE_FREE_COIN_TRANSACTION,
                                amount = 1
                            });
                            userId = newId;
                        }
                        else
                        {
                            return Result<customer_account>.Make(null, ErrorCodes.InvalidUserName);
                        }
                    }

                    if (inviter != null)
                        inviterId = inviter.id;

                    user = repo.GetCustomerByUserName(db, profile.account).Data;
                    if (user == null)
                    {
                        var newId = repo.CreateCustomerAccount(db,
                            profile.email,
                            profile.account,
                            profile.country_code,
                            profile.country_name,
                            profile.nickname,
                            profile.gender,
                            profile.bio,
                            game_id);

                        if (newId > 0)
                        {
                            var transacton = new free_coin_transaction
                            {
                                order_id = Guid.NewGuid().ToString(),
                                customer_account_id = newId,
                                status = ConstantValues.S_SUCCESS,
                                description = ConstantValues.S_DESCRIPTION_CREATE_FREE_COIN_TRANSACTION,
                                amount = 1
                            };
                            CreateFreeCoinTransaction(transacton);
                            userId = newId;
                        }
                        else
                        {
                            return Result<customer_account>.Make(null, ErrorCodes.InvalidUserName);
                        }
                    }
                    else
                    {
                        repo.UpdateCustomerAccount(db, user.id,
                            profile.email,
                            profile.country_code,
                            profile.country_name,
                            profile.nickname,
                            profile.gender,
                            profile.bio);
                        userId = user.id;
                    }

                    user = repo.GetCustomerById(db, userId).Data;
                    if (user != null && !string.IsNullOrEmpty(inviterUsername) && inviterId > 0)
                    {
                        AddInviter(gtokenProfile.session, user, inviterId, inviterUsername);
                    }

                    var i = 0;
                    if (string.IsNullOrEmpty(user.cover_filename))
                    {
                        i = user.id % 11;
                        user.cover_filename = string.Format(ConstantCommon.COVER_URL, i);
                    }
                    if (string.IsNullOrEmpty(user.avatar_filename))
                    {
                        i = user.id % 15;
                        user.avatar_filename = string.Format(ConstantCommon.AVATAR_URL, i);
                    }
                    repo.UpdateCustomerAccount(db, user.id, user.country_code, user.country_name, DateTime.UtcNow, user.avatar_filename, user.cover_filename);

                    return Result<customer_account>.Make(repo.GetCustomerById(db, userId).Data, null);
                }
            }
            catch
            {
                return Result<customer_account>.Make(null, ErrorCodes.ServerError);
            }
        }
 public int CreateFreeCoinTransaction(IDbConnection db, free_coin_transaction freeCoin)
 {
     string sql = @"INSERT INTO free_coin_transaction(
     customer_account_id, amount, game_id, credit_type_id, package_id, 
     created_at, description, status, order_id, topup_card_id, payment_method, 
     price, ip_address, country_code)
     VALUES (
     @customer_account_id, @amount, @game_id, @credit_type_id, @package_id, 
     @created_at, @description, @status, @order_id, @topup_card_id, @payment_method, 
     @price, @ip_address, @country_code)
      RETURNING id";
     return db.Query<int>(sql, freeCoin).FirstOrDefault();
 }
        private free_coin_transaction CreateFreeCoinTrans(decimal playTokenAmount)
        {
            var coinTransaction = new free_coin_transaction();
            coinTransaction.order_id = Guid.NewGuid().ToString();
            coinTransaction.customer_account_id = this.user.id;
            coinTransaction.amount = -1 * playTokenAmount;
            coinTransaction.game_id = this.game.id;

            if (this.exchangeOption is CreditType)
            {
                coinTransaction.credit_type_id = this.exchangeOption.id;
            }
            else if (this.exchangeOption is Package)
            {
                coinTransaction.package_id = exchangeOption.id;
            }
            coinTransaction.status = "payment_created";
            coinTransaction.description = String.Format("Exchange for {0} in {1}", exchangeOption.name, game.name);

            var country_name = String.Empty;
            ip.GetCountryCode(c => coinTransaction.country_code = c, n => country_name = n);
            coinTransaction.ip_address = ip.ToString();
            var api = GoPlayApi.Instance;

            var id = api.CreateFreeCoinTransaction(coinTransaction);
            return api.GetFreeCoinTransactionById(id).Data;

        }
        public free_coin_transaction CreateFreeCoinTrans(ApplicationUser user, topup_card card)
        {
            var api = GoPlayApi.Instance;
            var transaction = new free_coin_transaction();
            transaction.order_id = Guid.NewGuid().ToString();
            transaction.customer_account_id = user.Id;
            transaction.amount = card.amount;
            transaction.price = card.amount;
            transaction.payment_method = "Top Up Card";
            transaction.status = "success";
            transaction.description = String.Format("You topped up {0} Play Token", Helper.displayDecimal(card.amount));
            transaction.topup_card_id = card.id;
            transaction.created_at = DateTime.UtcNow;

            IPAddress ip = WebIpHelper.GetClientIp(Request);
            var country_name = String.Empty;
            ip.GetCountryCode(c => transaction.country_code = c, n => country_name = n);
            transaction.ip_address = ip.ToString();

            api.CreateFreeCoinTransaction(transaction);
            return transaction;
        }
        public async Task<ActionResult> IpnHandler()
        {
            try
            {
                // extract ipn data into a string
                byte[] param = Request.BinaryRead(Request.ContentLength);
                string strRequest = Encoding.ASCII.GetString(param);

                // append PayPal verification code to end of string
                strRequest += "&cmd=_notify-validate";

                logger.Debug(strRequest);

                // create an HttpRequest channel to perform handshake with PayPal
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["PAYPAL_URL"]);
                req.Method = "POST";
                req.ContentType = "application/x-www-form-urlencoded";
                req.ContentLength = strRequest.Length;

                // send data back to PayPal to request verification
                StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), Encoding.ASCII);
                streamOut.Write(strRequest);
                streamOut.Close();

                // receive response from PayPal
                StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
                string strResponse = streamIn.ReadToEnd();
                streamIn.Close();

                // if PayPal response is successful / verified
                logger.Debug(strResponse);
                if (strResponse.Equals("VERIFIED"))
                {
                    // paypal has verified the data, it is safe for us to perform processing now

                    // extract the form fields expected: buyer and seller email, payment status, amount
                    // string payerEmail = Request.Form["payer_email"];
                    string paymentStatus = Request.Form["payment_status"];
                    //string receiverEmail = Request.Form["receiver_email"];
                    string amount = Request.Form["mc_gross"];
                    string txn_id = Request.Form["txn_id"];
                    string txn_type = Request.Form["txn_type"];
                    string payment_type = Request.Form["payment_type"];

                    logger.Debug(txn_id);
                    logger.Debug(txn_type);

                    if (txn_type == "cart" && payment_type == "instant")
                    {
                        if (paymentStatus.Equals("Completed"))
                        {
                            var api = GoPlayApi.Instance;
                            var paypalHelper = new PaypalHelper();
                            var sale = Sale.Get(paypalHelper.GetGetAPIContext(), txn_id);
                            if (sale != null)
                            {
                                var payment_id = sale.parent_payment;
                                var transaction = api.GetCoinTransactionByPaypalPaymentId(payment_id);
                                if (!transaction.HasData)
                                {
                                    return new HttpStatusCodeResult(HttpStatusCode.OK);
                                }


                                var user = api.GetUserById(transaction.Data.customer_account_id).Data;
                                //if transaction.use_gtoken:
                                //# Charge 25% in GToken
                                //gtoken = transaction.amount / 4
                                //sufficientBalance = venvici.checkGToken(user, gtoken)
                                //if not sufficientBalance:
                                //    transaction.status = u'failure'
                                //    transaction.description += u'. Paypal approved but insufficient Play Token'
                                //    store.commit()
                                //    return '', 200
                                //venvici.deductGToken(user, transaction)

                                if (transaction.Data.status == Helper.GetDescription(TransactionStatus.Pending))
                                {
                                    if (user.HasDiscount())
                                    {
                                        user.is_discount_permanent = true;
                                        api.UpdateCustomerAccount(user.id, user.is_discount_permanent);
                                    }
                                    transaction.Data.status = Helper.GetDescription(TransactionStatus.Success);
                                    api.UpdateCoinTransactionStatus(transaction.Data.id, transaction.Data.status);
                                    //update status GTOKEN transaction
                                    await api.updateGTokenTransactionStatus(transaction.Data.order_id, Helper.GetDescription(TransactionStatus.Success));

                                }

                                if (!string.IsNullOrEmpty(user.inviter_username))
                                {
                                    var inviter = api.GetUserByUserName(user.inviter_username);
                                    if (inviter.Data.username == "gdc")
                                    {
                                        string sqlString = @"SELECT * FROM coin_transaction
                                WHERE customer_account_id={0} AND status={1} AND amount >= 5 AND sender_account_id is NULL ";
                                        var transactions = api.GetCoinTransactionsByCustomQuery(String.Format(sqlString, user.id, "success"));
                                        if (transactions.HasData && transactions.Data.Count == 1)
                                        {
                                            var freeCoin = new free_coin_transaction()
                                            {
                                                order_id = Guid.NewGuid().ToString(),
                                                customer_account_id = user.id,
                                                status = Helper.GetDescription(TransactionStatus.Success),
                                                description = "GDC Promotion",
                                                amount = 3
                                            };
                                            api.CreateFreeCoinTransaction(freeCoin);
                                        }
                                    }
                                }
                                //Venici - from 15/3/2015    
                                //venvici.updateVenviciBalance(user,transaction)

                            }
                        }
                    }
                    else
                    {
                        string adminEmail = ConfigurationManager.AppSettings["ADMINS"];
                        string subject = "Another payment type";
                        string body = String.Format("Transaction id: {0}, payment type: {1}, txn type: {2}", txn_id, payment_type, txn_type);
                        var from = new MailAddress("*****@*****.**", "GoPlay Admin");
                        var to = new MailAddress(adminEmail);
                        var message = new MailMessage(from, to)
                        {
                            Subject = subject,
                            Body = body
                        };
                        EmailHelper.SendMail(message);

                    }
                }
            }
            catch (Exception ex)
            {
                logger.Fatal("API Handler: " + ex.StackTrace);
            }

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }
 public int CreateFreeCoinTransaction(free_coin_transaction freeCoinTrans)
 {
     var repo = Repo.Instance;
     freeCoinTrans.created_at = DateTime.UtcNow;
     using (var db = repo.OpenConnectionFromPool())
     {
         var newId = repo.CreateFreeCoinTransaction(db, freeCoinTrans);
         if (newId > 0)
         {
             StormFlushedFreeCoinTransaction(newId);
         }
         return newId;
     }
 }