.Net Core 实现账户充值,还款,用户登录(WebApi的安全)

个人未开通网站: http://justin1107.pc.evyundata.cn/vip_justin1107.html


Api 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Iot.Loan.Exam.Dapper;
using Iot.Loan.Exam.Models;
using JWT.Exceptions;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace Iot.Loan.Exam.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [EnableCors("any")]
    public class LoanController : ControllerBase
    {
        JWTHelper helper = new JWTHelper();
        private IDapper dapper;
        public LoanController(IDapper _dapper)
        {
            dapper = _dapper;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpPost]
        public string Login([FromForm]UserInfo info)
        {
            //得到登录model
            UserInfo model = dapper.Login(info);
            if (model != null)
            {
                //定义字典存放用户登录的信息
                Dictionary<string, object> keys = new Dictionary<string, object>();
                keys.Add("User_Name", model.User_Name);
                keys.Add("User_ID", model.User_ID);
                keys.Add("User_Pwd", model.User_Pwd);
                //得到toekn,给他失效时间
                string token = helper.GetToken(keys, 30000);
                return token;
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 还款信息列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<HuK_UserInfo>> Select(string token)
        { 
            //token解码
            string json = helper.GetPayload(token);
            //反序列化
            UserInfo model = JsonConvert.DeserializeObject<UserInfo>(json);
            if (model != null)
            {
                return await Task.Run(() => { return dapper.Select(model.User_ID); });
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 账户信息列表
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<List<ZhuanHu_UserInfo>> ZhuanHuSelect(string token)
        {
            //token解码
            string json = helper.GetPayload(token);
            //反序列化
            UserInfo model = JsonConvert.DeserializeObject<UserInfo>(json);
            if (model != null)
            {
                return await Task.Run(() => { return dapper.YSelect(model.User_ID); });
            }
            else
            {
                return null;
            }
        }
        /// <summary>
        /// 还款
        /// </summary>
        /// <param name="HkId">还款ID</param>
        /// <param name="token">用户登录的token,</param>
        /// <returns></returns>
        [HttpPost]
        public int HK(int HkId, string token)
        {
            string json = helper.GetPayload(token);
            UserInfo model = JsonConvert.DeserializeObject<UserInfo>(json);
            if (model != null)
            {
                return dapper.HunKuan(model.User_ID, HkId);
            }
            else
            {
                return 0;
            }
        }
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="money">充值金额</param>
        /// <param name="token">用户登录保存的Token</param>
        /// <returns></returns>
        [HttpPost]
        public int CZ(decimal money, string token)
        {
            //token解码
            string json = helper.GetPayload(token);
            //反序列化
            UserInfo info = JsonConvert.DeserializeObject<UserInfo>(json);
            if (info != null)
            {
                return dapper.CzMoney(info.User_ID, money);
            }
            else
            {
                return 0;
            }
        }
    }
}
View Code

cshtml

<script src="~/lib/jquery/dist/jquery.js"></script>
<div style="150px;height:100px;background-color:aqua">
    <table>
        <tr>
            <th style="200px;">可用余额<br /></th>
            <th id="th"></th>
        </tr>
        <tr>
            <th colspan="2">
                <input hidden="hidden" id="cz_money" type="text" />
                <input id="btn_CZ" type="button" value="充值" />&nbsp;&nbsp;&nbsp;&nbsp;
                <input id="btn_TX" type="button" value="提现" />
            </th>
        </tr>
    </table>
</div>
<div style="margin-left:0px;margin-top:15px;">
    <table>
        <tr>
            <th>还款期数</th>
            <th>还款日期</th>
            <th>应还本金</th>
            <th>还款利息</th>
            <th>还款总额</th>
            <th>还款状态</th>

        </tr>
        <tbody id="tb"></tbody>
    </table>
</div>
<script>
    $('#btn_CZ').click(function () {
        $.ajax({
            url: 'http://localhost:53048/Api/Loan/CZ?money=' + $('#cz_money').val() + '&token=' + localStorage["User_Name"],
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            accepts: 'application/x-www-form-urlencoded',
            success: function (data) {
                if (data > 0) {
                    $('#cz_money').attr('hidden', 'hidden');
                    window.location.reload();
                } else {
                    alert("网络不可用,无法充值");
                    return;
                }
            }
        })
    })
    $.ajax({
        url: 'http://localhost:53048/Api/Loan/Select?token=' + localStorage["User_Name"],
        type: 'post',
        contentType: 'application/x-www-form-urlencoded',
        accepts: 'application/x-www-form-urlencoded',
        success: function (data) {
            var tr = '';
            var state = '';
            $.each(data, function (i, t) {
                $('#tb').empty();
                if (t.hk_State == 1) {
                    state = '已还清';
                } else if (t.hk_State == 0) {
                    state = '<a href="#" onclick="HuK(' + t.huanK_id + ')">还款</a>';
                } else if (t.hk_State == 2) {
                    state = '还款';
                }
                tr += '<tr>';
                tr += '<th>' + t.hK_QiShu + '</th>';
                tr += '<th>' + t.hk_DataTime + '</th>';
                tr += '<th>' + t.hk_BenJin + '</th>';
                tr += '<th>' + t.hk_LiXi + '</th>';
                tr += '<th>' + (t.hk_BenJin + t.hk_LiXi) + '</th>';
                tr += '<th>' + state + '</th>';
                tr += '</tr>';
            })
            $('#tb').append(tr);
        }
    })
    $.ajax({
        url: 'http://localhost:53048/Api/Loan/ZhuanHuSelect?token=' + localStorage["User_Name"],
        type: 'post',
        contentType: 'application/x-www-form-urlencoded',
        accepts: 'application/x-www-form-urlencoded',
        success: function (data) {
            var th = '';
            $.each(data, function (i, t) {
                $('#th').empty();
                th += '<th>' + t.zhuHu_Money + '</th>';
            })
            $('#th').append(th);
        }
    })
    function HuK(hkid) {
        $.ajax({
            url: 'http://localhost:53048/Api/Loan/HK?HkId=' + hkid + '&token=' + localStorage["User_Name"],
            type: 'post',
            contentType: 'application/x-www-form-urlencoded',
            accepts: 'application/x-www-form-urlencoded',
            success: function (data) {
                if (data > 0) {
                    alert("还款成功");
                    window.location.reload();
                } else if (data == 0) {
                    alert("还款失败");
                } else {
                    alert("余额不足");
                    $('#cz_money').removeAttr('hidden');
                }
            }
        })
    }
</script>
View Code

DapperHelper(我使用的是接口)

    public class DapperHelper : IDapper
    {
        /// <summary>
        /// 充值
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="money"></param>
        /// <returns></returns>
        public int CzMoney(int UserId, decimal money)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Iot.Loan_DB;Integrated Security=True"))
            {
                return conn.Execute($"update ZhuanHu_UserInfo set ZhuHu_Money=ZhuHu_Money+{money} where User_Id={UserId}");
            }
        }
        /// <summary>
        /// 还款
        /// </summary>
        /// <param name="UserId"></param>
        /// <param name="HkId"></param>
        /// <returns></returns>
        public int HunKuan(int UserId, int HkId)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Iot.Loan_DB;Integrated Security=True"))
            {
                object Zhmoney = conn.ExecuteScalar($"select ZhuHu_Money from ZhuanHu_UserInfo where User_Id={UserId}");

                object HkMoney = conn.ExecuteScalar($"select Hk_BenJin+Hk_LiXi from HuK_UserInfo where HuanK_id={HkId}");
                if (Convert.ToDouble(Zhmoney) >= Convert.ToDouble(HkMoney))
                {
                    //开始把账户余额减少
                    int h = conn.Execute($"update ZhuanHu_UserInfo set ZhuHu_Money=ZhuHu_Money-{HkMoney} where User_Id={UserId}");
                    if (h > 0)
                    {
                        //修改还款状态
                        return conn.Execute($"update HuK_UserInfo set Hk_State=1 where HuanK_id={HkId}");
                    }
                    else
                    {
                        return 0;
                    }
                }
                else
                {
                    //余额不足
                    return -1;
                }

            }
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public UserInfo Login(UserInfo user)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Iot.Loan_DB;Integrated Security=True"))
            {
                string sql = $"select * from UserInfo where User_Name='{user.User_Name}' and User_Pwd='{user.User_Pwd}'";
                return conn.Query<UserInfo>(sql).FirstOrDefault();
            }

        }
        /// <summary>
        /// 还款信息列表
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<HuK_UserInfo> Select(int UserId)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Iot.Loan_DB;Integrated Security=True"))
            {
                string sql = $"select * from HuK_UserInfo where User_Id={UserId}";
                return conn.Query<HuK_UserInfo>(sql).ToList();
            }
        }
        /// <summary>
        /// 账户信息列表
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        public List<ZhuanHu_UserInfo> YSelect(int UserId)
        {
            using (SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=Iot.Loan_DB;Integrated Security=True"))
            {
                string sql = $"select * from ZhuanHu_UserInfo where User_Id={UserId}";
                return conn.Query<ZhuanHu_UserInfo>(sql).ToList();
            }
        }
    }
View Code
原文地址:https://www.cnblogs.com/wj1107/p/13083132.html