public OperateStatus MoveUser(Account currentAccount, string openID, string groupID)
        {
            try
            {
                var accessToken = AccessTokenHelper.GetAccessToken(currentAccount);
                var postParams = new { openid = openID, to_groupid = groupID };
                var postParamsStr = JsonConvert.SerializeObject(postParams);

                var url = string.Format(MoveUserUrlFormat, accessToken);
                var responseResult = HttpHelper.GetResponseResultByPost(url, postParamsStr, contentType: "application/json");
                if (responseResult.Status != ResponseStatus.Success)
                {
                    return null;
                }
                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("移动错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };
            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "移动异常," + ex.Message };
            }
        }
Beispiel #2
0
        private OperateStatus SendMessage(Account currentAccount, SendMsg msg)
        {
            try
            {
                string url = string.Format(SendMessageUrlFormat, AccessTokenHelper.GetAccessToken(currentAccount));

                var param = JsonConvert.SerializeObject(msg);
                var responseResult = HttpHelper.GetResponseResultByPost(url, param, contentType: "application/json");

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("创建错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "创建异常," + ex.Message };
            }
        }
Beispiel #3
0
 private bool CheckSignature(Account account, string signature, string timestamp, string nonce)
 {
     ISet<string> paramList = new SortedSet<string> { account.Token, timestamp, nonce };
     var currentSignature = HashCryptography.Sha1Encrypt(paramList.Aggregate((o, t) => o + t));
     FileLogHelper.WriteInfo("CheckSignature:" + currentSignature);
     return currentSignature == signature;
 }
Beispiel #4
0
        public OperateStatus SendTemplateMsg(Account currentAccount, TemplateMsgParams templateMsgParams, IList<TemplateParameter> parameters)
        {
            try
            {
                string url = SendTemplateMsgUrl + AccessTokenHelper.GetAccessToken(currentAccount);

                var templateMsg = new TemplateMsg(templateMsgParams, parameters);

                var param = JsonConvert.SerializeObject(templateMsg);
                var responseResult = HttpHelper.GetResponseResultByPost(url, param);

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("发送错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送异常," + ex.Message };
            }
        }
        public OperateStatus Create(Account currentAccount, IList<CustomMenu> menus)
        {
            try
            {
                string url = MenuCreateUrl + AccessTokenHelper.GetAccessToken(currentAccount);

                var menu = new Menu();
                menu.AddButtons(menus);

                var param = JsonConvert.SerializeObject(menu);
                var responseResult = HttpHelper.GetResponseResultByPost(url, param, contentType: "application/json");

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("创建错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "创建异常," + ex.Message };
            }
        }
Beispiel #6
0
        public OperateStatus Delete(Account currentAccount, string userId)
        {
            try
            {
                string url = string.Format(UserDeleteUrlFormat, AccessTokenHelper.GetAccessToken(currentAccount), userId);

                var responseResult = HttpHelper.GetResponseResultByGet(url);

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("删除错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "删除异常," + ex.Message };
            }
        }
 public string GetOpenIDByCode(Account currentAccount, string code)
 {
     var accessTokenInfo = GetAccessTokenInfo(currentAccount, code);
     if (accessTokenInfo == null)
     {
         return string.Empty;
     }
     return accessTokenInfo.OpenID;
 }
Beispiel #8
0
        public OperateStatus Main(Account currentAccount, string signature, string timestamp, string nonce, string echostr)
        {
            WXBizMsgCryptHelper wxcrptyHelper = new WXBizMsgCryptHelper();

            if (!string.IsNullOrEmpty(echostr))
            {
                return VerifyUrl(currentAccount, signature, timestamp, nonce, echostr);
            }

            var content = GetContent();
            FileLogHelper.WriteInfo("Content:" + content, "CorpInfoLog");
            if (string.IsNullOrEmpty(content))
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "请求参数内容不存在" };
            }

            string deContent;
            var ret = wxcrptyHelper.DecryptMsg(currentAccount, signature, timestamp, nonce, content, out deContent);
            if (ret != EnumWXBizMsgCryptErrorCode.OK)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "解密不通过," + ret };
            }
            FileLogHelper.WriteInfo("DeCentent:" + deContent, "CorpInfoLog");

            var dicParams = XmlHelper.ConvertToDictionary(deContent);
            FileLogHelper.WriteInfo("DicParams:" + dicParams, "CorpInfoLog");

            if (!dicParams.ContainsKey("MsgType"))
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "不包含MsgType" };
            }
            string responseStr;
            switch (dicParams["MsgType"])
            {
                case "text":
                    responseStr = GetResponseForText(currentAccount, dicParams);
                    break;
                case "event":
                    responseStr = GetResponseForEvent(currentAccount, dicParams);
                    break;
                default:
                    responseStr = "暂时不支持";
                    break;
            }
            FileLogHelper.WriteInfo("ResponseString:" + responseStr, "CorpInfoLog");

            string enResponseStr;
            ret = wxcrptyHelper.EncryptMsg(currentAccount, responseStr, timestamp, nonce,
                out enResponseStr);
            if (ret != EnumWXBizMsgCryptErrorCode.OK)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "加密不通过" };
            }

            FileLogHelper.WriteInfo("EncryptMsg:" + enResponseStr, "CorpInfoLog");
            return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = enResponseStr };
        }
 private AccessTokenInfo GetAccessTokenInfo(Account currentAccount, string code)
 {
     var url = string.Format(GetAccessTokenUrlFormat, currentAccount.AppID, currentAccount.AppSecret, code);
     var responseResult = HttpHelper.GetResponseResultByGet(url);
     if (responseResult.Status != ResponseStatus.Success)
     {
         return null;
     }
     return JsonConvert.DeserializeObject<AccessTokenInfo>(responseResult.ResponseString);
 }
        public UserInfo GetUserInfoByCode(Account currentAccount, string code)
        {
            var accessToken = AccessTokenHelper.GetAccessToken(currentAccount);

            var url = string.Format(GetUserInfoUrlFormat, accessToken, code);
            var responseResult = HttpHelper.GetResponseResultByGet(url);
            if (responseResult.Status != ResponseStatus.Success)
            {
                return null;
            }
            return JsonConvert.DeserializeObject<UserInfo>(responseResult.ResponseString);
        }
