Ejemplo n.º 1
0
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public JsonResult ResetPsw(SysUser user)
        {
            string    psw   = ConfigManage.AppSettings <string>("AppSettings:DefaultPassWord");
            StateCode state = ServiceIoc.Get <SysUserService>().ResetPsw(bid, psw);

            return(Json(GetResult(StateCode.State_200)));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 签名验证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            try
            {
                base.OnActionExecuting(actionContext);
                //加密字符串参数
                string ticket = actionContext.HttpContext.Request.Query["ticket"];
                //业务类型
                string bizType = actionContext.HttpContext.Request.Query["bizType"];
                //业务ID
                string bizId = actionContext.HttpContext.Request.Query["bizId"];

                if (!string.IsNullOrEmpty(ticket) && !string.IsNullOrEmpty(bizType) && !string.IsNullOrEmpty(bizId))
                {
                    string val = bizType + "#" + bizId + ConfigManage.AppSettings <string>("AppSettings:EncryptKey");
                    if (!ticket.ToUpper().Equals(StringHelper.ConvertTo32BitSHA1(val).ToUpper()))
                    {
                        //actionContext.Response = APIResponse.toJson(StateCode.State_9000);
                        return;
                    }
                }
                else
                {
                    //actionContext.Response = APIResponse.toJson(StateCode.State_9001);
                    return;
                }
            }
            catch (Exception ex)
            {
                ServiceIoc.Get <APILogsService>().Save("AppCheckUp==>" + ex.ToString());
            }

            return;
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 初始化数据
        /// </summary>
        public void Initial()
        {
            //读取
            enableRedis = ConfigManage.AppSettings <bool>("RedisConfig:EnableRedis");
            if (enableRedis)
            {
                cacheRedis = CacheSessionFactory.Instance.CreateCache();
            }

            //版本号
            VNo = ConfigManage.AppSettings <string>("AppSettings:VNo");
            //系统名称
            SysName = ConfigManage.AppSettings <string>("AppSettings:SysName");
            //资源域名
            Res = ConfigManage.AppSettings <string>("AppSettings:DomainRes");
            //后台域名
            Admin = ConfigManage.AppSettings <string>("AppSettings:DomainAdmin");

            //获取所有菜单
            List <SysModelMenu> db_menus = ServiceIoc.Get <SysModelMenuService>().Where(m => m.is_enable == true).OrderByDescending(a => a.order_index).ToList();
            //获取所有权限
            List <SysPermission> db_permissions = ServiceIoc.Get <SysPermissionService>().GetAll().OrderByDescending(a => a.order_index).ToList();
            //角色集合
            List <SysRole> db_reles = ServiceIoc.Get <SysRoleService>().Where(r => r.is_enable == true).ToList();
            //用户角色权限
            List <UserRole> db_user_reles = ServiceIoc.Get <UserRoleService>().GetAll();
            //所有用户权限
            //List<SysUserPermission> db_user_permissions = ServiceIoc.Get<SysUserPermissionService>().GetAll();
            //用户角色权限
            List <SysRolePermission> db_role_permissions = ServiceIoc.Get <SysRolePermissionService>().GetAll();

            //是否开启Redis缓存
            if (EnableRedis)
            {
                //系统菜单
                cacheRedis.Write(sys_menu_key, db_menus, CacheId.module);
                //系统权限
                cacheRedis.Write(sys_func_key, db_permissions, CacheId.module);
                //系统角色
                cacheRedis.Write(sys_role_key, db_reles, CacheId.module);
                //系统角色权限
                cacheRedis.Write(sys_role_func_key, db_role_permissions, CacheId.module);
            }
            else
            {
                //系统菜单
                menus = db_menus;
                //系统权限
                permissions = db_permissions;
                //系统角色
                roles = db_reles;
                //系统角色权限
                rolePermissions = db_role_permissions;
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 执行Action之前
        /// </summary>
        /// <param name="context"></param>
        public async override void OnActionExecuting(ActionExecutingContext context)
        {
            //获取基类控制器
            var baseController = ((BaseController)context.Controller);

            //获取请求参数
            byte[] buffer = new byte[1024];
            var    len    = await context.HttpContext.Request.Body.ReadAsync(buffer, 0, buffer.Length);

            List <byte> list = new List <byte>();

            while (len > 0)
            {
                list.AddRange(buffer.Take(len));
                //读取完成跳出循环
                len = await context.HttpContext.Request.Body.ReadAsync(buffer, 0, buffer.Length);
            }
            //基类控制器
            baseController.DynamicStr = Encoding.UTF8.GetString(list.ToArray());
            //动态运行时对象
            baseController.Dynamic = JsonConvert.DeserializeObject <dynamic>(baseController.DynamicStr);

            //post提交方式
            if ("post".Equals(context.HttpContext.Request.Method.ToLower()))
            {
                if (context.HttpContext.User.Identity.IsAuthenticated)
                {
                    string token = context.HttpContext.Request.Headers["Authorization"];
                    if (token.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase))
                    {
                        token = token.Substring("Bearer ".Length).Trim();
                    }
                }

                //数据包
                baseController.Sign = JsonConvert.DeserializeObject <SignPackage>(baseController.Dynamic.Global.ToString());

                //签名校验
                if (!WeiFosSign.SignAuth(sign_secret, baseController.DynamicStr))
                {
                    if (!ConfigManage.AppSettings <bool>("AppSettings:IsDebugModel"))
                    {
                        context.Result = APIResponse.GetResult(StateCode.State_5);
                    }
                    else
                    {
                        context.Result = APIResponse.GetResult(StateCode.State_5);
                    }
                    return;
                }
            }
        }
Ejemplo n.º 5
0
        public async Task <IActionResult> UploadFile(List <IFormFile> files)
        {
            if (ConfigManage.AppSettings <bool>("WeChatSettings:IsOpenOss"))
            {
                //弱类型在这里不能初始化值,所以必须重新定义
                var result = Uploader.UploadFile(HttpContext);
                return(Ok(result));
            }
            else
            {
                var result = await Uploader.UploadFolderToAsync(HttpContext);

                return(Ok(result));
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 根据信息类型获取对应链接
        /// </summary>
        /// <param name="content_type"></param>
        /// <param name="content_value"></param>
        /// <returns></returns>
        public static string GetLinkByType(WeChatAccountTmp account, int sid, int content_type, string usercode, string content_value)
        {
            StringBuilder sb = new StringBuilder();

            switch (content_type)
            {
            //一键拨号
            case MsgContentType.OneTouchDial:
                return(sb.Append("tel:").Append(content_value).ToString());

            //外链
            case MsgContentType.OutLink:
                return(content_value);

            //图文
            case MsgContentType.ImgTextDetails:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Res"));
                sb.Append("Home/InfoDetails/").Append(content_value).Append(".html");
                return(sb.ToString());

            //导航
            case MsgContentType.Navigation:
                sb.Append("http://api.map.baidu.com/marker?location=");
                if (!string.IsNullOrEmpty(content_value) && content_value.IndexOf(",") != -1 && content_value.IndexOf("#") != -1)
                {
                    int    index    = content_value.IndexOf("#");
                    string location = content_value.Substring(0, index);
                    string address  = content_value.Substring(index + 1, content_value.Length - index - 1);
                    sb.Append(location);
                    sb.Append("&title=").Append(account.nick_name);
                    sb.Append("&content=").Append(address);
                    sb.Append("&output=html");
                }
                return(sb.ToString());

            //微活动
            case MsgContentType.WeiActivity:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("weiactivity.aspx?");
                sb.Append("aid=" + account.id + "&");
                sb.Append("bid=" + content_value.Split('#')[0].ToString() + "&");
                sb.Append("code=" + content_value.Split('#')[1].ToString() + "&");
                sb.Append("usercode=" + usercode);
                return(sb.ToString());

            //微相册
            case MsgContentType.WeiAlbum:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("Album/Album.aspx?");
                sb.Append("bid=" + content_value);
                return(sb.ToString());

            //微留言
            case MsgContentType.WeiMessage:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("weimessage.aspx?");
                sb.Append("code=" + content_value + "&");
                sb.Append("usercode=" + usercode);
                return(sb.ToString());

            //名片
            case MsgContentType.VisitingCard:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("Home/MyQRCode");
                return(sb.ToString());

            //完成注册
            case MsgContentType.Register:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("Home/Register");
                return(sb.ToString());

            //微商城
            case MsgContentType.WeiMall:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("index");
                return(sb.ToString());

            //微预约
            case MsgContentType.WeiResv:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));
                sb.Append("WeiReservation/ResvOrderSubmit.aspx?");
                sb.Append("aid=" + account.id + "&");
                sb.Append("bid=" + content_value);
                return(sb.ToString());

            //微信会员卡
            case MsgContentType.MemberCard:
                sb.Append(ConfigManage.AppSettings <string>("AppSettings:Mob"));

                //存在会员卡号
                if (content_value.IndexOf("#") != -1)
                {
                    sb.Append("MemberCard/Index.aspx?");
                    sb.Append("aid=" + account.id + "&");
                    sb.Append("bid=" + content_value.Split('#')[0] + "&");
                    sb.Append(usercode);
                }    //不存在会员卡号
                else
                {
                    sb.Append("MemberCard/ResvOrderSubmit.aspx?");
                    sb.Append("aid=" + account.id + "&");
                    sb.Append("bid=" + content_value);
                }

                return(sb.ToString());

            default:
                return("");
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 保存系统用户
        /// </summary>
        /// <param name="created_user_id"></param>
        /// <param name="entity"></param>
        /// <param name="employee"></param>
        /// <param name="rIds"></param>
        /// <param name="pIds"></param>
        /// <returns></returns>
        public StateCode SaveUser(long created_user_id, SysUser entity, Employee employee, string rIds, string pIds)
        {
            //角色ID
            long[] roleIds = StringHelper.StringToLongArray(rIds);
            //权限ID
            long[] permissionIds = StringHelper.StringToLongArray(pIds);

            using (ISession s = SessionFactory.Instance.CreateSession())
            {
                s.StartTransaction();
                try
                {
                    if (entity.id == 0)
                    {
                        //是否是管理员
                        entity.is_manager = false;
                        //登录次数
                        entity.login_count = 0;
                        //创建用户ID
                        entity.created_user_id = created_user_id;
                        //创建时间
                        entity.created_date = DateTime.Now;
                        //密码
                        entity.pass_word = StringHelper.ConvertTo32BitSHA1(ConfigManage.AppSettings <string>("AppSettings:DefaultPassWord"));
                        //插入用户数据
                        s.Insert(entity);

                        //对应系统用户
                        employee.sys_user_id = entity.id;
                        //插入用户对应员工数据
                        s.Insert(employee);
                    }
                    else
                    {
                        //修改用户实体
                        s.Update(entity);
                        int exist = s.Exist <Employee>("where sys_user_id = @0", entity.id);
                        if (exist == 0)
                        {
                            s.Insert(employee);
                        }
                        else
                        {
                            s.Update(employee);
                        }
                    }

                    //用户角色处理
                    s.ExcuteUpdate("delete tb_sys_user_role where sysuser_id = @0", entity.id);
                    if (roleIds != null && roleIds.Count() > 0)
                    {
                        for (int i = 0; i < roleIds.Length; i++)
                        {
                            UserRole ur = new UserRole();
                            ur.sysuser_id = entity.id;
                            ur.role_id    = roleIds[i];
                            s.Insert <UserRole>(ur);
                        }
                    }

                    //用户权限处理
                    s.ExcuteUpdate("delete tb_sys_user_permission where sysuser_id=@0", entity.id);
                    if (permissionIds != null && permissionIds.Count() > 0)
                    {
                        for (int i = 0; i < permissionIds.Length; i++)
                        {
                            SysUserPermission up = new SysUserPermission();
                            up.sysuser_id    = entity.id;
                            up.permission_id = permissionIds[i];
                            s.Insert(up);
                        }
                    }

                    s.Commit();
                    return(StateCode.State_200);
                }
                catch (Exception ex)
                {
                    s.RollBack();
                    return(StateCode.State_500);
                }
            }
        }
Ejemplo n.º 8
0
        public static dynamic UploadFile(HttpContext context)
        {
            //状态位
            StateCode state = StateCode.State_200;
            //错误消息
            string error = string.Empty;
            //原文件名
            string originName = string.Empty;
            //上传文件地址
            string fileurl = string.Empty;
            //文件名
            string newfilename = string.Empty;

            //OSS AccessId
            string accessId = ConfigManage.AppSettings <string>("AppSettings:AccessId");
            //OSS AccessKey
            string accessKey = ConfigManage.AppSettings <string>("AppSettings:AccessKey");
            //OSS endpoint
            string endpoint = ConfigManage.AppSettings <string>("AppSettings:endpoint");
            //OSS 图片Bucket
            string PicBucket = ConfigManage.AppSettings <string>("AppSettings:PicBucket");
            //OSS 图片域名
            string PicDomain = ConfigManage.AppSettings <string>("AppSettings:PicDomain");

            try
            {
                //业务类型
                string bizType = NHttpContext.Current.Request.Query["bizType"];

                //业务IDTicketID
                string bizId = NHttpContext.Current.Request.Query["bizId"];
                bizId = string.IsNullOrEmpty(bizId) ? "0" : StringHelper.GetDecryption(bizId);

                //上传file 名称
                //string filedName = Config.GetString("imageFieldName");

                ////获取file 数据
                //var file = HttpContext.Current.Request.Files[filedName];

                ////原文件名
                //originName = file.FileName;

                ////OSS 上传
                //string firstName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + new Random().Next(100000, 999999);
                //string lastName = Path.GetExtension(file.FileName);
                //string fullName = firstName + lastName;

                ////写入数据库信息
                //if (file.ContentLength < int.Parse(Config.GetString("imageMaxSize")))
                //{
                //    string[] imgmsg = OSSUpload.SaveImgOss(bizType, PicDomain, firstName, originName, file.ContentLength);
                //}

                //ObjectMetadata metadata = new ObjectMetadata();
                //metadata.ContentType = file.ContentType;

                //OssClient ossClient = new OssClient(endpoint, accessId, accessKey);

                //using (var fs = file.InputStream)
                //{
                //    var ret = ossClient.PutObject(PicBucket, fullName, fs, metadata);
                //}
                ////图片全路径
                //fileurl = PicDomain + fullName;
                ////原始图片名
                //originName = file.FileName;
                ////新图片名
                //newfilename = firstName;
            }
            catch (Exception e)
            {
                state = StateCode.State_500;
                error = e.Message;
            }

            var backdata = new
            {
                state    = (int)state,
                url      = fileurl,
                original = originName,
                data     = newfilename,
                error    = error
            };

            return(backdata);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 处理进程
        /// </summary>
        public async override void Process()
        {
            byte[] uploadFileBytes = null;  //文件内容
            string uploadFileName  = null;  //文件名

            if (UploadConfig.Base64)
            {
                uploadFileName  = UploadConfig.Base64Filename;
                uploadFileBytes = Convert.FromBase64String(Request.Form[UploadConfig.UploadFieldName]);
            }
            else
            {
            }

            try
            {
                //上传状态
                StateCode state = StateCode.State_500;
                //原文件名,url地址,data:上传后新生成的名
                string original = string.Empty, url = string.Empty, data = string.Empty;
                //是否使用OSS上传功能
                if (ConfigManage.AppSettings <bool>("WeChatSettings:IsOpenOss"))
                {
                    var result = OSSUpload.UploadFile(Context);
                    state    = result.state;
                    url      = result.url;
                    data     = result.data;
                    original = result.original;
                }
                else
                {
                    if (Uploader.CheckUploadFile(Context))
                    {
                        var result = await Uploader.UploadFile(Context);

                        state    = result.state;
                        url      = result.url;
                        data     = result.data;
                        original = result.original;
                    }
                    else
                    {
                        Result.ErrorMessage = "上传票据校验失败";
                    }
                }

                if (state == StateCode.State_200)
                {
                    Result.State = UploadState.Success;
                }

                //原始路径名
                Result.OriginFileName = original;
                Result.Url            = url;
                Result.Data           = data;
            }
            catch (Exception e)
            {
                Result.State        = UploadState.FileAccessError;
                Result.ErrorMessage = e.Message;
            }
            finally
            {
                WriteResult();
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 公众号设置
        /// </summary>
        /// <param name="user"></param>
        /// <param name="auth_code"></param>
        /// <param name="expires_in"></param>
        /// <returns></returns>
        public IActionResult AccountSetting(SysUser user, string auth_code = "", string expires_in = "")
        {
            //当前用户加密ID
            ViewBag.Ticket = StringHelper.GetEncryption(bid.ToString());
            //用户图片路径
            ViewBag.imgurl = string.Empty;

            ViewBag.OpenToken = "";
            ViewBag.AscKey    = "";

            //缺省图片路劲
            ViewBag.defimgurl         = ResXmlConfig.Instance.DefaultImgSrc(AppGlobal.Res, ImgType.WX_Account);
            ViewBag.wx_account_imgurl = ViewBag.defimgurl;
            WeChatAccount account = ServiceIoc.Get <WeChatAccountService>().Get();

            if (account != null)
            {
                Img img = ServiceIoc.Get <ImgService>().GetImg(ImgType.WX_Account, account.id);
                if (img != null)
                {
                    ViewBag.wx_account_imgurl = string.IsNullOrEmpty(img.getImgUrl()) ? ViewBag.defimgurl : img.getImgUrl();
                }
                ViewBag.account = JsonConvert.SerializeObject(account);
            }
            else
            {
                ViewBag.Token = StringHelper.CreateRandomCode(10);
            }

            WeChatMerchant merchant = ServiceIoc.Get <WeChatMerchantService>().Get();

            if (merchant != null)
            {
                ViewBag.merchant = JsonConvert.SerializeObject(merchant);
            }

            WXOpenAccount openAcount = ServiceIoc.Get <WXOpenAccountService>().Get();

            if (openAcount != null)
            {
                ViewBag.openAcount = JsonConvert.SerializeObject(openAcount);
            }

            WXOpenSetting openSetting = ServiceIoc.Get <WXOpenSettingService>().Get();

            if (openSetting != null)
            {
                ViewBag.opensetting = JsonConvert.SerializeObject(openSetting);
            }
            else
            {
                ViewBag.OpenToken = StringHelper.GetRandomCode(10);
                ViewBag.AscKey    = StringHelper.GetRandomCode(43);
            }

            ViewBag.AuthTitle = "待微信推送票据";
            ViewBag.url       = "javascript:;";

            //获取当前凭据
            WXOpenCmptVerifyTicket ticket = ServiceIoc.Get <WXOpenAuthService>().GetCmptVerifyTicket();

            if (ticket != null && ConfigManage.AppSettings <bool>("WeChatSettings:IsOpenAuthUrl"))
            {
                if (ticket.ComponentVerifyTicket != null)
                {
                    ViewBag.WXOpenTicket = ticket.ComponentVerifyTicket.Value;
                    string cmpt_access_token = ServiceIoc.Get <WXOpenAuthService>().GetCmptAccessToken(openSetting, ViewBag.WXOpenTicket);
                    string pre_auth_code     = ServiceIoc.Get <WXOpenAuthService>().GetOpenPreAuthCode(cmpt_access_token, openSetting.component_appid);
                    string redirect_uri      = AppGlobal.Admin + "WeChat/AccountSetting";

                    ViewBag.AuthTitle = "授权公众号";
                    //授权地址
                    ViewBag.url = WeChatOpenHelper.GetOpenOuthUrl(openSetting.component_appid, pre_auth_code, redirect_uri);
                }
            }

            //授权回调
            if (!string.IsNullOrEmpty(auth_code) && !string.IsNullOrEmpty(expires_in))
            {
                //组件Token
                string cmpt_access_token = ServiceIoc.Get <WXOpenAuthService>().GetCmptAccessToken(openSetting, ticket.ComponentVerifyTicket.Value);
                //使用授权码换取公众号的接口调用凭据和授权信息
                WXOpenAuthFun auth_fun = ServiceIoc.Get <WXOpenAuthService>().GetAuthInfo(cmpt_access_token, openSetting.component_appid, auth_code);
                //组件ID
                string cmpt_token = ServiceIoc.Get <WXOpenAuthService>().GetCmptAccessToken(openSetting, ticket.ComponentVerifyTicket.Value);
                //成功
                if (auth_fun != null && !string.IsNullOrEmpty(cmpt_token))
                {
                    ServiceIoc.Get <WXOpenAccountService>().AuthWeChatAccount(user.id, cmpt_token, openSetting.component_appid, auth_fun.authorization_info.authorizer_appid);
                }

                return(Redirect(AppGlobal.Admin + "WeChat/AccountSetting"));
            }

            return(View());
        }
Ejemplo n.º 11
0
        public JsonResult SubmitRefundOrder(string no, decimal refund_amount, IHostingEnvironment host)
        {
            try
            {
                //退款状态码
                StateCode state = StateCode.State_500;

                #region 订单基本状态判断

                //退款单
                OrderRefund orderRefund = ServiceIoc.Get <OrderRefundService>().Get(no);

                //订单
                ProductOrder order = ServiceIoc.Get <ProductOrderService>().GetById(orderRefund.order_id);

                //是否存在订单
                if (order == null)
                {
                    return(Json(GetResult(StateCode.State_551)));
                }

                //订单是否未支付
                if (!order.is_pay)
                {
                    return(Json(GetResult(StateCode.State_552)));
                }

                //退款金额是否大于实际支付金额
                if (refund_amount > order.actual_amount)
                {
                    return(Json(GetResult(StateCode.State_554)));
                }

                //订单状态和退款单状态是可以退款的情况
                if (order.refund_status != 1 || orderRefund.status != 1)
                {
                    return(Json(GetResult(StateCode.State_553)));
                }

                #endregion

                //返回信息
                string msg = string.Empty;

                bool PayStatus = ConfigManage.AppSettings <bool>("AppSettings:WXPayStatus");

                //支付宝支付
                if (PayMethod.AliPay == order.pay_method)
                {
                    //商户号ID
                    string app_id = ConfigManage.AppSettings <string>("AppSettings:ALIPAY_APP_ID");
                    //AliRefundPayBizContent bizContent = new AliRefundPayBizContent();
                    //bizContent.out_trade_no = orderRefund.order_serial_no;
                    //bizContent.refund_amount = PayStatus ? refund_amount : decimal.Parse("0.01");

                    ////string webRootPath = host.WebRootPath;
                    //string privateKeyPem = host.ContentRootPath + "Config\\alipay_cret\\rsa_private_key.pem";
                    //string publicKeyPem = host.ContentRootPath + "Config\\alipay_cret\\rsa_public_key.pem";

                    //IAopClient client = new DefaultAopClient("https://openapi.alipay.com/gateway.do", app_id, privateKeyPem, "json", "1.0", "RSA2", publicKeyPem, "utf-8", true);
                    //AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                    //request.BizContent = JsonConvert.SerializeObject(bizContent);

                    //AlipayTradeRefundResponse response = client.Execute(request);
                    //if (!response.IsError)
                    //{
                    //    state = ServiceIoc.Get<OrderRefundService>().AliPayConfirmRefund(orderRefund.order_serial_no, order.id);
                    //}
                    //else { }
                }//微信app支付
                else if (PayMethod.WeChat_App == order.pay_method)
                {
                    RefundPay refundParam = new RefundPay();

                    //证书路径
                    DirectoryInfo Dir      = Directory.GetParent(ConfigManage.AppSettings <string>("AppSettings:WeChat_App_CertPath"));
                    string        certPath = Dir.Parent.Parent.FullName;

                    //证书密钥
                    //string certPwd = Settings.AppSettings("CertPwd");
                    //商户信息
                    WeChatMerchant merchant = ServiceIoc.Get <WeChatMerchantService>().Get();

                    refundParam.appid = merchant.app_id;
                    //商户号
                    refundParam.mch_id = merchant.mch_id;
                    //随机数
                    refundParam.nonce_str = StringHelper.CreateNoncestr(16);
                    //商户侧传给微信的订单号
                    refundParam.out_trade_no = orderRefund.order_serial_no;
                    //商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔
                    refundParam.out_refund_no = orderRefund.refund_serial_no;
                    //订单总金额,单位为分
                    refundParam.total_fee = PayStatus ? (int)(refund_amount * 100) : 1;
                    //订单总金额,单位为分
                    refundParam.refund_fee = PayStatus ? (int)(refund_amount * 100) : 1;
                    //操作员帐号, 默认为商户号
                    refundParam.op_user_id = merchant.mch_id;

                    //退款
                    state = ServiceIoc.Get <OrderRefundService>().WeChatConfirmRefund(refundParam, order.id, certPath, merchant.mch_id, merchant.pay_key, out msg);
                }//微信公众号支付
                else if (PayMethod.WeChat_JsApi == order.pay_method || PayMethod.WeChat_Native == order.pay_method)
                {
                    RefundPay refundParam = new RefundPay();

                    //证书路径
                    DirectoryInfo Dir      = Directory.GetParent(ConfigManage.AppSettings <string>("AppSettings:WeChat_App_CertPath"));
                    string        certPath = Dir.Parent.Parent.FullName;

                    //证书密钥
                    //string certPwd = Settings.AppSettings("CertPwd");

                    //开放平台授权公众号信息
                    WeChatAccount weChatAccount = ServiceIoc.Get <WeChatAccountService>().Get();

                    refundParam.appid = weChatAccount.appid;
                    //商户号
                    refundParam.mch_id = weChatAccount.mch_id;
                    //随机数
                    refundParam.nonce_str = StringHelper.CreateNoncestr(16);
                    //商户侧传给微信的订单号
                    refundParam.out_trade_no = orderRefund.order_serial_no;
                    //商户系统内部的退款单号,商户系统内部唯一,同一退款单号多次请求只退一笔
                    refundParam.out_refund_no = orderRefund.refund_serial_no;
                    //订单总金额,单位为分
                    refundParam.total_fee = PayStatus ? (int)(refund_amount * 100) : 1;
                    //订单总金额,单位为分
                    refundParam.refund_fee = PayStatus ? (int)(refund_amount * 100) : 1;
                    //操作员帐号, 默认为商户号
                    refundParam.op_user_id = weChatAccount.mch_id;

                    //退款
                    state = ServiceIoc.Get <OrderRefundService>().WeChatConfirmRefund(refundParam, order.id, certPath, weChatAccount.mch_id, weChatAccount.pay_key, out msg);
                }

                return(Json(GetResult(state, msg)));
            }
            catch (Exception ex)
            {
                ServiceIoc.Get <APILogsService>().Save("提交退款SubmitRefundOrder==>" + ex.ToString());
                return(Json(GetResult(StateCode.State_500)));
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 发送短信验证码
        /// </summary>
        /// <param name="moblile"></param>
        /// <param name="type"></param>
        /// <param name="data">默认#拼接参数</param>
        /// <returns></returns>
        public StateCode GetSMSCode(string moblile, int type, string data = "")
        {
            string code    = StringHelper.CreateRandomCode(4);
            bool   is_test = ConfigManage.AppSettings <bool>("AppSettings:IsTestSendSms");

            if (is_test)
            {
                code = "8888";
            }

            StateCode state = SendSms(moblile, code, type);

            if (StateCode.State_200 == state && !is_test)
            {
                IClientProfile   profile = DefaultProfile.GetProfile("default", ConfigManage.AppSettings <string>("AppSettings:SMSKey"), ConfigManage.AppSettings <string>("AppSettings:SMSKeySecret"));
                DefaultAcsClient client  = new DefaultAcsClient(profile);
                CommonRequest    request = new CommonRequest();
                request.Method  = MethodType.POST;
                request.Domain  = "dysmsapi.aliyuncs.com";
                request.Version = "2017-05-25";
                request.Action  = "SendSms";
                request.AddQueryParameters("PhoneNumbers", moblile);
                request.AddQueryParameters("SignName", "微狐信息科技");
                // request.Protocol = ProtocolType.HTTP;

                if (type == (int)SendSmsType.Register)
                {
                    //注册
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpRegister"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }
                else if (type == (int)SendSmsType.ForgetPsw)
                {
                    //忘记密码
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpForgetPsw"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }
                else if (type == (int)SendSmsType.BindNewMobile)
                {
                    //绑定新手机号
                    request.AddQueryParameters("TemplateCode", ConfigManage.AppSettings <string>("AppSettings:SMSTmpBindNewMob"));
                    request.AddQueryParameters("TemplateParam", JsonConvert.SerializeObject(new { code, product = "微狐信息科技" }));
                }

                try
                {
                    CommonResponse response = client.GetCommonResponse(request);
                    Console.WriteLine(System.Text.Encoding.Default.GetString(response.HttpResponse.Content));
                }
                catch (ServerException e)
                {
                    state = StateCode.State_500;
                    Console.WriteLine(e);
                }
                catch (ClientException e)
                {
                    state = StateCode.State_500;
                    Console.WriteLine(e);
                }
            }

            return(state);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        private async Task <IActionResult> Func100()
        {
            return(await Task.Run(() =>
            {
                try
                {
                    //用户
                    string login_name = Dynamic.Data.LoginName.ToString();

                    //密码
                    string pass_word = Dynamic.Data.Password.ToString();

                    //是否登录
                    User user = ServiceIoc.Get <UserService>().Login(login_name, pass_word, HttpContext.GetClientIp(), Sign);
                    if (user.login_code == StateCode.State_200)
                    {
                        var claims = new[] {
                            new Claim(JwtRegisteredClaimNames.Sub, user.login_name),
                            new Claim("UserId", user.id.ToString()),
                            new Claim("HeadImg", user.head_img ?? "")
                        };

                        ClaimsIdentity identity = new ClaimsIdentity(new GenericIdentity(user.login_name, "TokenAuth"), claims);

                        var now = DateTime.UtcNow;
                        var ex = now + TimeSpan.FromMinutes(60);
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(ConfigManage.AppSettings <string>("Jwt:Key")));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);//加密方式
                        var token = new SecurityTokenDescriptor
                        {
                            //Jwt token 的签发者
                            Issuer = ConfigManage.AppSettings <string>("AppSettings:DomainApi"),
                            //Jwt token 的接收者
                            Audience = ConfigManage.AppSettings <string>("AppSettings:DomainApi"),
                            IssuedAt = now,
                            Expires = ex,
                            SigningCredentials = creds,
                            Subject = identity
                        };

                        //基于Jwt身份认证
                        //var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, JwtBearerDefaults.AuthenticationScheme));

                        //签发一个加密后的用户信息凭证,用来标识用户的身份
                        HttpContext.SignInAsync(JwtBearerDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

                        var tokenHandler = new JwtSecurityTokenHandler();

                        return APIResponse.GetResult(user.login_code, new
                        {
                            token = tokenHandler.CreateEncodedJwt(token),
                            sid = user.id,
                            name = user.login_name,
                            auth_time = new DateTimeOffset(now).ToUnixTimeSeconds(),
                            expires_at = new DateTimeOffset(ex).ToUnixTimeSeconds()
                        });
                    }

                    return APIResponse.GetResult(user.login_code);
                }
                catch (Exception ex)
                {
                    ServiceIoc.Get <APILogsService>().Save("登录接口==>" + ex.ToString());
                    return APIResponse.GetResult(StateCode.State_500);
                }
            }));
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="HttpContext"></param>
        /// <param name="moreSize"></param>
        /// <param name="biz_type"></param>
        /// <param name="biz_id"></param>
        /// <param name="is_async">是否是异步线程写入</param>
        /// <returns></returns>
        private static async Task <dynamic> UploadFolder(HttpContext HttpContext, int moreSize, string biz_type, long biz_id, bool is_async = false)
        {
            //错误消息
            string error = string.Empty, url = string.Empty, original = string.Empty, data = string.Empty;

            //状态
            StateCode state = StateCode.State_200;

            //结果集合
            List <dynamic> result = new List <dynamic>();

            //当前资源站点域名
            string domain = AppGlobal.Res;

            if (HttpContext.Request.Form.Files.Count() > 0)
            {
                foreach (var file in HttpContext.Request.Form.Files)
                {
                    //原文件名
                    original = file.FileName;

                    //访问路径 文件名
                    string[] filedata = { };
                    try
                    {
                        filedata = Uploader.GetUploadPath(biz_type, biz_id, original);
                        //资源根目录
                        string localPath = Directory.CreateDirectory("wwwroot/" + filedata[0] + "/").FullName;

                        //获取图片基本信息
                        BaseRes res = GetBaseRes(biz_type, localPath, filedata[0], filedata[1].Split('.')[0], original, file.Length, domain);
                        Img     img = (Img)res;
                        img.biz_type = biz_type;
                        if (ImgType.User.Equals(biz_type))
                        {
                            img.biz_id = biz_id;
                            SaveAutoComplete(img);
                        }
                        else
                        {
                            //保存图片
                            SaveImgMsg(img);
                        }

                        //文件字节
                        byte[] fileBytes = new byte[file.Length];

                        //文件扩展名
                        string f_name = img.extend_name.ToLower();
                        var    is_img = ((".gif".Equals(f_name) || ".jpg".Equals(f_name) || ".jpeg".Equals(f_name) || ".bmp".Equals(f_name) || ".png".Equals(f_name)));

                        //如果是图片类型
                        if (is_img)
                        {
                            if (file.Length < int.Parse(ConfigManage.AppSettings <string>("UploadSettings:imageMaxSize")))
                            {
                                //写入图片
                                if (await Uploader.WriteFile(file, localPath, filedata[1], is_async) && is_img)
                                {
                                    switch (moreSize)
                                    {
                                    //创建小图
                                    case 1:
                                        CreateThumbnailPicture(localPath + filedata[1], GetThmUrl(localPath), filedata[1]);
                                        break;

                                    //创建中图
                                    case 2:
                                        CreateThumbnailPicture(localPath + filedata[1], GetMedUrl(localPath), filedata[1], true);
                                        break;

                                    //创建小图和中图
                                    case 3:
                                        CreateThumbnailPicture(localPath + filedata[1], GetThmUrl(localPath), filedata[1]);
                                        CreateThumbnailPicture(localPath + filedata[1], GetMedUrl(localPath), filedata[1], true);
                                        break;

                                    default:
                                        break;
                                    }
                                }
                            }
                        }
                        else
                        {
                            await Uploader.WriteFile(file, localPath, filedata[1], is_async);
                        }

                        url  = domain + filedata[0] + filedata[1];
                        data = filedata[1].Split('.')[0];
                    }
                    catch (Exception e)
                    {
                        state = StateCode.State_500;
                        error = e.Message;
                    }

                    //图片列表
                    result.Add(new
                    {
                        key = data,
                        val = url,
                        original,
                        state
                    });
                }
            }


            return(new
            {
                state,
                url,
                original,
                data,
                result,
                error
            });
        }