/// <summary>
 /// 关注
 /// </summary>
 /// <param name="wechatMessageModel"></param>
 /// <returns></returns>
 private void Subscribe(WeChatMsgViewModel wechatMessageModel)
 {
     try
     {
         LogUtil.Debug("新关注用户OpenId:" + wechatMessageModel.FromUserName);
         var dbNow  = TimeUtil.Now;
         var entity = wxUserServ.GetEntity(wechatMessageModel.FromUserName, EnumWeChatType.Client.GetHashCode());
         if (entity == null)
         {
             //新关注用户
             entity             = new WxUserEntity();
             entity.ShopId      = 0;
             entity.OpenId      = wechatMessageModel.FromUserName;
             entity.WxType      = EnumWeChatType.Client.GetHashCode();
             entity.EnabledFlag = EnabledFlagType.Valid.GetHashCode();
             entity.CreateDate  = dbNow;
             wxUserServ.InsertEntity(entity);
             LogUtil.Debug(string.Format("openId:{0},关注记录写入成功!", wechatMessageModel.FromUserName));
         }
         else
         {
             //已取消关注用户重新关注
             if (entity.EnabledFlag != EnabledFlagType.Valid.GetHashCode())
             {
                 entity.EnabledFlag = EnabledFlagType.Valid.GetHashCode();
                 wxUserServ.UpdateEntity(entity);
                 LogUtil.Debug(string.Format("openId:{0},关注记录更新成功!", wechatMessageModel.FromUserName));
             }
         }
     }
     catch (Exception ex)
     {
         LogUtil.Error(string.Format("openId:{0},关注记录写入失败,参考信息:{1}", wechatMessageModel.FromUserName, ex.Message));
     }
 }
Ejemplo n.º 2
0
        /// <summary>
        /// 保存用户
        /// </summary>
        /// <param name="inObj"></param>
        /// <returns></returns>
        public async Task <ResultObj <int> > saveUser(WxUserEntity inObj, List <string> saveFieldList)
        {
            ResultObj <int> resultObj = new ResultObj <int>();
            var             saveEnt   = new DtoSave <WxUserEntity>()
            {
                data = inObj
            };
            string openid = inObj.openid;

            if (await dbHelper_user.Count(x => x.openid == openid) > 0)
            {
                saveEnt.ignoreFieldList = new List <string> {
                    "openid"
                };
                saveEnt.whereList = new List <string> {
                    "openid"
                };
                saveEnt.data.lastTime = DataTimeHelper.getDateLong(DateTime.Now);
                saveEnt.saveFieldList = saveFieldList;
                resultObj.data        = await dbHelper_user.Update(saveEnt);
            }
            else
            {
                saveEnt.data.createTime = DataTimeHelper.getDateLong(DateTime.Now);
                saveEnt.data.lastTime   = saveEnt.data.createTime;
                resultObj.data          = await dbHelper_user.Save(saveEnt);
            }

            resultObj.success = resultObj.data > 0;
            return(resultObj);
        }
Ejemplo n.º 3
0
        public async Task GoodsCheck(string code, string state, string prcode)
        {
            if (string.IsNullOrEmpty(code))
            {
                string ip = this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
                if (!string.IsNullOrEmpty(prcode))
                {
                    state = $"{state}_{prcode}";
                }
                state = $"{state}|{ip}";
                var url = Helper.WeiChat.Utility.GetWebpageAuthorization(appConfig.WeiXin.Appid, $"http://{Request.Host.Host}{Request.Path}", Fun.Base64Encode(state), false);
                Response.Redirect(url);
            }
            else
            {
                var stateList = Fun.Base64Decode(state).Split('|');
                state = stateList[0];
                var goodsGuid = state.Split("_")[0];
                var goodsCode = state.Split("_")[1];

                WxUserEntity wxUser = new WxUserEntity();
                try
                {
                    //出错后,返回重新查看
                    wxUser = Helper.WeiChat.Utility.GetWebpageUserInfo(appConfig.WeiXin.Appid, appConfig.WeiXin.Secret, code);
                }
                catch
                {
                    await ShowHtml($"微信用户有误。<a href=\"GoodsDetail?state={goodsGuid}\">点击返回</a>");

                    return;
                }

                wxUser.ip = stateList[1];
                PsGoodsLogEntity inLog = new PsGoodsLogEntity()
                {
                    goodsGuid = goodsGuid,
                    ip        = wxUser.ip,
                    openid    = wxUser.openid
                };

                var reObj = await _respoitory.GoodsCheck(inLog, goodsCode);

                if (reObj.success)
                {
                    Response.Redirect($"GoodsDetail?state={goodsGuid}");
                }
                else
                {
                    await ShowHtml($"产品防伪码有误。<a href=\"GoodsDetail?state={goodsGuid}\">点击返回</a>");
                }
            }
        }