Beispiel #11
0
        /// <summary>
        /// 获取签名
        /// </summary>
        /// <param name="currentAccount">当前账号信息</param>
        /// <param name="noncestr">随机字符串</param>
        /// <param name="timestamp">时间戳</param>
        /// <param name="currentUrl">当前页面的Url</param>
        /// <returns>签名</returns>
        private static string GetSignature(Account currentAccount, string noncestr, string timestamp, string currentUrl)
        {
            var dicPreParams = new Dictionary<string, string>
            {
                {"noncestr",noncestr},
                {"timestamp",timestamp},
                {"jsapi_ticket",GetTicket(currentAccount)},
                {"url",currentUrl}
            };

            var preStr = HttpHelper.CreateLinkString(dicPreParams);
            return HashCryptography.Sha1Encrypt(preStr);
        }
Beispiel #12
0
        /// <summary>
        /// 获取JS请求所需数据
        /// </summary>
        /// <param name="currentAccount">账号</param>
        /// <param name="currentUrl">当前页面的Url</param>
        /// <returns>操作结果,WeiXinJsData</returns>
        public OperateStatus GetJsData(Account currentAccount, string currentUrl)
        {
            string noncestr = DateTime.Now.ToString("yyyyMMddHHmmss");
            string timestamp = DateTime.Now.ToTimestamp().ToString();
            string signature = GetSignature(currentAccount, noncestr, timestamp, currentUrl);

            var returnValue = JsonConvert.SerializeObject(new WeiXinJsData
            {
                AppID = currentAccount.AppID,
                NonceStr = noncestr,
                Timestamp = timestamp,
                Signature = signature
            });
            return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = returnValue };
        }
