企业微信网页授权初试

代码中重定向:

  if (Request["code"] == null)
            //if (Request.Cookies["UID"] == null)
            {
                string httpUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww732213544815bfee&redirect_uri=http://www.xxx.com/Report/Login&response_type=code&scope=snsapi_base&#wechat_redirect";
                Response.Redirect(httpUrl);
                EmptyResult er = new EmptyResult();
                ViewBag.UID = 0;
                return View(er);
            }
            else
            {
                //TODO 获取userguid之后处理步骤 Request.Cookies["UserGuid"].ToString();
                string token = WXQYHHelper.GetAccessToken();
                //5.获取UserInfo,包含userId
                string userinfoUrl = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo";
                string userinfojson = WXQYHHelper.GetBase(userinfoUrl + "?access_token=" + token + "&code=" + Request["code"]);
                TicketController.Userinfo userinfo1 = JsonConvert.DeserializeObject(userinfojson);
                //HttpCookie cookie = new HttpCookie("UID", userinfo1.UserId);
                ViewBag.UID = userinfo1.UserId;
            }
            return View();


        public class Userinfo
        {
            public string UserId { get; set; }
            public string DeviceId { get; set; }
        }
public class WXQYHHelper
    {
        private WXQYHHelper() { }

        static string CORPID;
        static string SECRET;

        /// 
        /// .Ctor
        /// 
        static WXQYHHelper()
        {
            //企业ID 企业微信唯一
            CORPID = ConfigurationManager.AppSettings["CorpID"];
            SECRET = ConfigurationManager.AppSettings["ticketSecret"];
        }

        /// 
        /// ACCESS_TOKEN最后一次更新时间
        /// 
        static DateTime _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds(-7201);

        /// 
        /// 存储微信访问凭证
        /// 
        static string _AccessToken;

        /// 
        /// 获取微信访问凭证
        /// 
        public static string GetAccessToken()
        {
            try
            {
                if (_lastGetTimeOfAccessToken < DateTime.Now)
                {

                    string url = string.Format("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={0}&corpsecret={1}", CORPID, SECRET);
                    string responseText = GetBase(url); // 封装的get请求
                                                        /*
                                                            API:http://qydev.weixin.qq.com/wiki/index.php?title=%E4%B8%BB%E5%8A%A8%E8%B0%83%E7%94%A8#.E8.8E.B7.E5.8F.96AccessToken
                                                            正确的Json返回示例:
                                                            {
                                                               "access_token": "accesstoken000001",
                                                               "expires_in": 7200
                                                            }
                                                            错误的Json返回示例:
                                                            {
                                                               "errcode": 43003,
                                                               "errmsg": "require https"
                                                            }
                                                        */
                    var rsEntity = new { access_token = "", expires_in = 0, errcode = 0, errmsg = "" };
                    dynamic en = Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(responseText, rsEntity); // Newtonsoft.Json提供的匿名类反序列化
                    _lastGetTimeOfAccessToken = DateTime.Now.AddSeconds((double)en.expires_in - 1);
                    _AccessToken = en.access_token;
                }
                return _AccessToken;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static string Get(string url)
        {
            string baseUrl = ConfigurationManager.AppSettings["baseUrl"];// "http://192.168.103.200:8001/eps/api/interface/";
            var request = (HttpWebRequest)WebRequest.Create(baseUrl + url);
            var response = (HttpWebResponse)request.GetResponse();
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        } 

        public static string GetTicket(string url)
        {
            string baseUrl = ConfigurationManager.AppSettings["ticketUrl"];// "http://192.168.40.44:8080/fzt/api/ticketinterface/";
            var request = (HttpWebRequest)WebRequest.Create(baseUrl + url);
            var response = (HttpWebResponse)request.GetResponse();
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        public static string GetBase(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            var response = (HttpWebResponse)request.GetResponse();
            return new StreamReader(response.GetResponseStream()).ReadToEnd();
        }

        public static string PostDate(string url, string sparams)
        {
            System.Net.HttpWebRequest request;
            request = (System.Net.HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["ticketUrl"] + url);
            //Post请求方式  
            request.Method = "POST";
            // 内容类型  

            request.ContentType = "application/x-www-form-urlencoded";
            byte[] payload;
            //将URL编码后的字符串转化为字节  
            payload = System.Text.Encoding.UTF8.GetBytes(sparams);
            //设置请求的 ContentLength   
            request.ContentLength = payload.Length;
            //获得请 求流  
            System.IO.Stream writer = request.GetRequestStream();
            //将请求参数写入流  
            writer.Write(payload, 0, payload.Length);
            // 关闭请求流  
            writer.Close();
            System.Net.HttpWebResponse response;
            // 获得响应流  
            response = (System.Net.HttpWebResponse)request.GetResponse();
            System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string responseText = myreader.ReadToEnd();
            myreader.Close();
            return responseText;
        }
    } 
  

开发文档:https://work.weixin.qq.com/api/doc#10012

微信接口类(比如扫一扫,分享这种微信功能的):https://open.work.weixin.qq.com/api/jsapidemo#menu-basic

把上面的地址发送到企业微信中用手机就能打开测试了.

网页授权:https://work.weixin.qq.com/api/doc#10028

步骤:

1、登录到企业管理端后台,选择“企业应用”选项卡,进入需要使用网页授权的应用并编辑“可信域名”表单项,此选项将用于网页OAuth2.0授权的时候进行安全验证。请注意,这里填写的是域名,而不是URL,因此请勿加 http:// 等协议头
2、可信域名配置规范为全域名。比如需要网页授权的域名为:www.qq.com,配置以后此域名下面的页面http://www.qq.com/music.html 、 http://www.qq.com/login.html 都可以进行OAuth2.0鉴权。但http://pay.qq.com 、 http://music.qq.com 、 http://qq.com无法进行OAuth2.0鉴权
3、如果redirect_uri有端口号,那么“可信域名”也必须带上端口号。

照着上面做就行了,上面的意思就是在企业微信的后台添加应用后设置主页和可信域名,主页如果想要有授权

我的示例:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=ww732213544815bfe1&redirect_uri=http://www.baidu.com&response_type=code&scope=snsapi_privateinfo&agentid=1000009&state=STATE&connect_redirect=1#wechat_redirect

上面一段网页是设置在应用的主页上的, redirect_uri是自己的网页

参数解释:

获取code

如果企业需要在打开的网页里面携带用户的身份信息,第一步需要构造如下的链接来获取code参数:

参数说明:

参数 必须 说明
appid 企业的CorpID
redirect_uri 授权后重定向的回调链接地址,请使用urlencode对链接进行处理
response_type 返回类型,此时固定为:code
scope 应用授权作用域。
snsapi_base:静默授权,可获取成员的的基础信息(UserId与DeviceId);
snsapi_userinfo:静默授权,可获取成员的详细信息,但不包含手机、邮箱;
snsapi_privateinfo:手动授权,可获取成员的详细信息,包含手机、邮箱
注意:企业自建应用可以根据userid获取成员详情,无需使用snsapi_userinfo和snsapi_privateinfo两种scope。更多说明见scope
agentid 企业应用的id。
当scope是snsapi_userinfo或snsapi_privateinfo时,该参数必填
注意redirect_uri的域名必须与该应用的可信域名一致
state 重定向后会带上state参数,企业可以填写a-zA-Z0-9的参数值,长度不可超过128个字节
#wechat_redirect 终端使用此参数判断是否需要带上身份信息

如果参数都填写正确,点击网页后页面url会重定向成:

 redirect_uri?code=CODE&state=STATE

比如redirect_url写的是http://www.baidu.com则网页的url变成http://www.baidu.com?code=.....

想要获取userid要根据这个code和token来访问以下接口:

https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE

流程:

企业微信网页授权初试_第1张图片

 

看懂上图就差不多了.

实际代码:

  $(function () {
        //先获取授权后的userid  第一次获取的userid可能为空(微信规则)
        debugger
        getUID();
        if (uid == "") //如果为空再获取一次
            getUID();
        isRes(); //根据uid判断是否已经注册

    })

用的razor  @Request["code"]意思是url地址中code的参数

    var uid = "";
    function getUID() {
        $.ajax({
            url: "@Url.Action("UID")?code=@Request["code"]",
            type: 'get',
            async: false,
            dataType: "html",
            success: function (data) {                
                uid = data;
            }
        })
    }
        public string UID(string code)
        {
            string token = GetQiyAccess_token();
            WriteLogs(DateTime.Now.Year.ToString(), "token", token); 
            string uid = GetQiyGetUserinfo(token, code);
            WriteLogs(DateTime.Now.Year.ToString(),"code", code);
            WriteLogs(DateTime.Now.Year.ToString(),"code", uid);
            return uid;
        }

上面检测BUG的时候不好测 用log日志类写在服务器上方便知道代码走到哪一步了  WriteLogs就是日志类

下面gettoken

 public string GetQiyAccess_token()
        {
            var request = (HttpWebRequest)WebRequest.Create("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ww732213544815b78fee&corpsecret=KCmFrkqMO_tt4PTaX7uzoV1D6o7IgaVNFEFIHBVMOnog");
            var response = (HttpWebResponse)request.GetResponse();
            var to = new StreamReader(response.GetResponseStream()).ReadToEnd();

            //TWeixinHelper weihelper = new TWeixinHelper();
            //string to = weihelper.GetData("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + appid + "&corpsecret=" + appsecret);


            string access_token = "";
            string strCode = @"\""access_token\"":\s*""(?'access_token'[^""]*)""";
            Regex regex = new Regex(strCode, RegexOptions.IgnoreCase);
            if (regex.IsMatch(to))
            {
                MatchCollection matches = regex.Matches(to);
                StringBuilder stringBuilder = new StringBuilder();
                foreach (Match match in matches)
                {
                    access_token = match.Groups["access_token"].Value;
                }
            }


            return access_token;
        }

然后获取授权人信息

   public string GetQiyGetUserinfo(string accesstoken, string code)
        {
            var request = (HttpWebRequest)WebRequest.Create("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accesstoken + "&code=" + code);
            var response = (HttpWebResponse)request.GetResponse();
            var to = new StreamReader(response.GetResponseStream()).ReadToEnd();

            //TWeixinHelper weihelper = new TWeixinHelper();
            //string to = weihelper.GetData("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + accesstoken + "&code=" + code);


            string strUserId = "";
            string strCode = @"\""UserId\"":\s*""(?'UserId'[^""]*)""";
            Regex regex = new Regex(strCode, RegexOptions.IgnoreCase);
            if (regex.IsMatch(to))
            {
                MatchCollection matches = regex.Matches(to);
                StringBuilder stringBuilder = new StringBuilder();
                foreach (Match match in matches)
                {
                    strUserId = match.Groups["UserId"].Value;
                }
            }
            return strUserId;
        }

 

 

 

你可能感兴趣的:(微信开发)