微信企业号开发部分代码

之前在一个公司做过,微信企业号开发。为了方便查询将部分代码发上来。

  1  public class WXService: System.Web.Services.WebService
  2     {
  3         /// <summary>
  4         /// 发送数据的方法
  5         /// </summary>
  6         /// <param name="touser">要发往的人员名称</param>
  7         /// <param name="touserlength">要发往的人员数目</param>
  8         /// <param name="content">要发送的文件内容</param>
  9         /// <param name="machineid">发生碰撞的机械ID</param>
 10         /// <returns></returns>
 11         [WebMethod]
 12         public bool sendmessage(string tousermain, string content, string machineid,string crashid,string address)//发送数据的方法
 13         {
 14             bool success = true;
 15             //获取access token
 16             string accesstoken = JudgeAndGetAccessToken();
 17             //推送消息给用户
 18             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + accesstoken;
 19             //发送一条news消息
 20             string paraUrlCoded = "{\"touser\": \"" + tousermain + "\",\"msgtype\": \"news\",\"agentid\": \"1\",\"news\":{\"articles\":[{\"title\":\"车号为" + machineid + "的车辆发生碰撞\",\"description\":\"" + content + "\",\"url\":\""+ address + crashid + "\",\"picurl\":\""}]}}";
 21             JObject obj = JObject.Parse(post(strURL, paraUrlCoded));
 22             if (obj["errmsg"].ToString() == "ok")
 23             {
 24                 success = true;
 25             }
 26             else
 27             {
 28                 string errcode = obj["errcode"].ToString();
 29                 string fpath = Server.MapPath("");
 30                 Daily daily = new Daily();
 31                 daily.Settxtwrong(errcode,paraUrlCoded,fpath);
 32                 success = false;
 33             }
 34             return success;
 35         }
 36 
 37         /// <summary>
 38         /// 新增成员的方法
 39         /// </summary>
 40         /// <param name="id">用户id</param>
 41         /// <param name="username">用户名</param>
 42         /// <param name="mobile">手机号码</param>
 43         /// <param name="email">邮箱地址</param>
 44         /// <param name="gender">性别</param>
 45         /// <returns></returns>
 46         [WebMethod]
 47         public bool Addpeople(string id, string username, string mobile, string email, string gender)//添加人员的方法
 48         {
 49             bool success = true;
 50             //获取access token
 51             string accesstoken = JudgeAndGetAccessToken();
 52             if (gender == "")
 53             {
 54                 gender = "1";
 55             }
 56             else
 57             {
 58                 if (gender == "")
 59                 {
 60                     gender = "2";
 61                 }
 62                 else
 63                 {
 64                     gender = "";
 65                 }
 66             }
 67             //推送消息给用户
 68             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + accesstoken;
 69             //编码json字符串
 70             string paraUrlCoded = "{\"userid\": \"" + id + "\",\"name\": \"" + username + "\",\"department\": [4],\"mobile\": \"" + mobile + "\",\"gender\": \"" + gender + "\"}";
 71             JObject obj = JObject.Parse(post(strURL, paraUrlCoded));
 72             if (obj["errmsg"].ToString() == "created")
 73             {
 74                 success = true;
 75             }
 76             else
 77             {
 78                 string errcode = obj["errcode"].ToString();
 79                 string fpath = Server.MapPath("");
 80                 Daily daily = new Daily();
 81                 daily.Settxtwrong(errcode, paraUrlCoded,fpath);
 82                 success = false;
 83             }
 84             return success;
 85         }
 86 
 87         /// <summary>
 88         /// 修改人员的方法
 89         /// </summary>
 90         /// <param name="userid">用户ID</param>
 91         /// <param name="username">用户名</param>
 92         /// <param name="mobile">手机号码</param>
 93         /// <param name="email">邮箱地址</param>
 94         /// <param name="gender">性别</param>
 95         /// <returns></returns>
 96         [WebMethod]
 97         public int Changepeople(string userid, string username, string mobile, string email, string gender)//修改人员信息的方法
 98         {
 99             //获取access token
100             string accesstoken = JudgeAndGetAccessToken();
101             if (gender == "")
102             {
103                 gender = "1";
104             }
105             else
106             {
107                 if (gender == "")
108                 {
109                     gender = "2";
110                 }
111                 else
112                 {
113                     gender = "";
114                 }
115             }
116             //推送消息给用户
117             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + accesstoken;
118             //编码json字符串
119             string paraUrlCoded = "{\"userid\": \"" + userid + "\",\"name\": \"" + username + "\",\"department\": [4],\"mobile\": \"" + mobile + "\",\"gender\": \"" + gender + "\"}";
120             JObject obj = JObject.Parse(post(strURL, paraUrlCoded));
121             if (obj["errmsg"].ToString() == "updated")
122             {
123 
124             }
125             else
126             {
127                 string errcode = obj["errcode"].ToString();
128                 Daily daily = new Daily();
129                 string fpath = Server.MapPath("");
130                 daily.Settxtwrong(errcode, paraUrlCoded,fpath);
131             }
132             return Convert.ToInt32(obj["errcode"].ToString());
133         }
134 
135         /// <summary>
136         ///删除人员的方法
137         /// </summary>
138         /// <param name="id"></param>
139         /// <param name="username"></param>
140         /// <param name="mobile"></param>
141         /// <param name="email"></param>
142         /// <param name="gender"></param>
143         /// <returns></returns>
144         [WebMethod]
145         public int Removepeople(string id)//删除人员的方法
146         {
147             //获取access token
148             string accesstoken = JudgeAndGetAccessToken();
149             //推送消息给用户
150             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/user/delete?access_token=" + accesstoken + "&userid=" + id + "";
151             JObject obj = JObject.Parse(get(strURL));
152             if (obj["errmsg"].ToString() == "deleted")
153             {
154                 
155             }
156             else
157             {
158                 string errcode = obj["errcode"].ToString();
159                 string fpath = Server.MapPath("");
160                 Daily daily = new Daily();
161                 daily.Settxtwrong(errcode,fpath);
162             }
163             return Convert.ToInt32(obj["errcode"].ToString());
164         }
165 
166         /// <summary>
167         /// 邀请人员的方法
168         /// </summary>
169         /// <param name="id">人员ID</param>
170         /// <returns></returns>
171         [WebMethod]
172         public bool Invitepeople(string id)//邀请人员的方法
173         {
174             bool success = true;
175             //获取access token
176             string accesstoken = JudgeAndGetAccessToken();
177             //推送消息给用户
178             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/invite/send?access_token=" + accesstoken;
179             string json = "{\"userid\":\"" + id + "\"}";
180             JObject obj = JObject.Parse(post(strURL, json));
181             if (obj["errmsg"].ToString() == "ok")
182             {
183                 success = true;
184             }
185             else
186             {
187                 string errcode = obj["errcode"].ToString();
188                 string fpath = Server.MapPath("");
189                 Daily daily = new Daily();
190                 daily.Settxtwrong(errcode,json,fpath);
191                 success = false;
192             }
193             return success;
194         }
195 
196         /// <summary>
197         /// 通过微信接口获取accesstoken字符串
198         /// </summary>
199         /// <returns></returns>
200         private string GetAccessToken()
201         {
202             //读取程序集的配置文件
203             Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(System.Web.HttpContext.Current.Request.ApplicationPath);
204             string accesstoken = "";
205             string time = "";
206             //重新获取accesstoken
207             string CorpID = config.AppSettings.Settings["CorpID"].Value;
208             string Secret = config.AppSettings.Settings["Secret"].Value;
209             string strURL = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + CorpID + "&corpsecret=" + Secret + "";
210             string responseText = get(strURL);
211             //取出access token
212             JObject obj = JObject.Parse(responseText);
213             accesstoken = obj["access_token"].ToString();
214             time = DateTime.Now.ToString();
215             //存入到配置文件中
216             config.AppSettings.Settings.Remove("accesstoken");
217             config.AppSettings.Settings.Remove("time");
218             config.AppSettings.Settings.Add("accesstoken", accesstoken);
219             config.AppSettings.Settings.Add("time", time);
220             ConfigurationManager.RefreshSection("appSettings");//刷新
221             config.Save(ConfigurationSaveMode.Modified);
222             return accesstoken;
223         }//获取AccessToken
224 
225         /// <summary>
226         /// 判断配置文件,获取accesstoken字符串
227         /// </summary>
228         /// <returns></returns>
229         private string JudgeAndGetAccessToken()//判断并获取AccessToken
230         {
231             //先判断配置文件中的access token是否过期,以及是否存在
232             string accesstoken;
233             string time;
234             if (ConfigurationManager.AppSettings["accesstoken"] == null || ConfigurationManager.AppSettings["accesstoken"] == "" || ConfigurationManager.AppSettings["time"] == null || ConfigurationManager.AppSettings["time"] == "")
235             {
236                 //重新获取
237                 accesstoken = GetAccessToken();
238             }
239             else
240             {
241                 time = ConfigurationManager.AppSettings["time"];
242                 //判断accesstoken是否过期
243                 DateTime dt = Convert.ToDateTime(time);
244                 DateTime dt1 = DateTime.Now;
245                 TimeSpan ts = dt1 - dt;
246                 if (ts.Days == 0)
247                 {
248                     int seconds = ts.Hours * 3600 + ts.Minutes * 60 + ts.Seconds;
249                     if (seconds > 5400)
250                     {
251                         //重新获取
252                         accesstoken = GetAccessToken();
253                     }
254                     else
255                     {
256                         accesstoken = ConfigurationManager.AppSettings["accesstoken"];
257                     }
258                 }
259                 else
260                 {
261                     //重新获取
262                     accesstoken = GetAccessToken();
263                 }
264             }
265             return accesstoken;
266         }
267 
268         /// <summary>
269         /// 判断配置文件,获取accesstoken字符串
270         /// </summary>
271         /// <returns></returns>
272 
273         /// <summary>
274         /// post数据通用方法
275         /// </summary>
276         /// <param name="strURL">要post到的URL</param>
277         /// <param name="paraUrlCoded">要post过去的字符串</param>
278         /// <returns></returns>
279         private string post(string strURL, string paraUrlCoded)//post数据通用方法
280         {
281             HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
282             System.Net.HttpWebResponse response;
283             //Post请求方式
284             request.Method = "POST";
285             // 内容类型
286             request.ContentType = "application/x-www-form-urlencoded";
287             // 参数经过URL编码
288             byte[] payload;
289             //将URL编码后的字符串转化为字节
290             payload = System.Text.Encoding.UTF8.GetBytes(paraUrlCoded);
291             //设置请求的 ContentLength 
292             request.ContentLength = payload.Length;
293             //获得请 求流
294             System.IO.Stream writer = request.GetRequestStream();
295             //将请求参数写入流
296             writer.Write(payload, 0, payload.Length);
297             // 关闭请求流
298             writer.Close();
299             // 获得响应流
300             response = (System.Net.HttpWebResponse)request.GetResponse();
301             System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
302             myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
303             string responseText = myreader.ReadToEnd();
304             myreader.Close();
305             return responseText;
306         }
307 
308         /// <summary>
309         /// get数据通用方法
310         /// </summary>
311         /// <param name="strURL">拼接好的链接</param>
312         /// <returns></returns>
313         private string get(string strURL)//get数据通用方法
314         {
315             string json = "";
316             System.Net.HttpWebRequest request;
317             // 创建一个HTTP请求
318             request = (HttpWebRequest)WebRequest.Create(strURL);
319             //request.Method="get";
320             System.Net.HttpWebResponse response;
321             response = (System.Net.HttpWebResponse)request.GetResponse();
322             System.IO.StreamReader myreader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8);
323             json = myreader.ReadToEnd();
324             myreader.Close();
325             return json;
326         }
327 
328         /// <summary>
329         /// 通过code得到id的代码
330         /// </summary>
331         /// <param name="code">在querystring中取到的code字符串</param>
332         /// <returns></returns>
333         [WebMethod]
334         public string GetId(string code)//通过code得到id的代码
335         {
336             string access_token = JudgeAndGetAccessToken();
337             string Url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + access_token + "&code=" + code;
338             string json = get(Url);
339             //取出id
340             JObject obj = JObject.Parse(json);
341             string id = "";
342             try
343             {
344                 id = obj["UserId"].ToString();
345             }
346             catch
347             {
348                 //id = (string)obj["OpenId"];
349             }
350             return id;
351         }
352     }

 

posted @ 2016-05-23 16:19  huhu583  阅读(2138)  评论(0编辑  收藏  举报