Beispiel #13
0
        public OperateStatus Main(Account currentAccount, string signature, string timestamp, string nonce, string echostr)
        {
            if (!CheckSignature(currentAccount, signature, timestamp, nonce))
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "验签不通过" };
            }

            if (!string.IsNullOrEmpty(echostr))
            {
                return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = echostr };
            }

            HttpContext.Current.Request.InputStream.Position = 0;
            string content;
            using (var reader = new StreamReader(HttpContext.Current.Request.InputStream))
            {
                content = reader.ReadToEnd();
            }

            FileLogHelper.WriteInfo("Content:" + content);
            if (string.IsNullOrEmpty(content))
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "请求参数内容不存在" };
            }
            var dicParams = XmlHelper.ConvertToDictionary(content);
            FileLogHelper.WriteInfo(dicParams);

            if (!dicParams.ContainsKey("MsgType"))
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "不包含MsgType" };
            }
            string responseStr;
            switch (dicParams["MsgType"])
            {
                case "text":
                    responseStr = GetResponseForText(currentAccount, dicParams);
                    break;
                case "event":
                    responseStr = GetResponseForEvent(currentAccount, dicParams);
                    break;
                default:
                    responseStr = "暂时不支持";
                    break;
            }
            FileLogHelper.WriteInfo("ResponseString:" + responseStr);

            return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = responseStr };
        }
        /// <summary>
        /// 获取通行令
        /// </summary>
        /// <param name="currentAccount">当前账号信息</param>
        /// <returns>通行令</returns>
        public static string GetAccessToken(Account currentAccount)
        {
            Monitor.Enter(DicAccessToken);
            try
            {
                AccessToken accessToken;
                if (DicAccessToken.ContainsKey(currentAccount.ID))
                {
                    accessToken = DicAccessToken[currentAccount.ID];
                    if (accessToken.ExpireTime > DateTime.Now)
                    {
                        return accessToken.Value;
                    }
                    DicAccessToken.Remove(currentAccount.ID);
                }

                var result =
                    HttpHelper.GetResponseResultByGet(
                        string.Format(GetTokenUrlFormat, currentAccount.AppID, currentAccount.AppSecret)
                        , timeout: 1000);
                if (result.Status != ResponseStatus.Success)
                {
                    return "";
                }
                JObject jObject = JsonConvert.DeserializeObject<JObject>(result.ResponseString);
                JToken value, time;
                if (!jObject.TryGetValue("access_token", out value) || !jObject.TryGetValue("expires_in", out time))
                {
                    return "";
                }

                accessToken = new AccessToken
                {
                    Value = value.ToString(),
                    ExpireTime = DateTime.Now.AddSeconds(time.ToObject<double>())
                };
                DicAccessToken.Add(currentAccount.ID, accessToken);

                return accessToken.Value;
            }
            finally
            {
                Monitor.Exit(DicAccessToken);
            }
        }
