微信公众平台(开发模式)

Ps:是一名菜鸟,第一次写文章,写得不好还请多多指教!!!最近刚好应公司需求研究开发微信公众平台,就记录起来!!!

现在的很多商家、媒体都有开发对应的微信公众平台,我们可以从http://mp.weixin.qq.com/网上进行注册申请。注册可以注册个人的和组织的,个人的没有自定义菜单功能,组织的可以自定义菜单,注册成功后,可以在高级功能里面看到编辑模式和开发模式,只能选择其中一种,本文主要介绍开发模式。

在进行开发模式前,得先了解微信消息的几种类型,可以登录后,查看公众平台API里面查看,然后我们可以根据消息类型创建对应的实体类,接收和发送的格式都xml格式。

运用开发模式,需要有自己的域名和服务器,进去开发模式需要填写,你需要先把你开发的程序部署在服务器上,才能填写

  

  1  const string Token = "你定义的Token";
  2       
  3         protected void Page_Load(object sender, EventArgs e)
  4         {
  5             if (Request.HttpMethod.ToLower() == "post")
  6             {
  7                 //WriteLog(Request.ContentLength.ToString());
  8                 System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
  9                 byte[] b = new byte[s.Length];
 10                 s.Read(b, 0, (int)s.Length);
 11                 string postStr = System.Text.Encoding.UTF8.GetString(b);
 12                 if (!string.IsNullOrEmpty(postStr))
 13                 {
 14 
 15                     WriteLog(postStr);
 16                     DealPost(postStr);
 17                 }
 18 
 19             }
 20             else
 21             {
 22                 Valid();
 23                 //string get = Request["echostr"];
 24                 //Response.Write(get);
 25                
 26             }
 27         }
 28      
 29         
 30         private bool CheckSignature()
 31         {
 32             string signature = Request.QueryString["signature"].ToString();
 33             string timestamp = Request.QueryString["timestamp"].ToString();
 34             string nonce = Request.QueryString["nonce"].ToString();
 35             string[] ArrTmp = { Token, timestamp, nonce };
 36             Array.Sort(ArrTmp);     //字典排序
 37             string tmpStr = string.Join("", ArrTmp);
 38             tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
 39             tmpStr = tmpStr.ToLower();
 40             if (tmpStr == signature)
 41             {
 42                 return true;
 43             }
 44             else
 45             {
 46                 return false;
 47             }
 48         }
 49 
 50         private void Valid()
 51         {
 52             string echoStr = Request.QueryString["echoStr"]??"test";
 53             if (CheckSignature())
 54             {
 55                 if (!string.IsNullOrEmpty(echoStr))
 56                 {
 57                     Response.Write(echoStr);
 58                    // Response.End();
 59                 }
 60             }
 61         }
 62 
 63         private void DealPost(string postStr)
 64         {
 65            
 66             csWXLogic wx = new csWXLogic();
 67             DealXml dx = new DealXml(postStr);
 68             string res = "";
 69            
 70             int mdatetime = ResponseWeixin.ConvertDateTimeInt(DateTime.Now);               
 71             if (dx.MsgType.Equals("text"))
 72             {
 73                 //处理文本消息
 74                TextType tt = dx.NewTextType(dx.Xn);
 75                 res = wx.GlobalExecute(tt.Content + "#" + tt.FromUserName);
 76               
 77                 Response.ContentEncoding = Encoding.UTF8;
 78                 Response.Write(ResponseWeixin.ResponseText(res, tt.FromUserName, tt.ToUserName, mdatetime.ToString()));
 79             }
 80             if (dx.MsgType.Equals("event"))
 81             {
 82                 EventType et = dx.NewEnentType(dx.Xn);
 83                 switch (et.Event)
 84                 {
 85                     case "subscribe":
 86                         res = wx.GlobalExecute("000");break;
 87                     case "CLICK":
 88                        res = wx.GlobalExecute(et.EventKey + "#" + et.FromUserName); break;
 89                        
 90                 }
 91                 
 92                    
 93                 
 94                 Response.ContentEncoding = Encoding.UTF8;
 95                 Response.Write(ResponseWeixin.ResponseText(res, et.FromUserName, et.ToUserName, mdatetime.ToString()));
 96             }
 97             if (dx.MsgType.Equals("location"))
 98             {
 99                 LocationType lt = dx.NewLocationType(dx.Xn);
100                 res = wx.GlobalExecute(lt.Location_X + "" + lt.Location_Y + "#" + lt.FromUserName);
101                 Response.ContentEncoding = Encoding.UTF8;
102                 Response.Write(ResponseWeixin.ResponseText(res, lt.FromUserName, lt.ToUserName, mdatetime.ToString()));
103             } 
104            
105         }
View Code