Ejemplo n.º 4
0
        //通过code换取网页授权access_token
        public OpenId GetOpenId(string code)
        {
            try
            {
                var client = new RestClient("https://api.weixin.qq.com/sns/oauth2");

                var request = new RestRequest("access_token?appid={appid}&secret={appsecret}&code={code}&grant_type=authorization_code", Method.GET);
                request.AddUrlSegment("appid", _setting.WeiXinAppId);
                request.AddUrlSegment("appsecret", _setting.WeiXinAppSecret);
                request.AddUrlSegment("code", code);
                var response = client.Execute(request);
                var data     = JsonConvert.DeserializeObject <OpenId>(response.Content);

                LogHelp.WriteLog("GetOpenId:::" + data);

                if (data != null)
                {
                    var userInfo = GetUserInfo(data.openid, data.access_token);

                    if (userInfo != null)
                    {
                        WxUserEntity Entry = new WxUserEntity();
                        Entry.Openid       = userInfo.openid;
                        Entry.Nickname     = userInfo.nickname;
                        Entry.Sex          = userInfo.sex;
                        Entry.City         = userInfo.city;
                        Entry.Country      = userInfo.country;
                        Entry.Province     = userInfo.province;
                        Entry.UserLanguage = userInfo.language;
                        Entry.Headimgurl   = userInfo.headimgurl;
                        new WxUserBC().SaveWxUser(Entry, userInfo.openid);
                    }
                }
                return(data ?? new OpenId());
            }
            catch (Exception ex)
            {
                LogHelp.WriteLog(ex.Message);
                return(new OpenId());
            }
        }
