public ActionResult GetUserInfo(string opendId = "ocvtlxMqS5KUWkQ77LIDGKGC7Vas") { var result = AccessTokenContainer .TryGetAccessToken("wx7a206d7f9cbf4f4f", "1139e29b74b0d7456b0914e9743971d0"); Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson userInfo = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(result, opendId); return(Json(userInfo, JsonRequestBehavior.AllowGet)); }
private bool UpdateUserSnsInfo(IdentityEntities db, string userId, Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson userInfo) { if (userInfo == null) { return(false); } var currInfos = db.UserSnsInfos.Where(x => x.UserId == userId).ToList(); //identify by unionid UpdateUserSnsInfo(db, userId, currInfos, System.Security.Claims.ClaimTypes.NameIdentifier, userInfo.unionid); //open id UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.OpenId, userInfo.openid); //union id UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.UnionId, userInfo.unionid); //nickname UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.NickName, userInfo.nickname); //city UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.City, userInfo.city); //province UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.Province, userInfo.province); //country UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.Country, userInfo.country); //headimage UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.HeadImageUrl, userInfo.headimgurl); //sex UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.Sex, userInfo.sex == 1 ? "M" : "F"); //group UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.GroupId, userInfo.groupid.ToString()); //subscribed UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.Subscribed, userInfo.subscribe == 0 ? "False" : "True"); if (userInfo.subscribe == 1) { UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.SubscribedTime, DateTime.Now.AddMilliseconds(-userInfo.subscribe_time).ToString()); } //loaded time UpdateUserSnsInfo(db, userId, currInfos, WeChatClaimTypes.LoadedTime, DateTime.Now.ToString()); return(true); }
public static string HeadImage(string wxfusn) { try { if (wxfusn != null && wxfusn != "") { Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson user = UserApi.Info(MPBasicSetting.AppID, wxfusn); return(user.headimgurl); } } catch (Exception e) { FileHelper.WriteLog("CommFunction_HeadImage", e.Message); } return("/Images/noImage.png"); }
public ActionResult Index() { ViewBag.isok = "OK"; ViewBag.Appid = sysConfigs.GetKeyValue("appid"); ViewBag.Uri = sysConfigs.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; userid = Request.QueryString["userid"]; ViewBag.userid = userid; ViewBag.openid = openid; //根据授权 获取openid //根据授权 获取用户的openid string code = Request.QueryString["code"];//获取授权code LogHelper.WriteLog("//////////////////////////////////////////////////////////////////////////////////"); LogHelper.WriteLog("code:" + code); if (!string.IsNullOrEmpty(code)) { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + sysConfigs.GetKeyValue("appid") + "&secret=" + sysConfigs.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; // LogHelper.WriteLog("openIdUrl:" + openIdUrl); string content = Tools.GetPage(openIdUrl, ""); LogHelper.WriteLog("content:" + content); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(token.IsExistAccess_Token(), openid); LogHelper.WriteLog("XXXXXXXXXXX:" + openid); if (dic != null) { ViewBag.nickname = dic.nickname; ViewBag.headimgurl = dic.headimgurl; } } else { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx5affe01247a2482c&redirect_uri=http://qxw2062640039.my3w.com/help/index/&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } return(View()); }
public ActionResult UserMain() { ViewBag.PageFlag = "UserMain"; ViewBag.isok = "OK"; ViewBag.Appid = WeChatConfig.GetKeyValue("appid"); ViewBag.Uri = WeChatConfig.GetKeyValue("shareurl"); noncestr = CommonMethod.GetCode(16); string jsapi_ticket = Js_sdk_Signature.IsExistjsapi_ticket(token.IsExistAccess_Token()); timestamp = DateTime.Now.Ticks.ToString().Substring(0, 10);; string url = Request.Url.ToString().Replace("#", ""); JssdkSignature = Js_sdk_Signature.GetjsSDK_Signature(noncestr, jsapi_ticket, timestamp, url); ViewBag.noncestr = noncestr; ViewBag.jsapi_ticket = jsapi_ticket; ViewBag.timestamp = timestamp; openid = CommonMethod.getCookie("openid"); userid = CommonMethod.getCookie("userid"); if (string.IsNullOrEmpty(openid)) { //根据授权 获取openid //根据授权 获取用户的openid string code = Request.QueryString["code"];//获取授权code LogHelper.WriteLog("//////////////////////////////////////////////////////////////////////////////////"); LogHelper.WriteLog("code:" + code); if (string.IsNullOrEmpty(code)) { string codeurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx242aa47391c159f6&redirect_uri=http://www.aoshacar.com/AoShaCar/userMain&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"; Response.Redirect(codeurl); } else { string openIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatConfig.GetKeyValue("appid") + "&secret=" + WeChatConfig.GetKeyValue("appsecret") + "&code=" + code + "&grant_type=authorization_code"; string content = Tools.GetPage(openIdUrl, ""); openid = Tools.GetJsonValue(content, "openid");//根据授权 获取当前人的openid } } var model = VIEW_YX_weiUser.ToViewModel(weiUserM.GetModelWithOutTrace(u => u.openid == openid)); if (model != null) { CommonMethod.delCookie("openid"); CommonMethod.delCookie("userid"); CommonMethod.setCookie("openid", openid, 1); CommonMethod.setCookie("userid", model.userNum, 1); ViewBag.nickname = model.nickname; ViewBag.headimgurl = model.headimgurl; } else { Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(token.IsExistAccess_Token(), openid); //LogHelper.WriteLog("XXXXXXXXXXX:" + openid); if (dic != null) { ViewBag.nickname = dic.nickname; ViewBag.headimgurl = dic.headimgurl; } model = new MODEL.ViewModel.VIEW_YX_weiUser(); model.subscribe = dic.subscribe; model.openid = dic.openid; model.nickname = dic.nickname; model.sex = dic.sex; model.U_language = dic.language; model.city = dic.city; model.province = dic.province; model.country = dic.country; model.headimgurl = dic.headimgurl; model.subscribe_time = DateTime.Now; model.userSex = dic.sex == 2 ? "女" : "男"; model.userNum = Common.Tools.Get8Digits(); model.F_id = 0; model.isfenxiao = 0; model.userMoney = 0; model.userYongJin = 0; weiUserM.Add(VIEW_YX_weiUser.ToEntity(model)); } ViewBag.UserType = ConfigSettings.GetSysConfigValue("USERTYPE", model.isfenxiao.ToString()); return(View(model)); }
public void CreateHaiBao(string fromUser, string toUser, string temppath) { OfficialAccount_BLL obll = new OfficialAccount_BLL(); //OfficialAccount model = obll.Get(a => a.OriginalID == toUser); OfficialAccount model = obll.Get(a => a.OriginalID == "gh_9229f06559cd"); if (!AccessTokenContainer.CheckRegistered(model.AppID)) //检查是否已经注册 { AccessTokenContainer.Register(model.AppID, model.AppSecret); //如果没有注册则进行注册 } try { Account_QRCode_Template aqt = new Account_QRCode_Template_BLL().GetList(a => a.AccountID == model.AccountID) .OrderByDescending(a => a.CreateTime) .FirstOrDefault(); QRCode_Template temp = new QRCode_Template_BLL().Get(a => a.TemplateID == aqt.TemplateID); DateTime now = DateTime.Now.AddMinutes(-2); WS.Utility.FileHelper.DeleteFilesBeforeTime(temppath, now); WebClient wc = new WebClient(); ICredentials cred; cred = new NetworkCredential("user-22", "user-22"); WebProxy wp = new WebProxy("http://172.18.226.109:808/", true, null, cred); wc.Proxy = wp; //下载原图 //string yuanfilename = Guid.NewGuid().ToString() + ".png"; string yuanlocalfilename = temppath + Guid.NewGuid().ToString() + ".jpg"; //wc.DownloadFile(ConfigurationManager.AppSettings["QiNiuDomain"] + model.QRCodeBgImg, yuanlocalfilename); wc.DownloadFile("http://qiniu.weixin.hairuiit.com/" + aqt.QRCodeBgImg, yuanlocalfilename); Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson uij = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(model.AppID, fromUser); //加入昵称 string savename1 = temppath + Guid.NewGuid().ToString() + ".jpg"; ImageHelper.Add_FontMark(yuanlocalfilename, savename1, uij.nickname, temp.NickName_FontFamily, (int)temp.NickName_FontSize, Color.Black, (int)temp.NickName_FontX, (int)temp.NickName_FontY); //下载头像 string touxiang = temppath + Guid.NewGuid().ToString() + ".png"; wc.DownloadFile(uij.headimgurl, touxiang); //下载二维码 // Senparc.Weixin.MP.AdvancedAPIs.QrCode.CreateQrCodeResult createQrCodeResult =QrCodeApi.CreateByStr(model.AppID, fromUser); Senparc.Weixin.MP.AdvancedAPIs.QrCode.CreateQrCodeResult createQrCodeResult = QrCodeApi.Create(model.AppID, 0, 0, Senparc.Weixin.MP.QrCode_ActionName.QR_LIMIT_STR_SCENE, fromUser); string localcodefile = temppath + Guid.NewGuid().ToString() + ".png"; wc.DownloadFile(QrCodeApi.GetShowQrCodeUrl(createQrCodeResult.ticket), localcodefile); wc.Dispose(); ///加头像 string savename2 = temppath + Guid.NewGuid().ToString() + ".jpg"; ImageHelper.Add_ImageMark(savename1, touxiang, savename2, (int)temp.HeadImg_X, (int)temp.HeadImg_Y, (int)temp.HeadImg_Width, (int)temp.HeadImg_Height); string savename3 = temppath + Guid.NewGuid().ToString() + ".jpg"; ImageHelper.Add_ImageMark(savename2, localcodefile, savename3, (int)temp.QRCode_X, (int)temp.QRCode_Y, (int)temp.QRCode_Width, (int)temp.QRCode_Height); Senparc.Weixin.MP.AdvancedAPIs.Media.UploadTemporaryMediaResult media = Senparc.Weixin.MP.AdvancedAPIs.MediaApi.UploadTemporaryMedia(model.AppID, Senparc.Weixin.MP.UploadMediaFileType.image, savename3); Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, fromUser, "专属海报已经接收成功,请保存到手机相册,分享海报兑换奖品哦!"); Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendImage(model.AppID, fromUser, media.media_id); Thread.Sleep(6000); WS.Utility.FileHelper.Delete(yuanlocalfilename); WS.Utility.FileHelper.Delete(savename1); WS.Utility.FileHelper.Delete(savename2); WS.Utility.FileHelper.Delete(savename3); WS.Utility.FileHelper.Delete(touxiang); WS.Utility.FileHelper.Delete(localcodefile); //var responseMessage = this.CreateResponseMessage<ResponseMessageText>(); //responseMessage.Content = "生成成功"; //return responseMessage; //return null; } catch (Exception ex) { //LogHelper.ErrorInfo(ex); //Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, requestMessage.FromUserName, // ex.Message.ToString()); Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, fromUser, ex.ToString()); } }
/// <summary> /// 事件消息回复 /// </summary> public void responseMsg() { string content = ""; //发送的内容 CreateMenu(); //创建菜单 XmlDocument EventOrNews_XML = GetMsgXML(); string EventName = (object)EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("Event") == null ? "" : EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("Event").InnerText; //事件类型 string EventKey = (object)EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("EventKey") == null ? "" : EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("EventKey").InnerText; //事件KEY值,与自定义菜单接口中KEY值对应 string MsgType = (object)EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("MsgType") == null ? "" : EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText; //消息类型 语音为voice 文本为 text string UserOpenId = EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText; LogHelper.WriteLog(UserOpenId); #region 关注 if (!string.IsNullOrEmpty(EventName) && EventName.Trim().ToLower() == "subscribe")//关注 - 事件类型 { //发送图文 string newsTitle2 = "欢迎加入傲鲨汽车生活馆"; string newsDescription2 = "“欢迎加入傲鲨汽车生活馆“ "; string newsPicUrl2 = "http://mmbiz.qpic.cn/mmbiz_jpg/x2FJcrdnw52ibeuGbIOJpiadG3ZjERJZDVewfKaklpxlnMOeM8gdcIKzvtWQXdiaDMibxfibkLWmvBJeicgRdhuwaPOw/640?wx_fmt=jpeg&tp=webp&wxfrom=5&wx_lazy=1"; string newsUrl2 = "http://mp.weixin.qq.com/s/LbQOK2MbaY3pM6eUQfW_sQ"; Senparc.Weixin.MP.Entities.Article arc2 = new Senparc.Weixin.MP.Entities.Article(); arc2.Title = newsTitle2; arc2.Description = newsDescription2; arc2.PicUrl = newsPicUrl2; arc2.Url = newsUrl2; List <Senparc.Weixin.MP.Entities.Article> list2 = new List <Senparc.Weixin.MP.Entities.Article>(); list2.Add(arc2); CustomApi.SendNews(WeChatConfig.IsExistAccess_Token2(), UserOpenId, list2); //发送图文结束 LogHelper.WriteLog("subscribe"); int isfenxiao = 0; // int FId = 0; if (EventKey.Contains("qrscene_"))//、用户通过带有场景值的二维码进行的关注事件 添加分享表 上下级关系 { isfenxiao = 1; string[] Uids = EventKey.Split('_');//获取情景值 LogHelper.WriteLog("进去了" + EventKey + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" + Uids.Length.ToString()); try { FId = Convert.ToInt32(Uids[1]); } catch { FId = 0; } } Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson dic = UserApi.Info(WeChatConfig.IsExistAccess_Token2(), UserOpenId); if (weiuserB.GetListasNoTrackingBy(w => w.openid == dic.openid).Count <= 0) { var wechatuser = new MODEL.YX_weiUser(); wechatuser.subscribe = dic.subscribe; wechatuser.openid = dic.openid; wechatuser.nickname = dic.nickname; wechatuser.sex = dic.sex; wechatuser.U_language = dic.language; wechatuser.city = dic.city; wechatuser.province = dic.province; wechatuser.country = dic.country; wechatuser.headimgurl = dic.headimgurl; wechatuser.subscribe_time = DateTime.Now; wechatuser.userSex = dic.sex == 2 ? "女" : "男"; wechatuser.userNum = Common.Tools.Get8Digits(); wechatuser.F_id = 0; wechatuser.isfenxiao = 0; wechatuser.userMoney = 0; wechatuser.userYongJin = 0; wechatuser.TREE_NODE_ID = "144e42158f676695"; weiuserB.Add(wechatuser); } } #endregion #region 其他 if (!string.IsNullOrEmpty(EventName) && EventName.Trim().ToLower() == "unsubscribe")//取消订阅。 { // UserBll.upState(UserOpenId, 1, 0);//修改当前状态 } if (!string.IsNullOrEmpty(MsgType) && MsgType.Trim().ToLower() == "voice") { } if (!string.IsNullOrEmpty(MsgType) && MsgType.Trim().ToLower() == "image") { string touser = UserOpenId; string fromuser = EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText; string CreateTime = EventOrNews_XML.SelectSingleNode("xml").SelectSingleNode("CreateTime ").InnerText; HttpContext.Current.Response.Write(GetKeFuXML(touser, fromuser, CreateTime)); } #region CliCK if (!string.IsNullOrEmpty(EventName) && EventName.Trim().ToLower() == "click")//菜单单击事件 { LogHelper.WriteLog("click"); List <WeChatMenus> ClickMenus = new List <WeChatMenus>(); object ClickMenusList = CacheHelper.GetCache("ClickMenusList");//设置单击菜单缓存 防止多次访问数据库 if (ClickMenusList != null) { ClickMenus = (List <WeChatMenus>)ClickMenusList; } else { ClickMenus = wechatMenus.GetClickMenus(); if (ClickMenus != null) { CacheHelper.SetCache("ClickMenusList", ClickMenus, TimeSpan.FromMinutes(60)); } } foreach (var item in ClickMenus) { if (!string.IsNullOrEmpty(EventName) && EventKey.Trim().ToUpper() == item.WX_MenusKey_URL.ToUpper()) { string flat1 = item.flat1.ToString(); //用于匹配那张消息表:例如,YX_text YX_news YX_image等 int Id = item.Id; // string tableName = ""; //表名 switch (flat1) { case "1": tableName = "YX_text"; break; case "2": tableName = "YX_news"; break; case "3": tableName = "YX_image"; break; case "4": tableName = "YX_voice"; break; case "5": tableName = "YX_video"; break; case "6": tableName = "YX_music"; break; } if (tableName == "YX_text")//发送文本消息 { LogHelper.WriteLog(Id.ToString()); LogHelper.WriteLog("YX_text-" + EventKey); MODEL.ViewModel.VIEW_YX_text textdt = new MODEL.ViewModel.VIEW_YX_text(); object text_dt = CacheHelper.GetCache(EventKey);//设置主菜单缓存 防止多次访问数据库V1003_TODAY_MUSIC if (text_dt != null) { textdt = (MODEL.ViewModel.VIEW_YX_text)text_dt; } else { textdt = textM.GetClickMenusText(Id); if (textdt != null) { CacheHelper.SetCache(EventKey, textdt, TimeSpan.FromMinutes(60)); } } if (textdt != null) { string msgContent = textdt.msgContent; Common.Tools.GetPage("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=" + WeChatConfig.IsExistAccess_Token2(), GetSubcribePostData(UserOpenId, msgContent)); } } if (tableName == "YX_news")//发送图文消息 { LogHelper.WriteLog("YX_news-" + EventKey); MODEL.ViewModel.VIEW_YX_news newsdt = new MODEL.ViewModel.VIEW_YX_news(); object news_dt = CacheHelper.GetCache(EventKey);//设置主菜单缓存 防止多次访问数据库V1003_TODAY_MUSIC if (news_dt != null) { newsdt = (MODEL.ViewModel.VIEW_YX_news)news_dt; } else { newsdt = newsM.GetClickMenusNews(Id); if (newsdt != null) { CacheHelper.SetCache(EventKey, newsdt, TimeSpan.FromMinutes(60)); } } if (newsdt != null) { string newsTitle = newsdt.newsTitle; string newsDescription = newsdt.newsDescription; string newsPicUrl = newsdt.newsPicUrl; string newsUrl = newsdt.newsUrl; Senparc.Weixin.MP.Entities.Article arc = new Senparc.Weixin.MP.Entities.Article(); arc.Title = newsTitle; arc.Description = newsDescription; arc.PicUrl = newsPicUrl; arc.Url = newsUrl; List <Senparc.Weixin.MP.Entities.Article> list = new List <Senparc.Weixin.MP.Entities.Article>(); list.Add(arc); CustomApi.SendNews(WeChatConfig.IsExistAccess_Token2(), UserOpenId, list); } } if (tableName == "YX_image")//发送图片消息 { //DataTable imagedt = new DataTable(); //imagedt = wxdb.GetClickMenusMsg(tableName, Id); //if (imagedt != null) //{ //} } if (tableName == "YX_voice")//发送语音消息 { //DataTable voicedt = new DataTable(); //voicedt = wxdb.GetClickMenusMsg(tableName, Id); } if (tableName == "YX_video")//发送视频消息 { //DataTable videodt = new DataTable(); //videodt = wxdb.GetClickMenusMsg(tableName, Id); } if (tableName == "YX_music")//发送音乐消息 { //DataTable musicdt = new DataTable(); //musicdt = wxdb.GetClickMenusMsg(tableName, Id); } } } } #endregion if (!string.IsNullOrEmpty(EventName) && EventName.Trim().ToLower() == "scancode_push")//菜单单击事件 { LogHelper.WriteLog("scancode_push"); } #endregion }
/// <summary> /// 关注事件 /// </summary> /// <param name="requestMessage"></param> public void Subscribe(RequestMessageEvent_Subscribe requestMessage) { OfficialAccount_BLL obll = new OfficialAccount_BLL(); OfficialAccount model = obll.Get(a => a.OriginalID == requestMessage.ToUserName); if (!AccessTokenContainer.CheckRegistered(model.AppID)) //检查是否已经注册 { AccessTokenContainer.Register(model.AppID, model.AppSecret); //如果没有注册则进行注册 } Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson uij = UserApi.Info(model.AppID, requestMessage.FromUserName); bool isInArea = false; if (model.AreaLimit != null) { if (model.AreaLevel == "国家" && model.AreaLimit.Contains(uij.country)) { isInArea = true; } if (model.AreaLevel == "省份" && model.AreaLimit.Contains(uij.province)) { isInArea = true; } if (model.AreaLevel == "城市" && model.AreaLimit.Contains(uij.city)) { isInArea = true; } } else { isInArea = true; } if (!isInArea) { try { Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, uij.openid, "对不起,该活动只限" + model.AreaLimit + "地区用户!"); } catch (Exception e) { } } //判断返回体是否带有参数 bool hasPara = !string.IsNullOrWhiteSpace(requestMessage.EventKey); string popenid = hasPara ? requestMessage.EventKey.Substring(8) : null; Subscriber_BLL bll = new Subscriber_BLL(); //扫码者是否存在 if (bll.GetCount(a => a.OpenID == uij.openid && a.AccountID == model.AccountID) > 0) { //如果存在(指的是数据库中有没有用的信息) Subscriber sub = bll.Get(a => a.OpenID == uij.openid && a.AccountID == model.AccountID); if (sub.IsOK == true) { sub.FromOpenID = popenid; bll.Update(sub); //如果已关注 //Senparc.Weixin.MP.AdvancedAPIs.CustomApi.SendText(model.AppID, sub.OpenID, model.ReSubscribeWelcome);//吃菊 } else { //如果已取消关注 sub.FromOpenID = popenid; sub.IsOK = true; bll.Update(sub); try { CustomApi.SendText(model.AppID, sub.OpenID, model.ReSubscribeWelcome); } catch (Exception e) { } //再次关注发送消息 } } else { //如果不存在 //添加扫码者信息 Subscriber sub = new Subscriber { SubscribeID = Guid.NewGuid(), AccountID = model.AccountID, NickName = uij.nickname, Province = uij.province, City = uij.city, Country = uij.country, OpenID = uij.openid, Sex = uij.sex, HeadImgUrl = uij.headimgurl, FromOpenID = popenid, SubscribeTime = DateTime.Parse("1970-01-01 08:00").AddSeconds(uij.subscribe_time), Score = 0, SignScore = 0, DirectScore = 0, IndirectScore = 0, SignContinuityCount = 0, UnSubscribeCount = 0, IsOK = true }; bll.Add(sub); //发送首次关注欢迎信息 try { CustomApi.SendText(model.AppID, sub.OpenID, model.SubscribeWelcome); } catch (Exception e) { } if (hasPara) { //判断参数对应用户是否存在(第一级) if (bll.GetCount(a => a.OpenID == popenid && a.AccountID == model.AccountID) > 0) { if (isInArea) { Subscriber psub = bll.Get(a => a.OpenID == popenid && a.AccountID == model.AccountID); if (psub.DirectScore != null) { psub.DirectScore += model.SubscribeAddScore; } else { psub.DirectScore = model.SubscribeAddScore; } psub.DirectScoreUpdateTime = DateTime.Parse("1970-01-01 08:00").AddSeconds(uij.subscribe_time); if (psub.Score != null) { psub.Score += model.SubscribeAddScore; } else { psub.Score = model.SubscribeAddScore; } bll.Update(psub); //发送第一级 StringBuilder msgp = new StringBuilder(); msgp.Append("恭喜,您有新的粉丝【" + uij.nickname + "】加入!\n"); msgp.Append("获得推广积分:" + model.SubscribeAddScore + "分,累计积分:" + psub.Score.ToString() + "分\n"); CustomApi.SendText(model.AppID, psub.OpenID, msgp.ToString()); } } else { if (isInArea) { //第一级用户不存在,需要补充信息 Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson puij = UserApi.Info(model.AppID, popenid); //补充上一级信息 Subscriber psub = new Subscriber { SubscribeID = Guid.NewGuid(), AccountID = model.AccountID, NickName = puij.nickname, Province = puij.province, City = puij.city, Country = puij.country, OpenID = puij.openid, Sex = puij.sex, HeadImgUrl = puij.headimgurl, SubscribeTime = DateTime.Parse("1970-01-01 08:00").AddSeconds(puij.subscribe_time), Score = model.SubscribeAddScore, SignScore = 0, DirectScore = model.SubscribeAddScore, DirectScoreUpdateTime = sub.SubscribeTime, IndirectScore = 0, SignContinuityCount = 0, UnSubscribeCount = 0, IsOK = true }; bll.Add(psub); //发送第一级 StringBuilder msgp = new StringBuilder(); msgp.Append("恭喜,您有新的粉丝【" + uij.nickname + "】加入!\n"); msgp.Append("获得推广积分:" + model.SubscribeAddScore + "分,累计积分:" + psub.Score.ToString() + "分\n"); CustomApi.SendText(model.AppID, psub.OpenID, msgp.ToString()); } else { //第一级用户不存在,需要补充信息 Senparc.Weixin.MP.AdvancedAPIs.User.UserInfoJson puij = UserApi.Info(model.AppID, popenid); //补充上一级信息 Subscriber psub = new Subscriber { SubscribeID = Guid.NewGuid(), AccountID = model.AccountID, NickName = puij.nickname, Province = puij.province, City = puij.city, Country = puij.country, OpenID = puij.openid, Sex = puij.sex, HeadImgUrl = puij.headimgurl, SubscribeTime = DateTime.Parse("1970-01-01 08:00").AddSeconds(puij.subscribe_time), Score = 0, SignScore = 0, DirectScore = 0, DirectScoreUpdateTime = sub.SubscribeTime, IndirectScore = 0, SignContinuityCount = 0, UnSubscribeCount = 0, IsOK = true }; bll.Add(psub); //发送第一级 } } } } }