Beispiel #15
0
        /// <summary>
        /// 获取票据
        /// </summary>
        /// <param name="currentAccount">当前账号信息</param>
        /// <returns>票据</returns>
        private static string GetTicket(Account currentAccount)
        {
            Monitor.Enter(DicTicket);
            try
            {
                Ticket ticket;
                if (DicTicket.ContainsKey(currentAccount.ID))
                {
                    ticket = DicTicket[currentAccount.ID];
                    if (ticket.ExpireTime > DateTime.Now)
                    {
                        return ticket.Value;
                    }
                    DicTicket.Remove(currentAccount.ID);
                }

                var accessToken = AccessTokenHelper.GetAccessToken(currentAccount);
                var result = HttpHelper.GetResponseResultByGet(string.Format(GetTicketUrlFormat, accessToken),
                    timeout: 1000);
                if (result.Status != ResponseStatus.Success)
                {
                    return "";
                }
                JObject jObject = JsonConvert.DeserializeObject<JObject>(result.ResponseString);
                JToken value;
                if (!jObject.TryGetValue("ticket", out value))
                {
                    return "";
                }

                ticket = new Ticket { Value = value.ToString(), ExpireTime = DateTime.Now.AddSeconds(7190) };
                DicTicket.Add(currentAccount.ID, ticket);

                return ticket.Value;
            }
            finally
            {
                Monitor.Exit(DicTicket);
            }
        }
 // 检验消息的真实性,并且获取解密后的明文
 // @param sMsgSignature: 签名串,对应URL参数的msg_signature
 // @param sTimeStamp: 时间戳,对应URL参数的timestamp
 // @param sNonce: 随机串,对应URL参数的nonce
 // @param sPostData: 密文,对应POST请求的数据
 // @param sMsg: 解密后的原文,当return返回0时有效
 // @return: 成功0,失败返回对应的错误码
 public EnumWXBizMsgCryptErrorCode DecryptMsg(Account account, string sMsgSignature, string sTimeStamp, string sNonce, string sPostData, out string sMsg)
 {
     sMsg = string.Empty;
     if (account.EncodingAESKey.Length != 43)
     {
         return EnumWXBizMsgCryptErrorCode.IllegalAesKey;
     }
     XmlDocument doc = new XmlDocument();
     string sEncryptMsg;
     try
     {
         doc.LoadXml(sPostData);
         var root = doc.FirstChild;
         sEncryptMsg = root["Encrypt"].InnerText;
     }
     catch (Exception)
     {
         return EnumWXBizMsgCryptErrorCode.ParseXml_Error;
     }
     //verify signature
     var ret = VerifySignature(account.Token, sTimeStamp, sNonce, sEncryptMsg, sMsgSignature);
     if (ret != EnumWXBizMsgCryptErrorCode.OK)
         return ret;
     //decrypt
     string cpid;
     try
     {
         sMsg = WXCryptHelper.AES_Decrypt(sEncryptMsg, account.EncodingAESKey, out cpid);
     }
     catch (FormatException)
     {
         return EnumWXBizMsgCryptErrorCode.DecodeBase64_Error;
     }
     catch (Exception)
     {
         return EnumWXBizMsgCryptErrorCode.DecryptAES_Error;
     }
     return cpid != account.AppID ? EnumWXBizMsgCryptErrorCode.ValidateCorpid_Error : EnumWXBizMsgCryptErrorCode.OK;
 }
Beispiel #17
0
        private string GetResponseForEvent(Account currentAccount, Dictionary<string, string> dicParams)
        {
            if (!dicParams.ContainsKey("Event")) throw new Exception("没有获取到Event");
            switch (dicParams["Event"])
            {
                case "CLICK":
                    {
                        if (!dicParams.ContainsKey("EventKey")) throw new Exception("没有获取到EventKey");

                        Reply reply;
                        var clickEvents = EventListenerProvider.GetEventListener<IWeiXinClickEvent>(currentAccount.ID, dicParams["EventKey"], out reply);

                        var events = clickEvents.Aggregate(new Action<IDictionary<string, string>, Reply>((a, b) => { }),
                            (s, c) => s + c.OnEventInvoke);

                        EventHelper.EventInvoke(events, dicParams, reply);

                        var responseEvent = EventListenerProvider.GetSpecialEvent(clickEvents, reply);

                        return responseEvent.GetResponseString(dicParams, reply);
                    }
                case "subscribe":
                    {
                        Reply reply;
                        var sEvents = EventListenerProvider.GetEventListener<IWeiXinSubscribeEvent>(currentAccount.ID, "subscribe", out reply);

                        if (sEvents != null)
                        {
                            var events = sEvents.Aggregate(
                                new Action<IDictionary<string, string>, Reply>((a, b) => { }),
                                (s, c) => s + c.OnEventInvoke);
                            EventHelper.EventInvoke(events, dicParams, reply);
                        }
                        var responseEvent = EventListenerProvider.GetSpecialEvent(sEvents, reply);

                        return responseEvent.GetResponseString(dicParams, reply);
                    }
                case "unsubscribe":
                    {
                        var sEvents = EventListenerProvider.GetEventListener<IWeiXinUnsubscribeEvent>(currentAccount.ID);

                        if (sEvents != null)
                        {
                            var events = sEvents.Aggregate(
                                new Action<IDictionary<string, string>, Reply>((a, b) => { }),
                                (s, c) => s + c.OnEventInvoke);
                            EventHelper.EventInvoke(events, dicParams, null);
                        }
                        return string.Empty;
                    }
                case "SCAN":
                    return null;
                case "LOCATION":
                    return null;
                default:
                    return null;
            }
        }
 //验证URL
 // @param sMsgSignature: 签名串,对应URL参数的msg_signature
 // @param sTimeStamp: 时间戳,对应URL参数的timestamp
 // @param sNonce: 随机串,对应URL参数的nonce
 // @param sEchoStr: 随机串,对应URL参数的echostr
 // @param sReplyEchoStr: 解密之后的echostr,当return返回0时有效
 // @return:成功0,失败返回对应的错误码
 public EnumWXBizMsgCryptErrorCode VerifyURL(Account account, string sMsgSignature, string sTimeStamp, string sNonce, string sEchoStr, out string sReplyEchoStr)
 {
     sReplyEchoStr = string.Empty;
     if (account.EncodingAESKey.Length != 43)
     {
         return EnumWXBizMsgCryptErrorCode.IllegalAesKey;
     }
     var ret = VerifySignature(account.Token, sTimeStamp, sNonce, sEchoStr, sMsgSignature);
     if (0 != ret)
     {
         return ret;
     }
     string cpid;
     try
     {
         sReplyEchoStr = WXCryptHelper.AES_Decrypt(sEchoStr, account.EncodingAESKey, out cpid); //m_sCorpID);
     }
     catch (Exception)
     {
         sReplyEchoStr = "";
         return EnumWXBizMsgCryptErrorCode.DecryptAES_Error;
     }
     if (cpid != account.AppID)
     {
         sReplyEchoStr = "";
         return EnumWXBizMsgCryptErrorCode.ValidateCorpid_Error;
     }
     return EnumWXBizMsgCryptErrorCode.OK;
 }
        public string GetAuthUrl(Account currentAccount, string redirectUrl, EnumGetAuthType getAuthType)
        {
            var scope = getAuthType == EnumGetAuthType.Base ? "snsapi_base" : "snsapi_userinfo";

            return string.Format(GetAuthUrlFormat, currentAccount.AppID, HttpUtility.UrlEncode(redirectUrl), scope, "getauthcode");
        }