Ejemplo n.º 5
0
        public int SaveWxUser(WxUserEntity wxUser, string loginName)
        {
            var hasInfo = GetWxUserByOpenid(wxUser.Openid);

            if (hasInfo == null)
            {
                using (IDbConnection conn = DBContext.GetConnection(DataBaseName.AccountTrianDB, ReadOrWriteDB.Write))
                {
                    string query = string.Format(@"INSERT INTO Train_WxUser
                                                   (WxUserId
                                                   ,Subscribe
                                                   ,Openid
                                                   ,Nickname
                                                   ,Sex
                                                   ,City
                                                   ,Country
                                                   ,Province
                                                   ,UserLanguage
                                                   ,Headimgurl
                                                   ,Status
                                                   ,Phone
                                                   ,CreateTime
                                                   ,CreateUser
                                                   ,UpdateTime
                                                   ,UpdateUser
                                                   ,Name)
                                             VALUES
                                                   ('{0}'
                                                   ,'{1}'
                                                   ,'{2}'
                                                   ,'{3}'
                                                   ,'{4}'
                                                   ,'{5}'
                                                   ,'{6}'
                                                   ,'{7}'
                                                   ,'{8}'
                                                   ,'{9}'   
                                                   ,'{10}'
                                                   ,'{11}'
                                                   ,GETDATE()
                                                   ,'{12}'
                                                   ,GETDATE()
                                                   ,'{13}'
                                                   ,'{14}')",
                                                 Guid.NewGuid().ToString(), wxUser.Subscribe, wxUser.Openid, wxUser.Nickname, wxUser.Sex, wxUser.City, wxUser.Country,
                                                 wxUser.Province, wxUser.UserLanguage, wxUser.Headimgurl, 1, wxUser.Phone, loginName, loginName, wxUser.Name);

                    return(conn.Execute(query));
                }
            }
            else
            {
                using (IDbConnection conn = DBContext.GetConnection(DataBaseName.AccountTrianDB, ReadOrWriteDB.Write))
                {
                    string query = string.Format(@"UPDATE Train_WxUser
                                                   SET Subscribe = '{0}'
                                                      ,Nickname = '{1}'
                                                      ,Sex = '{2}'
                                                      ,City ='{3}'
                                                      ,Country = '{4}'
                                                      ,Province = '{5}'
                                                      ,UserLanguage = '{6}'
                                                      ,Headimgurl = '{7}'
                                                      ,Phone = '{8}'
                                                      ,Name = '{9}'
                                                      ,UpdateTime =getdate()
                                                      ,UpdateUser = '******'
                                                 WHERE WxUserId='{11}'",
                                                 wxUser.Subscribe, wxUser.Nickname, wxUser.Sex, wxUser.City, wxUser.Country,
                                                 wxUser.Province, wxUser.UserLanguage, wxUser.Headimgurl, wxUser.Phone, wxUser.Name, loginName, wxUser.WxUserId);

                    return(conn.Execute(query));
                }
            }
        }
        /// <summary>
        /// 更新微信用户信息
        /// </summary>
        /// <param name="shopId">门店ID</param>
        /// <param name="openId">微信用户openId</param>
        /// <param name="wxType">微信类型</param>
        /// <returns></returns>
        public int UpdateWxUserInfo(long shopId, string openId, int wxType)
        {
            int cnt   = 0;
            var dbNow = TimeUtil.Now;

            try
            {
                var wxUser = wxUserServ.GetEntity(shopId, wxType);
                if (wxUser != null)
                {
                    if (wxUser.OpenId != openId)
                    {
                        LogUtil.Info("更新OpenId");

                        //先删除新OpenId原来有关联的记录
                        wxUserServ.DeleteEntity(openId, wxType);

                        //关联门店和新OpenId
                        wxUser.OpenId      = openId ?? string.Empty;
                        wxUser.ModifyDate  = dbNow;
                        wxUser.EnabledFlag = (int)EnabledFlagType.Valid;
                        cnt = wxUserServ.UpdateEntity(wxUser);
                    }
                }
                else
                {
                    wxUser = wxUserServ.GetEntity(openId, wxType);
                    if (wxUser != null)
                    {
                        if (wxUser.ShopId != shopId)
                        {
                            LogUtil.Info("更新门店Id");

                            //先删除原来新门店Id原来有关联的记录
                            wxUserServ.DeleteEntity(shopId, wxType);

                            //更新OpenId对应的新门店Id
                            wxUser.ShopId      = shopId;
                            wxUser.ModifyDate  = dbNow;
                            wxUser.EnabledFlag = (int)EnabledFlagType.Valid;
                            cnt = wxUserServ.UpdateEntity(wxUser);
                        }
                    }
                    else
                    {
                        LogUtil.Info("新增");

                        wxUser             = new WxUserEntity();
                        wxUser.WxType      = wxType;
                        wxUser.OpenId      = openId ?? string.Empty;
                        wxUser.ShopId      = shopId;
                        wxUser.CreateDate  = dbNow;
                        wxUser.EnabledFlag = (int)EnabledFlagType.Valid;
                        cnt = wxUserServ.InsertEntity(wxUser);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.Error(ex.InnerException.ToString());
            }
            return(cnt);
        }
Ejemplo n.º 7
0
        public async Task GoodsDetail(string code, string state)
        {
            if (string.IsNullOrEmpty(code))
            {
                string ip = this.httpContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();
                state = $"{state}|{ip}";
                string rebackUrl = $"http://{Request.Host.Host}{Request.Path}";
                rebackUrl = HttpUtility.UrlEncode(rebackUrl);
                var url = Helper.WeiChat.Utility.GetWebpageAuthorization(appConfig.WeiXin.Appid, rebackUrl, Fun.Base64Encode(state), true);
                Response.Redirect(url);
            }
            else
            {
                var stateList = Fun.Base64Decode(state).Split('|');
                state = stateList[0];
                WxUserEntity wxUser = new WxUserEntity();
                try
                {
                    //出错后,返回重新查看
                    wxUser = Helper.WeiChat.Utility.GetWebpageUserInfo(appConfig.WeiXin.Appid, appConfig.WeiXin.Secret, code);
                }
                catch
                {
                    Response.Redirect($"GoodsDetail?state={state}");
                    return;
                }
                wxUser.ip = stateList[1];
                var addressList = await httpClientFactory.CreateClient().GetAddressAsync(wxUser.ip);

                wxUser.address = string.Join("", addressList);
                var opNum = await weiXin.saveUser(wxUser, new List <string> {
                    "nickname", "headimgurl", "lastTime", "ip", "address", "subscribe"
                });

                PsGoodsLogEntity inLog = new PsGoodsLogEntity()
                {
                    goodsGuid = state,
                    ip        = wxUser.ip,
                    openid    = wxUser.openid
                };
                var reObj = await _respoitory.GoodsDetail(inLog);

                if (reObj.success)
                {
                    StringBuilder htmlStringBuilder = new StringBuilder();
                    htmlStringBuilder.Append($"<a>");
                    string proNumStr = $"00000000{reObj.data.proNum}";
                    proNumStr = proNumStr.Substring(proNumStr.Length - 8);
                    htmlStringBuilder.Append($"产品编号:{reObj.data.batchCode}{proNumStr}<br />");
                    htmlStringBuilder.Append($"查阅次数:{reObj.data.lookNum}次<br />");
                    if (reObj.data.confirmTime == 0)
                    {
                        #region css样式
                        string headStr = @"
    <style>
        body {
            font-size: 14px;
        }
        input{
            border: 1px solid #333333;
        }
        button {
            font-size: 14px;
            border: 1px solid #333333;
        }
        .black_overlay {
            display: none;
            position: absolute;
            top: 0%;
            left: 0%;
            width: 100%;
            height: 100%;
            background-color: black;
            -moz-opacity: 0.5;
            opacity: .50;
            filter: alpha(opacity=50);
        }

        .white_content {
            display: none;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -80%);
            width: 50%;
            height: 100px;
            padding: 20px;
            background-color: white;
            overflow: auto;
            text-align: center;
        }

        .white_content div {
            margin-bottom: 5px;
        }
    </style>
";
                        #endregion

                        #region js脚本
                        string bootStr = @"
<script type='text/javascript'>
    function openDialog() {
        document.getElementById('light').style.display = 'block';
        document.getElementById('fade').style.display = 'block'
    }
    function closeDialog() {
        document.getElementById('light').style.display = 'none';
        document.getElementById('fade').style.display = 'none'
    }
</script>
";
                        #endregion

                        htmlStringBuilder.Append($"<a onclick=\"openDialog()\" href=\"#\">点击验证</a>");
                        htmlStringBuilder.Append($"</a>");

                        #region 验证框
                        htmlStringBuilder.Append($@"
    <div id='fade' class='black_overlay'></div>
    <div id='light' class='white_content'>
        <form action='GoodsCheck' method='GET'>
            <div>
                <a>请输入产品防伪码</a>
            </div>
            <div>
                <input name='prcode' />
            </div>
            <div>
                <input name='state' type='hidden' value='{state}'/>
                <button  onclick='submit()'>确定</button>
                <button type='reset' onclick='closeDialog()' style='margin-left: 10px;'>取消</button>
            </div>
        </form>
    </div>                    
                    ");
                        #endregion

                        await ShowHtml(htmlStringBuilder.ToString(), headStr, bootStr);
                    }
                    else
                    {
                        htmlStringBuilder.Append($"验证时间:{Helper.DataTimeHelper.getDate(reObj.data.confirmTime).ToString()}\r\n<br />");
                        htmlStringBuilder.Append($"防 伪 码:{reObj.data.code}");
                        htmlStringBuilder.Append($"</a>");
                        await ShowHtml(htmlStringBuilder.ToString());
                    }
                }
                else
                {
                    await ShowHtml(reObj.msg);
                }
            }
        }
Ejemplo n.º 8
0
        public int SaveWxUser(WxUserEntity wxUser, string loginName)
        {
            WxUserDA da = new WxUserDA();

            return(da.SaveWxUser(wxUser, loginName));
        }
Ejemplo n.º 9
0
        public async Task <string> index()
        {
            PostModel postModel = TypeChange.UrlToEntities <PostModel>(Request.QueryString.Value);

            if (!CheckSignature.Check(postModel.Signature, postModel.Timestamp, postModel.Nonce, appConfig.WeiXin.Token))
            {
                return("参数错误!");
            }
            else
            {
                Request.EnableBuffering();

                using (var reader = new StreamReader(Request.Body, encoding: Encoding.UTF8))
                {
                    var body = await reader.ReadToEndAsync();

                    var    xml          = TypeChange.XmlToDict(body);
                    String toUserName   = xml.GetValueOrDefault("ToUserName");
                    String fromUserName = xml.GetValueOrDefault("FromUserName");
                    String msgType      = xml.GetValueOrDefault("MsgType");
                    String content      = xml.GetValueOrDefault("Content");
                    String eventType    = xml.GetValueOrDefault("Event");
                    String eventKey     = xml.GetValueOrDefault("EventKey");
                    String ticket       = xml.GetValueOrDefault("Ticket");
                    await weiXin.saveLog(new WxQuestLogEntity
                    {
                        id           = await SequenceRepository.GetNextID <WxQuestLogEntity>(),
                        toUserName   = toUserName,
                        fromUserName = fromUserName,
                        msgType      = msgType,
                        content      = content,
                        eventType    = eventType,
                        eventKey     = eventKey,
                        ticket       = ticket,
                    });

                    if (MessageUtil.MESSAGE_EVENT.Equals(msgType))
                    {
                        switch (eventType.ToLower())
                        {
                        case "subscribe":     //订阅
                            if (!string.IsNullOrEmpty(fromUserName))
                            {
                                var userinfo = Helper.WeiChat.Utility.GetUserInfo(fromUserName);
                                await weiXin.saveUser(userinfo, new List <string> {
                                    "nickname", "headimgurl", "subscribe", "subscribe_time", "remark", "groupid", "tagidListStr", "subscribe_scene", "qr_scene", "qr_scene_str"
                                });
                            }
                            break;

                        case "unsubscribe":     //取消订阅
                            var unsubscribeUser = new WxUserEntity()
                            {
                                subscribe      = 0,
                                openid         = fromUserName,
                                subscribe_time = Helper.DataTimeHelper.getDateLongTimestamp(DateTime.Now)
                            };
                            await weiXin.saveUser(unsubscribeUser, new List <string> {
                                "subscribe", "subscribe_time"
                            });

                            break;

                        case "click":     //点击事件
                            String replay = "";
                            switch (eventKey)
                            {
                            case MessageUtil.CLICK_DOWNURL:
                                replay = MessageUtil.downloadApp();
                                break;

                            case MessageUtil.CLICK_ETC_INSTALL:
                                replay = MessageUtil.etcInstallPlace();
                                break;

                            case MessageUtil.CLICK_GetMoney:
                                replay = MessageUtil.etcGetMoney(fromUserName);
                                break;
                            }
                            string message = MessageUtil.initText(toUserName, fromUserName, replay);
                            return(message);

                        case "view":     //url类型
                            break;
                        }
                    }

                    // Do some processing with body…
                    // Reset the request body stream position so the next middleware can read it
                    Request.Body.Position = 0;
                    return("");
                }
            }
        }
Ejemplo n.º 10
0
        public ActionResult Register(RegisterModel model)
        {
            string ErrMsg;

            try
            {
                //数据校验
                if (string.IsNullOrEmpty(model.openid))
                {
                    ErrMsg = "OpenId不能为空";
                    return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                }

                if (string.IsNullOrEmpty(model.phone))
                {
                    ErrMsg = "手机号不能为空";
                    return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                }

                if (string.IsNullOrEmpty(model.code))
                {
                    ErrMsg = "验证码不能为空";
                    return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    //SMSCodes smsCode = Session["RegisterCode"] as SMSCodes;
                    if (Session["RegisterCode"] == null)
                    {
                        ErrMsg = "未获取验证码";
                        return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        //if (!smsCode.IsExpired && smsCode.IsUsered == false)
                        //{

                        if (model.code != "1234")
                        {
                            ErrMsg = "验证码不正确";
                            return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                        }
                        else
                        {
                            //string access_token = "";

                            //access_token = Util.GetAccessTokenOpen();
                            //LogHelp.WriteLog(DateTime.Now + "GetAccessTokenOpen:" +model.openid+ access_token);
                            //var userInfo = GetUserInfo(model.openid, access_token);

                            var userInfo = new WxUserBC().GetWxUserByOpenid(model.openid);
                            LogHelp.WriteLog(DateTime.Now + "GetWxUserByOpenid:" + model.openid);
                            //实体赋值
                            WxUserEntity Entry = new WxUserEntity();

                            //List<WxUserEntity> list = null;
                            //校验次手机号是否已注册
                            var list = new WxUserBC().GetWxUserListByCondition(null, model.phone, null, null).ToList();
                            if (list.Count > 0)
                            {
                                ErrMsg = "手机号已被注册";
                                return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                            }
                            else
                            {
                                Entry.WxUserId     = userInfo.WxUserId;
                                Entry.Openid       = userInfo.Openid;
                                Entry.Nickname     = userInfo.Nickname;
                                Entry.Sex          = userInfo.Sex;
                                Entry.City         = userInfo.City;
                                Entry.Country      = userInfo.Country;
                                Entry.Province     = userInfo.Province;
                                Entry.UserLanguage = userInfo.UserLanguage;
                                Entry.Headimgurl   = userInfo.Headimgurl;
                                Entry.Phone        = model.phone;
                                int d = new WxUserBC().SaveWxUser(Entry, userInfo.Openid);

                                if (d == 0)
                                {
                                    ErrMsg = "插入数据库失败";
                                    return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                                }
                                else
                                {
                                    //Session["DELIVERYMANCODE"] = new SMSCodes { Code = smsCode.Code, CreteTime = smsCode.CreteTime, IsUsered = true };
                                    ErrMsg = "Success";
                                    return(Json(ErrMsg, JsonRequestBehavior.AllowGet));
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ErrMsg = ex.Message.ToString();
                return(Json("Error"));
            }
        }