Пример #1
0
        /// <summary>
        /// 发送消息,有异常会跳过
        /// </summary>
        /// <param name="userIDs"></param>
        /// <param name="tempID"></param>
        /// <param name="data"></param>
        /// <param name="url"></param>
        public void SendTempMessage(IEnumerable <string> userIDs, string tempID, object data, string url)
        {
            var accessToken = GetAccessToken();

            foreach (var openID in userIDs)
            {
                var obj = new
                {
                    touser      = openID,
                    template_id = tempID,
                    url         = url,
                    data        = data
                };
                var api = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={accessToken}", "POST", obj);
                try
                {
                    var r2 = api.CreateRequestReturnJson();
                    Comm.WriteLog("wechat", $"OpenID:{openID},Result:{JsonConvert.SerializeObject(r2)}", DebugLogLevel.Normal);
                }
                catch (Exception ex)
                {
                    Comm.WriteLog("wechat", $"OpenID:{openID},Error:{ex.Message}", DebugLogLevel.Error);
                }
            }
        }
Пример #2
0
        public List <Models.User> GetUsesByDepID(int id)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", AccessToken);
            p.Add("department_id", id.ToString());
            p.Add("fetch_child", "0");
            var api    = new CommonApi.BaseApi($"https://qyapi.weixin.qq.com/cgi-bin/user/list{p.ToParam("?")}", "get");
            var result = api.CreateRequestReturnJson();

            return(result["userlist"].Value <JArray>()
                   .Select(s =>
            {
                ;
                return new Models.User
                {
                    Avatar = s["avatar"].Value <string>(),
                    Email = s["email"].Value <string>(),
                    Gender = (Gender)Enum.Parse(typeof(Gender), s["gender"].Value <string>()),
                    ID = s["userid"].Value <string>(),
                    Mobile = s["mobile"].Value <string>(),
                    Name = s["name"].Value <string>(),
                    Position = s["position"].Value <string>(),
                    Telephone = s["telephone"].Value <string>(),
                    //UnionID = GetUserUnionID(s["userid"].Value<string>())
                };
            }).ToList());
        }
