开发日志:企业微信实现扫码登录(WEB)
一:获取扫码登陆所需的参数:appid,secret,agentid
登录企业微信:https://work.weixin.qq.com/
扫码登录文档:https://work.weixin.qq.com/api/doc/90000/90135/90988
1:获取appid
点击我的企业就可以看到企业ID信息,这就是appid
2:获取secret和agentid
(1):点击应用管理-》点击创建应用
(2):应用创建完成之后我们就可以在应用中看到secret和agentid
2:配置企业微信授权登录
二:开发企业微信二维码登录功能
(1):开发企业微信二维码登录页面
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>企业微信扫码登录</title> <script src="http://rescdn.qqmail.com/node/ww/wwopenmng/js/sso/wwLogin-1.0.0.js"></script> </head> <body class="body"> <div id="wx_reg" style="text-align: center;margin-top: 10%;"> </div> <script> var wwLogin = new WwLogin({ "id": "wx_reg", "appid": "wwee5d37c708b1ecfb", "agentid": "1000020", "redirect_uri": encodeURIComponent('http://www.xxx.com/login/qywxlogin.ashx?type=qywxLogin'), "state": "lmg", "href":"", }); </script> </body> </html>
(2):开发企业微信二维码登录回调 qywxlogin.ashx
<%@ WebHandler Language="C#" Class="qywxlogin" Debug="true" %> using System; using System.IO; using System.Web; using System.Data; using System.Data.SqlClient; using System.Web.SessionState; using System.Configuration; using System.Collections; using System.Collections.Generic; using System.Net; using System.Text; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; public class qywxlogin : IHttpHandler, IRequiresSessionState { //企业微信 public string appid = ""; publi string secret = ""; public string PhyPath = ""; public void ProcessRequest (HttpContext context) { context.Response.ContentType = "text/plain"; context.Response.Cookies.Add(new HttpCookie("ASP.NET_SessionId", context.Session.SessionID)); PhyPath = context.Server.MapPath("/"); string type = context.Request["type"]; switch(type) { case "qywxLogin": qywxLogin(context); break; default: context.Response.Write("非法访问"); break; } context.Response.End(); } public void qywxLogin(HttpContext c){ string state = c.Request["state"]; string code = c.Request["code"]; string url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+appid+"&corpsecret="+secret+"&debug=1"; var token = HttpGet(url); if(!string.IsNullOrEmpty(token)) { JObject sk = JObject.Parse(token); if(sk["access_token"] != null) { string accessToken =sk["access_token"].ToString(); url ="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+accessToken+"&code="+code+"&debug=1"; var getuserinfo =HttpGet(url); JObject sk1 = JObject.Parse(getuserinfo); if(sk1["UserId"] != null) { string UserId=sk1["UserId"].ToString(); //企业微信通讯录里的账户名称 string sql ="select * from [Base_Users] where WeixinID='"+UserId+"'"; DataTable dtW = DataBase.ExecuteTable(sql); if(dtW != null && dtW.Rows.Count > 0) { //写 session }else{
//绑定页面 c.Response.Redirect("qywxbind.html?WeixinID="+UserId); } }else{ c.Response.Write(getuserinfo); } }else{ c.Response.Write(token); } }else{ c.Response.Write("验证错误"); } } #region GET/POST public string HttpGet(string url) { StringBuilder builder = new StringBuilder(); builder.AppendLine("========================================================="); builder.AppendLine("url:" + url); string retString = string.Empty; try { string errMsg = string.Empty; HttpWebRequest wbRequest = (HttpWebRequest)WebRequest.Create(url); wbRequest.Method = "GET"; wbRequest.ContentType = "text/html;charset=UTF-8"; HttpWebResponse wbResponse = (HttpWebResponse)wbRequest.GetResponse(); using(Stream responseStream = wbResponse.GetResponseStream()) { using(StreamReader sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"))) { retString = sReader.ReadToEnd(); } } builder.AppendLine(retString); } catch(Exception ex) { builder.AppendLine("errcode:" + ex.HResult); builder.AppendLine("errmsg:" + ex.Message); } LogWeChat(builder.ToString(), "Http"); return retString; } public string HttpPost(string url, string param = "", Dictionary<string, string> header = null,
string contentType = "application/json") { StringBuilder builder = new StringBuilder(); builder.AppendLine("========================================================="); builder.AppendLine("url:" + url); builder.AppendLine("param:" + param); string data = ""; try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; request.ContentType = contentType; request.Accept = "*/*"; request.Timeout = 15000; request.AllowAutoRedirect = false; if(header != null && header.Count > 0) { foreach(var item in header) { request.Headers.Add(item.Key, item.Value); } } if(!string.IsNullOrWhiteSpace(param)) { byte[] byteData = UTF8Encoding.UTF8.GetBytes(param.ToString()); request.ContentLength = byteData.Length; using(Stream postStream = request.GetRequestStream()) { postStream.Write(byteData, 0, byteData.Length); postStream.Close(); } } using(var response = request.GetResponse()) { StreamReader reader = new StreamReader(response.GetResponseStream()); data = reader.ReadToEnd(); } builder.AppendLine(data); } catch(Exception ex) { builder.AppendLine("errcode:" + ex.HResult); builder.AppendLine("errmsg:" + ex.Message); } LogWeChat(builder.ToString(), "Http"); return data; } #endregion #region Logging public void LogWeChat(string contents, string filename) { try { if(string.IsNullOrWhiteSpace(contents)) return; string msg = string.Format(@"{0}|{1}|" + filename + "|{2}" + Environment.NewLine, DateTime.Now, "", contents); string t = "logs"; string path = PhyPath + t; string logfile = path + "/wechat_" + filename + "_" + DateTime.Now.ToString("yyyyMMdd") + ".log"; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } File.AppendAllText(logfile, msg); } catch { } } #endregion public bool IsReusable { get { return false; } } }
(3):企业微信二维码登录(WEB)效果图: