企业微信应用的功能开发

时光怂恿深爱的人放手 提交于 2020-03-21 09:02:41

1.应用场景:

   企业微信中开发一个公共入口,用来外部各个子系统中的公用功能的整合;

2.业务分析:

  集团公司为了适应市场变化,拆分为四个子公司;现有集团资产管理系统,上层的决策是把系统代码直接复制为四套,分别部署在四个服务器中独立域名,独立数据库(已实施);

为我们后面维护造成了很大的问题;五月份通知全体公司要进行资产年度盘点,指定必须用移动端进行盘点;

3.架构方案:

  由于公司已有自己的企业微信平台,所以采用在企业微信工作台,新建一个盘点应用入口;开发一个H5站点作为UI(可以使用扫一扫进行扫码录入),在四套系统里开发相同的盘点接口供H5调用;

4.开发:

  主要分为 1.前端H5 界面开发; 2 .调用企业微信API; 3.调用四个系统的接口;这里主要讲下企业微信API的调用

 首先需要管理员身份进入公司的企业微信后台 https://work.weixin.qq.com/,创建好应用,并配置我们应用的 回调站点,必须是有效域名,这里需要注意的是需要把获取的 密匙txt文件WW_verify_wApslD6X0ysCCA8G.txt 放入服务器根目录下进行验证服务器

这里只说一下后台获取企业微信的配置 后台使用的是MVC Controller

  1  #region Get Post Http
  2         /// <summary>  
  3         /// 创建GET方式的HTTP请求  
  4         /// </summary>  
  5         /// <param name="url">请求的URL</param>  
  6         /// <param name="timeout">请求的超时时间</param>  
  7         /// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>  
  8         /// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>  
  9         /// <returns></returns>  
 10         public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies, string headerValue = "")
 11         {
 12             if (string.IsNullOrEmpty(url))
 13             {
 14                 throw new ArgumentNullException("url");
 15             }
 16             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
 17             request.Method = "GET";
 18             //request.UserAgent = DefaultUserAgent;
 19             request.KeepAlive = false;
 20             if (!string.IsNullOrEmpty(headerValue))
 21             {
 22                 request.Headers.Add("Authorization", headerValue);
 23             }
 24             if (!string.IsNullOrEmpty(userAgent))
 25             {
 26                 request.UserAgent = userAgent;
 27             }
 28             if (timeout.HasValue)
 29             {
 30                 request.Timeout = timeout.Value;
 31             }
 32             if (cookies != null)
 33             {
 34                 request.CookieContainer = new CookieContainer();
 35                 request.CookieContainer.Add(cookies);
 36             }
 37             return request.GetResponse() as HttpWebResponse;
 38         }
 39 
 40 
 41         /// <summary>  
 42         /// 创建POST方式的HTTP请求  
 43         /// </summary>  
 44         public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int timeout, string userAgent, CookieCollection cookies, string headerValue = "")
 45         {
 46             HttpWebRequest request = null;
 47             //如果是发送HTTPS请求  
 48             if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
 49             {
 50                 //ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
 51                 request = WebRequest.Create(url) as HttpWebRequest;
 52                 //request.ProtocolVersion = HttpVersion.Version10;
 53             }
 54             else
 55             {
 56                 request = WebRequest.Create(url) as HttpWebRequest;
 57             }
 58             request.Method = "POST";
 59             request.ContentType = "application/x-www-form-urlencoded";
 60             if (!string.IsNullOrEmpty(headerValue))
 61             {
 62                 request.Headers.Add("Authorization", headerValue);
 63             }
 64             //设置代理UserAgent和超时
 65             //request.UserAgent = userAgent;
 66             request.Timeout = timeout;
 67             request.KeepAlive = false;
 68             if (cookies != null)
 69             {
 70                 request.CookieContainer = new CookieContainer();
 71                 request.CookieContainer.Add(cookies);
 72             }
 73             //发送POST数据  
 74             if (!(parameters == null || parameters.Count == 0))
 75             {
 76                 StringBuilder buffer = new StringBuilder();
 77                 int i = 0;
 78                 foreach (string key in parameters.Keys)
 79                 {
 80                     if (i > 0)
 81                     {
 82                         buffer.AppendFormat("&{0}={1}", key, parameters[key]);
 83                     }
 84                     else
 85                     {
 86                         buffer.AppendFormat("{0}={1}", key, parameters[key]);
 87                         i++;
 88                     }
 89                 }
 90                 byte[] data = Encoding.ASCII.GetBytes(buffer.ToString());
 91                 using (Stream stream = request.GetRequestStream())
 92                 {
 93                     stream.Write(data, 0, data.Length);
 94                 }
 95             }
 96             string[] values = request.Headers.GetValues("Content-Type");
 97             return request.GetResponse() as HttpWebResponse;
 98         }
 99 
100         /// <summary>
101         /// 获取请求的数据
102         /// </summary>
103         public static string GetResponseString(HttpWebResponse webresponse)
104         {
105             using (Stream s = webresponse.GetResponseStream())
106             {
107                 StreamReader reader = new StreamReader(s, Encoding.UTF8);
108                 return reader.ReadToEnd();
109 
110             }
111         }
112 
113 
114         #endregion
http 请求工具类

首先需要获取access_token

https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=ID&corpsecret=SECRECT

https://work.weixin.qq.com/api/doc#10013/第一步:创建企业应用并获取secret

 1  //缓存网关token
 2         private string GetCacheGatewayToken()
 3         {
 4             if (HttpRuntime.Cache["GatewayToken"] == null)
 5             {
 6                 var token = CommonTools.GetGrantToken(Constants.GrantServiceUrl);
 7                 HttpRuntime.Cache.Insert("GatewayToken", token, null, System.DateTime.Now.AddHours(1), TimeSpan.Zero);
 8             }
 9             return HttpRuntime.Cache["GatewayToken"].ToString();
10         }
11          
12 
13  //public static string GetGrantToken(string url)
14        //{
15        //    var result = string.Empty;
16        //    IDictionary<string, string> postData = new Dictionary<string, string>();
17        //    postData.Add("client_id", Constants.WX_ClientID);
18        //    postData.Add("client_secret", Constants.WX_ClientSecret);
19        //    postData.Add("grant_type", Constants.WX_GrantType);
20        //    postData.Add("scope", Constants.WX_GrantScope);
21        //    //var param = string.Format("{{\"client_id\":{0},\"client_secret\":\"{1}\",\"grant_type\":\"{2}\",\"scope\":\"{3}\"}}", Constants.WX_ClientID, Constants.WX_ClientSecret, Constants.WX_GrantType, Constants.WX_GrantScope);
22        //    var strResponseInfo = RequestTool.CreatePostHttpResponse(url, postData, 60000, null, null);
23        //    if (strResponseInfo != null)
24        //        result = RequestTool.GetResponseString(strResponseInfo);
25        //    return result;
26        //}
获取并缓存token
 private static string CreateRandCode(int codeLen)
        {
            string codeSerial = "2,3,4,5,6,7,a,c,d,e,f,h,i,j,k,m,n,p,r,s,t,A,C,D,E,F,G,H,J,K,M,N,P,Q,R,S,U,V,W,X,Y,Z";
            if (codeLen == 0)
            {
                codeLen = 16;
            }
            string[] arr = codeSerial.Split(',');
            string code = "";
            int randValue = -1;
            Random rand = new Random(unchecked((int)DateTime.Now.Ticks));
            for (int i = 0; i < codeLen; i++)
            {
                randValue = rand.Next(0, arr.Length - 1);
                code += arr[randValue];
            }
            return code;
        }
生成16位随机码
System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // 当地时区
long timeStamp = (long)(DateTime.Now - startTime).TotalSeconds; // 相差秒数
System.Console.WriteLine(timeStamp);
当前时间戳

前端 获取到wx.config后就可以引入 js了 

 <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>

这时页面就可以调用企业微信api了;

后续应用中还设计到了一个网页授权;

https://work.weixin.qq.com/api/doc#10028

这里我们使用了 自己构建一个空的 form表单 获取到跳转的url后 提交,跳转的第二页,再从url中获取code ,通过code和 appid 获取登录企业微信的用户ID

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!