Пример #3
0
        /// <summary>
        /// 获取微信用户基本信息,通过openID,Token内嵌
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public UserInfoResult GetUserInfoCgi(string openID)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", GetAccessToken());
            p.Add("openid", openID);
            p.Add("lang", "zh_CN");
            try
            {
                var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/user/info{p.ToParam("?")}", "GET")
                             .CreateRequestReturnJson();
                if (result["errcode"] != null)
                {
                    throw new Exception(JsonConvert.SerializeObject(result));
                }
                return(new UserInfoResult
                {
                    NickName = result["nickname"].Value <string>(),
                    HeadImgUrl = result["headimgurl"].Value <string>(),
                    UnionID = result["unionid"].Value <string>(),
                    IsSubscribe = result["subscribe"]?.Value <int>() == 1
                });
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #4
0
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <param name="corpid">公司ID 我的企业→企业信息→企业ID</param>
        /// <param name="secret">通讯录Secret 管理工具→通讯录同步→Secret</param>
        public void GetAccessToken(string corpid, string secret)
        {
            var api    = new CommonApi.BaseApi($"https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={secret}", "get");
            var result = api.CreateRequestReturnJson();

            AccessToken = result["access_token"].Value <string>();
        }
Пример #5
0
        /// <summary>
        /// 使用Code换取OpenID,UnionID,Token等
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public AccessTokenResult GetAccessTokenSns(string code)
        {
            var p = new Dictionary <string, string>();

            p.Add("appid", _config.AppID);
            p.Add("secret", _config.AppSecret);
            p.Add("code", code);
            p.Add("grant_type", "authorization_code");
            string url = $"https://api.weixin.qq.com/sns/oauth2/access_token{p.ToParam("?")}";

            Comm.WriteLog("GetAccessTokenSns", url, DebugLogLevel.Normal);
            var result = new CommonApi.BaseApi(url, "GET").CreateRequestReturnJson();

            if (result["errcode"] != null)
            {
                throw new Exception(JsonConvert.SerializeObject(result));
            }
            _config.AccessToken  = result["access_token"].Value <string>();
            _config.RefreshToken = result["refresh_token"].Value <string>();
            return(new AccessTokenResult
            {
                OpenID = result["openid"].Value <string>(),
                AccessToken = _config.AccessToken,
                UnionID = result["unionid"].Value <string>(),
                RefreshToken = _config.RefreshToken
            });
        }
Пример #6
0
        /// <summary>
        /// 获取微信用户基本信息,通过openID,Token内嵌
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public string GetUserUnionID(string userid)
        {
            var p0 = new Dictionary <string, object>();

            p0.Add("access_token", AccessToken);
            try
            {
                var api    = new CommonApi.BaseApi($"https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid{p0.ToParam("?")}", "POST", new { userid = userid });
                var openid = api.CreateRequestReturnJson()["openid"].Value <string>();

                var p = new Dictionary <string, string>();
                p.Add("access_token", AccessToken);
                p.Add("openid", openid);
                p.Add("lang", "zh_CN");
                var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/user/info{p.ToParam("?")}", "GET")
                             .CreateRequestReturnJson();
                if (result["errcode"] != null)
                {
                    throw new Exception(JsonConvert.SerializeObject(result));
                }
                return(result["unionid"].Value <string>());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #7
0
        public String JsSign(string url, string noncestr, string timestamp)
        {
            var api2 = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={GetAccessToken()}&type=jsapi", "GET");

            try
            {
                var josn2 = api2.CreateRequestReturnJson();

                var str = $"jsapi_ticket={josn2["ticket"].Value<string>()}&noncestr={noncestr}&timestamp={timestamp}&url={url}";
                //Comm.WriteLog("JsSign", $"accessToken:{_config.AccessToken} \r\n Url:{str}", Enums.DebugLogLevel.Normal);
                byte[] StrRes = Encoding.Default.GetBytes(str);
                System.Security.Cryptography.HashAlgorithm iSHA = new System.Security.Cryptography.SHA1CryptoServiceProvider();
                StrRes = iSHA.ComputeHash(StrRes);
                StringBuilder EnText = new StringBuilder();
                foreach (byte iByte in StrRes)
                {
                    EnText.AppendFormat("{0:x2}", iByte);
                }
                //Comm.WriteLog("JsSign", EnText.ToString(), Enums.DebugLogLevel.Normal);
                return(EnText.ToString());
            }
            catch (Exception ex)
            {
                Comm.WriteLog("JsSignError", ex.Message, Enums.DebugLogLevel.Error);
                throw new Exception(ex.Message);
            }
        }
Пример #8
0
        /// <summary>
        /// 获取token
        /// </summary>
        /// <returns></returns>
        //public string GetAccessToken()
        //{
        //    var date = DateTime.Now;
        //    var api = new Api.BaseApi($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppID}&secret={Secret}", "GET");
        //    var result = api.CreateRequestReturnJson();
        //    _accessToken = new WeChat.AccessToken()
        //    {
        //        Code = result["access_token"].Value<string>(),
        //        End = DateTime.Now.AddSeconds(3500)
        //    };
        //    return _accessToken.Code;
        //}

        /// <summary>
        /// 使用Code换取OpenID和UnionID
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public Jscode2sessionResult Jscode2session(string code)
        {
            var p = new Dictionary <string, string>();

            p.Add("appid", AppID);
            p.Add("secret", Secret);
            p.Add("js_code", code);
            p.Add("grant_type", "authorization_code");
            var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/sns/jscode2session{p.ToParam("?")}", "GET").CreateRequestReturnJson();

            if (result["errcode"] != null)
            {
                throw new Exception(JsonConvert.SerializeObject(result));
            }


            var jscode2Session = new Jscode2sessionResult
            {
                OpenID  = result["openid"].Value <string>(),
                UnionID = result["unionid"]?.Value <string>(),
                Session = result["session_key"].Value <string>(),
            };

            Jscode2sessionResultList.SetSession(jscode2Session.OpenID, jscode2Session.Session);
            return(jscode2Session);
        }
Пример #9
0
        public string GetMenu()
        {
            string accessToken = GetAccessToken();
            var    url         = $"https://api.weixin.qq.com/cgi-bin/menu/get?access_token={accessToken}";
            var    api         = new CommonApi.BaseApi(url, "GET");
            var    result      = api.CreateRequestReturnString();

            return(result);
        }
Пример #10
0
        /// <summary>
        /// 刷新Token
        /// </summary>
        /// <returns></returns>
        public void RefreshToken()
        {
            var date   = DateTime.Now;
            var api    = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={AppID}&secret={Secret}", "GET");
            var result = api.CreateRequestReturnJson();

            _config.AccessToken    = result["access_token"].Value <string>();
            _config.AccessTokenEnd = DateTime.Now.AddSeconds(3500);
        }
Пример #11
0
        /// <summary>
        /// 注册用户(更新用户数据?)到腾讯云(已经注册的用户调用该接口不会报错,也不会重复注册)
        /// </summary>
        /// <param name="name">帐号 长度限制32</param>
        /// <param name="nickname">昵称</param>
        /// <param name="avatar">头像</param>
        public void ImportUser(string name, string nickname, string avatar)
        {
            //使用管理员帐号导入用户(注册)
            string url    = $"https://console.tim.qq.com/v4/im_open_login_svc/account_import?usersig={ImConfig.Sign}&identifier={ImConfig.Admin}&sdkappid={ImConfig.SdkAppId}&random={ImConfig.Random}&contenttype=json";
            var    api    = new CommonApi.BaseApi(url, "POST", new { Identifier = name, Nick = nickname, FaceUrl = avatar });
            var    result = api.CreateRequestReturnJson();

            if (result["ErrorCode"].Value <int>() != 0)
            {
                throw new Exception(result["ErrorInfo"].Value <string>());
            }
        }
Пример #12
0
        /// <summary>
        /// 修改微信菜单
        /// </summary>
        /// <param name="menu"></param>
        public void CreateMenu(string menu)
        {
            var    jMenu       = JsonConvert.DeserializeObject <JObject>(menu);
            string accessToken = GetAccessToken();
            var    url         = $"https://api.weixin.qq.com/cgi-bin/menu/create?access_token={accessToken}";
            var    api         = new CommonApi.BaseApi(url, "POST", jMenu);
            var    result      = api.CreateRequestReturnJson();

            if (result["errcode"].Value <string>() != "0")
            {
                throw new Exception(result["errmsg"].Value <string>());
            }
        }
Пример #13
0
        /// <summary>
        /// 获取关注用户的OpenID
        /// </summary>
        /// <param name="next">第一个拉取的OPENID,不填默认从头开始拉取</param>
        /// <returns></returns>
        public OpenIDList GetAllFollowerOpenIDs(string next = null)
        {
            var accessToken   = GetAccessToken();
            var apiGetOpenIDs = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/user/get?access_token={accessToken}&next_openid={next}", "GET");
            var result        = apiGetOpenIDs.CreateRequestReturnJson();
            var count         = result["count"].Value <int>();

            return(new OpenIDList
            {
                Count = count,
                Next = result["next_openid"].Value <string>(),
                OpenIDs = count > 0 ? result["data"]["openid"].Values <string>().ToArray() : new string[0],
                Total = result["total"].Value <int>(),
            });
        }
Пример #14
0
        /// <summary>
        /// 获取微信的推送消息模版
        /// </summary>
        /// <returns></returns>
        public List <TempMessage> GetAllTempMessage()
        {
            var url    = $"https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token={GetAccessToken()}";
            var api    = new CommonApi.BaseApi(url, "GET");
            var result = api.CreateRequestReturnJson();

            return(result["template_list"].Values <JObject>().Select(s => new TempMessage
            {
                Content = s["content"].Value <string>(),
                DeputyID = s["deputy_industry"].Value <string>(),
                ID = s["template_id"].Value <string>(),
                PrimaryID = s["primary_industry"].Value <string>(),
                Title = s["title"].Value <string>(),
            }).ToList());
        }
Пример #15
0
        /// <summary>
        /// 获取微信的临时文件
        /// </summary>
        /// <param name="mediaID">媒体ID</param>
        /// <param name="server">上传的服务器</param>
        /// <param name="extension">文件的扩展名带(.xxx)</param>
        /// <returns>本地服务返回~/Upload/xxxx.xxx,其他返回完整连接</returns>
        /// <remarks>文档:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727
        /// </remarks>
        public string GetTempMedia(string mediaID, CommModels.UploadServer server, string extension)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", GetAccessToken());
            p.Add("media_id", mediaID);

            string url = $"https://api.weixin.qq.com/cgi-bin/media/get{p.ToParam("?")}";

            //Comm.WriteLog("GetTempMedia", url, DebugLogLevel.Normal);
            try
            {
                var api   = new CommonApi.BaseApi(url, "GET");
                var dPath = $"~/Upload/{DateTime.Now:yyyyMMddHHmmss}{Comm.Random.Next(1000, 9999)}{extension}";
                var path  = HttpContext.Current.Server.MapPath(dPath);

                //string mp3SavePth = System.Web.HttpContext.Current.Request.MapPath($"~/Upload/{DateTime.Now:yyyyMMddHHmmss}{Comm.Random.Next(1000, 9999)}.mp3");

                var    result = api.CreateRequest();
                string errorMsg;
                var    reader = new StreamReader(result);
                errorMsg = reader.ReadToEnd();

                //Comm.WriteLog("GetTempMedia", errorMsg, DebugLogLevel.Normal);
                result.Position = 0;
                using (Stream output = File.OpenWrite(path))
                {
                    result.CopyTo(output);
                }
                switch (server)
                {
                default:
                case CommModels.UploadServer.Local:
                    return(dPath);

                case CommModels.UploadServer.QinQiu:
                    return(new Qiniu.QinQiuApi().upload(path, true));
                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);
                Comm.WriteLog("GetTempMedia", ex.Message, DebugLogLevel.Error);
                return(ex.Message);
            }
        }
Пример #16
0
        /// <summary>
        /// 获取微信用户基本信息
        /// </summary>
        /// <param name="openID"></param>
        /// <param name="accessToken"></param>
        /// <returns></returns>
        public UserInfoResult GetUserInfoSns(string openID)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", _config.AccessToken);
            p.Add("openid", openID);
            p.Add("lang", "zh_CN");
            var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/sns/userinfo{p.ToParam("?")}", "GET").CreateRequestReturnJson();

            if (result["errcode"] != null)
            {
                throw new Exception(JsonConvert.SerializeObject(result));
            }
            return(new UserInfoResult
            {
                NickName = result["nickname"].Value <string>(),
                HeadImgUrl = result["headimgurl"].Value <string>(),
                UnionID = result["unionid"].Value <string>(),
            });
        }
Пример #17
0
        /// <summary>
        /// 刷新微信登录的Token
        /// </summary>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public AccessTokenResult RefreshAccessTokenSns()
        {
            var p = new Dictionary <string, string>();

            p.Add("appid", _config.AppID);
            p.Add("grant_type", "refresh_token");
            p.Add("refresh_token", _config.RefreshToken);
            var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/sns/oauth2/refresh_token{p.ToParam("?")}", "GET").CreateRequestReturnJson();

            if (result["errcode"] != null)
            {
                throw new Exception(JsonConvert.SerializeObject(result));
            }
            _config.AccessToken  = result["access_token"].Value <string>();
            _config.RefreshToken = result["refresh_token"].Value <string>();
            return(new AccessTokenResult
            {
                OpenID = result["openid"].Value <string>(),
                AccessToken = _config.AccessToken,
                UnionID = result["unionid"].Value <string>(),
                RefreshToken = _config.RefreshToken
            });
        }
Пример #18
0
        /// <summary>
        /// 发送小程序推送
        /// </summary>
        /// <param name="openID">OpenID</param>
        /// <param name="formID">FromID</param>
        /// <param name="page">跳转页面</param>
        /// <param name="temp">模版<see cref="AiCard.Common.WeChat.WeChatMessageTemp.IWeChatMessageTemp"/> </param>
        /// <returns></returns>
        public string SendMessage(string openID, string formID, string page, WeChatMessageTemp.IWeChatMessageTemp temp)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", GetAccessToken());
            var data = new
            {
                touser      = openID,
                template_id = temp.ID,
                page        = page,
                data        = temp.Data,
                form_id     = formID,
            };
            var api     = new CommonApi.BaseApi($"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?{p.ToParam()}", "POST", data);
            var result  = api.CreateRequestReturnJson();
            var message = result["errmsg"].Value <string>();

            if (message != "ok")
            {
                throw new Exception(message);
            }
            return(JsonConvert.SerializeObject(result));
        }