Beispiel #20
0
        public OperateStatus Invite(Account currentAccount, string userId)
        {
            try
            {
                string url = string.Format(UserInviteUrlFormat, AccessTokenHelper.GetAccessToken(currentAccount));

                var responseResult = HttpHelper.GetResponseResultByPost(url, string.Format("{{userid:{0}}}", userId), contentType: "application/json");

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = result.GetValue("type").ToString() };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("邀请错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "邀请异常," + ex.Message };
            }
        }
Beispiel #21
0
        private OperateStatus VerifyUrl(Account currentAccount, string signature, string timestamp, string nonce, string echostr)
        {
            WXBizMsgCryptHelper wxcrptyHelper = new WXBizMsgCryptHelper();
            string replyEchoStr;
            var ret = wxcrptyHelper.VerifyURL(currentAccount, signature, timestamp, nonce, echostr, out replyEchoStr);
            if (ret != EnumWXBizMsgCryptErrorCode.OK)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "验签不通过" };
            }

            return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = replyEchoStr };
        }
Beispiel #22
0
 public OperateStatus SendTextMessage(Account currentAccount, SendMessageTarget target, string message)
 {
     // ReSharper disable once PossibleInvalidOperationException
     var sendMsg = new SendMsg(currentAccount.AgentID.Value, target, message);
     return SendMessage(currentAccount, sendMsg);
 }
        //将企业号回复用户的消息加密打包
        // @param sReplyMsg: 企业号待回复用户的消息,xml格式的字符串
        // @param sTimeStamp: 时间戳,可以自己生成,也可以用URL参数的timestamp
        // @param sNonce: 随机串,可以自己生成,也可以用URL参数的nonce
        // @param sEncryptMsg: 加密后的可以直接回复用户的密文,包括msg_signature, timestamp, nonce, encrypt的xml格式的字符串,
        //                        当return返回0时有效
        // return:成功0,失败返回对应的错误码
        public EnumWXBizMsgCryptErrorCode EncryptMsg(Account account, string sReplyMsg, string sTimeStamp, string sNonce, out string sEncryptMsg)
        {
            sEncryptMsg = "";
            if (account.EncodingAESKey.Length != 43)
            {
                return EnumWXBizMsgCryptErrorCode.IllegalAesKey;
            }
            string raw;
            try
            {
                raw = WXCryptHelper.AES_Encrypt(sReplyMsg, account.EncodingAESKey, account.AppID);
            }
            catch (Exception)
            {
                return EnumWXBizMsgCryptErrorCode.EncryptAES_Error;
            }
            string MsgSigature;
            var ret = GenarateSinature(account.Token, sTimeStamp, sNonce, raw, out MsgSigature);
            if (EnumWXBizMsgCryptErrorCode.OK != ret)
            {
                return ret;
            }
            var strBuilder = new StringBuilder();
            strBuilder.AppendFormat("<xml><Encrypt><![CDATA[{0}]]></Encrypt>", raw);
            strBuilder.AppendFormat("<MsgSignature><![CDATA[{0}]]></MsgSignature>", MsgSigature);
            strBuilder.AppendFormat("<TimeStamp><![CDATA[{0}]]></TimeStamp>", sTimeStamp);
            strBuilder.AppendFormat("<Nonce><![CDATA[{0}]]></Nonce></xml>", sNonce);

            sEncryptMsg = strBuilder.ToString();
            return EnumWXBizMsgCryptErrorCode.OK;
        }
Beispiel #24
0
        public OperateStatus GetByDepartment(Account currentAccount, string departmentId, bool fetchChild, int enumStatus, bool getDetail)
        {
            try
            {
                var format = getDetail ? UserGetDetailByDeparmentUrlFormat : UserGetByDeparmentUrlFormat;

                string url = string.Format(format, AccessTokenHelper.GetAccessToken(currentAccount), departmentId, fetchChild ? 1 : 0, enumStatus);

                var responseResult = HttpHelper.GetResponseResultByGet(url);

                if (responseResult.Status != ResponseStatus.Success)
                {
                    return new OperateStatus { ResultSign = ResultSign.Failed, Message = "发送请求异常," + responseResult.ExceptionMessages };
                }

                var result = JsonConvert.DeserializeObject<JObject>(responseResult.ResponseString);
                var errcode = result.Value<int>("errcode");
                if (errcode == 0)
                {
                    var userInfoList = JsonConvert.DeserializeObject<IList<CorpUserInfo>>(result.Value<string>("userlist"));

                    return new OperateStatus { ResultSign = ResultSign.Success, ReturnValue = JsonConvert.SerializeObject(userInfoList) };
                }
                return new OperateStatus
                {
                    ResultSign = ResultSign.Failed,
                    Message = string.Format("获取错误,错误码:{0},错误信息:{1}", errcode, result.Value<string>("errmsg"))
                };

            }
            catch (Exception ex)
            {
                return new OperateStatus { ResultSign = ResultSign.Failed, Message = "获取异常," + ex.Message };
            }
        }
Beispiel #25
0
        private string GetResponseForText(Account currentAccount, Dictionary<string, string> dicParams)
        {
            if (!dicParams.ContainsKey("ToUserName")) throw new Exception("没有获取到ToUserName");
            if (!dicParams.ContainsKey("FromUserName")) throw new Exception("没有获取到FromUserName");
            if (!dicParams.ContainsKey("Content")) throw new Exception("没有获取到Content");

            var replyRepository = new ReplyRepository();
            Reply reply = replyRepository.GetReply(currentAccount.ID, dicParams["Content"], EnumKeyType.Keyword);

            BaseReply returnReply;
            switch (reply.Message.Type)
            {
                case (int)EnumReplyType.TextReply:
                    returnReply = new TextReply { Content = reply.Message.Content };
                    break;
                case (int)EnumReplyType.ArticleReply:
                    returnReply = new ArticleReply
                    {
                        Articles = JsonConvert.DeserializeObject<List<ArticleReplyItem>>(reply.Message.Content)
                    };
                    break;
                default:
                    return null;
            }

            returnReply.FromUserName = dicParams["ToUserName"];
            returnReply.ToUserName = dicParams["FromUserName"];

            return returnReply.GetXmlString();
        }