ps:在页面加载时候判断是post还是get请求。如果get请求经行验证,接口说明文档有说需要获取signature、timestamp、nonce参数然后排序加密,进行判断返回echoStr,也可以不判定直接返回echoStr。如果是post请求就是处理用户发送的消息,我们判断消息类型,然后创建对应的消息实体,然后根据需要开发自己的业务逻辑。的地址:域名/该代码文件。


接下来是自定义菜单。在设置下,可以申请自定义菜单,身体通过后会得到固定的https://api.weixin.qq.com/cgi-bin/menu/create?access_token=XXX地址进行创建菜单,create、get、delete对应创建、查询、删除菜单,这些操作每天有次数限制。菜单只需本地自己执行一次,不用放在用户请求里面。

  

 1  public string getAccess_token()
 2         {
 3             string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
 4             string result = "";
 5             CookieContainer cc = new CookieContainer();
 6             HttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);
 7             http.CookieContainer = cc;
 8             http.Method = "GET"; //必须是get方式请求 
 9             http.ContentType = "application/x-www-form-urlencoded";
10             http.Timeout = 30000;
11             HttpWebResponse webResponse = (HttpWebResponse)http.GetResponse();
12             using (Stream streamReceive = webResponse.GetResponseStream())
13             {
14                 using (StreamReader sr = new StreamReader(streamReceive, Encoding.UTF8))
15                 {
16                     result = sr.ReadToEnd();
17                 }
18             }
19 
20             var accessToken = Json.Decode(result);
21             var a = accessToken.access_token;
22             return a;
23         }
24     
25         public void createMenu()
26         {
27             string result = string.Empty;
28             string accessToken = getAccess_token();
29             string user_define_menu = "{\"button\":[{\"type\":\"click\",\"name\":\"停车场信息\",\"key\":\"002\"},{\"name\":\"ECT注册\",\"sub_button\":[{\"type\":\"click\",\"name\":\"用户注册\",\"key\":\"001\"},{\"type\":\"click\",\"name\":\"取消注册\",\"key\":\"005\"}]},{\"name\":\"ECT查询\",\"sub_button\":[{\"type\":\"click\",\"name\":\"余额查询\",\"key\":\"003\"},{\"type\":\"click\",\"name\":\"消费明细\",\"key\":\"004\"}]}]}";
30             byte[] datamenu = Encoding.Default.GetBytes(user_define_menu);
31             string action = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + accessToken;
32             HttpWebRequest http = (HttpWebRequest)WebRequest.Create(action);
33             CookieContainer cc = new CookieContainer();
34             http.CookieContainer = cc;
35             http.Method = "POST"; //必须是get方式请求 
36             http.ContentType = "application/x-www-form-urlencoded";
37             http.Timeout = 30000;
38             http.ContentLength = datamenu.Length;
39 
40             using (Stream streamReceive = http.GetRequestStream())
41             {
42                 streamReceive.Write(datamenu, 0, datamenu.Length);
43 
44             }
45             HttpWebResponse webResponse = (HttpWebResponse)http.GetResponse();
46             using (StreamReader streamReceive = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
47             {
48 
49                 result = streamReceive.ReadToEnd();
50                 webResponse.Close();
51 
52             }
53         
54             
55         }
View Code

 

 

 

posted @ 2013-10-08 20:16  天朝程序猿  阅读(265)  评论(2)    收藏  举报