Пример #19
0
        public List <Department> GetDepartment(int?pid = null)
        {
            var p = new Dictionary <string, object>();

            p.Add("access_token", AccessToken);
            p.Add("id", pid);
            var api = new CommonApi.BaseApi($"https://qyapi.weixin.qq.com/cgi-bin/department/list{p.ToParam("?")}", "get");

            var result = api.CreateRequestReturnJson();
            var deps   = result["department"].Value <JArray>()
                         .Select(s => new Models.Department
            {
                ID       = s["id"].Value <int>(),
                Name     = s["name"].Value <string>(),
                Order    = s["order"].Value <int>(),
                ParentID = s["parentid"].Value <int>()
            }).ToList();
            var tree = new List <Models.Department>();
            Action <Models.Department> setChild = null;

            setChild = pDep =>
            {
                pDep.Child.AddRange(deps.Where(s => s.ParentID == pDep.ID));
                foreach (var child in pDep.Child)
                {
                    setChild(child);
                }
            };
            var topDeps = deps.Where(s => s.ParentID == 0).ToList();

            foreach (var item in topDeps)
            {
                setChild(item);
            }
            return(topDeps);
        }
Пример #20
0
        /// <summary>
        /// 获取小程序码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetWXACodeUnlimit(Enum type, Dictionary <string, string> scene)
        {
            var p = new Dictionary <string, string>();

            p.Add("access_token", GetAccessToken());

            string path = $"Type={Convert.ToInt32(type)}&{scene.ToParam()}";
            string page = "";//中转页面

            if (_config.AppID == new ConfigMini().AppID)
            {
                page = $"pages/test1/test1";
            }
            else if (_config.AppID == new ConfigMiniPersonal().AppID)
            {
                page = $"pages/test1/test1";
            }
            var data = new
            {
                page       = page,
                scene      = path,
                is_hyaline = true,
                //line_color= "{ 'r':'255','g':'255','b':'255'}"
            };
            var result = new CommonApi.BaseApi($"https://api.weixin.qq.com/wxa/getwxacodeunlimit{p.ToParam("?")}", "POST", data).CreateRequest();

            string codeName = $"{path.Replace("&", "_").Replace("=", "_")}.png";
            var    pDir     = HttpContext.Current.Server.MapPath("~/Upload/");

            //判断返回的文件流是否是png格式
            if (SteamCheck.IsAllowedExtension(result, FileType.Png))
            {
                System.Drawing.Image img = System.Drawing.Image.FromStream(result);

                string newimgpath = $"{pDir}{codeName}";
                img.Save(newimgpath, ImageFormat.Png);
                string resultpath = null;
                try
                {
                    QinQiuApi qniu = new QinQiuApi();
                    resultpath = qniu.UploadFile(newimgpath, false, true);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    File.Delete(newimgpath);
                }
                return(resultpath);
            }
            else
            {
                string txtData = "";
                if (result == null)
                {
                    return(null);
                }
                using (var reader = new StreamReader(result))
                {
                    txtData = reader.ReadToEnd();
                }
                throw new Exception(txtData);
            }
        }