.NET 微信開放平臺接口(接收短信、發送短信)

前兩天作個項目用到了微信api功能。項目完成後通過整理封裝以下微信操做類。php

如下功能的實現須要開發者已有微信的公衆平臺帳號,而且開發模式已開啓、接口配置信息已設置完畢。廢話很少說直接上代碼。html

 

一、公衆平臺帳號接口配置信息中URL接口代碼以下:web

  1 <%@ WebHandler Language="C#" Class="WeixinInterface" %>
  2 
  3 using System;
  4 using System.Web;
  5 
  6 using WeiXin;
  7 using System.Xml;
  8 public class WeixinInterface : IHttpHandler
  9 {
 10 
 11     HttpContext context;
 12     public void ProcessRequest(HttpContext context)
 13     {
 14         this.context = context;        
 15 
 16         //WriteLog("[Begin:" + DateTime.Now.ToString() + "]");  //開始接收信息(輸出日誌,供調試使用)
 17 
 18         /*
 19          * 第四個參數"checkToken"爲true時,此實例方法用於驗證微信公衆平臺配置的URL、Token。
 20          * 第四個參數"checkToken"爲false時,此實例方法用於接收用戶信息、回覆用戶信息。
 21          * 第四個參數"checkToken"爲true時,此實例代碼最好不要包含於try catch語句中
 22          * 第三個參數從配置文件中讀取,其值爲微信公衆平臺接口配置信息中的「Token」
 23          */
 24         //第一步:實例化微信封裝類 
 25         WeiXinMessage weixin = new WeiXinMessage(context.Request, context.Response, System.Configuration.ConfigurationManager.AppSettings["Token"].ToString(), false);
 26         //WriteLog("[ReceiveStr:" + reply.ReceiveStr + "]");    //輸出接收字符串(輸出日誌,供調試使用)
 27 
 28         //第二步:獲取用戶發送消息類型 
 29         string msgType = weixin.GetMsgType();
 30         
 31         
 32         //第三步:根據接收到不一樣的消息類型,執行不一樣的業務邏輯
 33         if (msgType == "text")
 34         {
 35             
 36             string msg = weixin.GetMsgText();//獲取用戶發送文本信息
 37             //WriteLog("[UserMsg:" + msg + "]");  //輸出用戶發送的文本信息(輸出日誌,供調試使用)
 38             string answer = "";
 39             try
 40             {
 41                 //根據用戶發送的信息,自動匹配自定義的「自動回覆」
 42                 //answer = HEBCCC.SSSS.BLL.W_ZDHFBLL.GetAnswer(answer);
 43             }
 44             catch (Exception ex)
 45             {
 46                 WriteLog(DateTime.Now.ToString() + "[error:" + ex.Message + "]");
 47             }
 48             //WriteLog("[answer:" + answer + "]");
 49             if (!string.IsNullOrEmpty(answer))
 50             {
 51                 //匹配出自動回覆內容,推送給用戶文本信息
 52                 weixin.SendMsgText(answer);//此代碼不能包含於try catch語句中,不然報錯。
 53             }
 54             else//匹配不出自動回覆內容時,從系統xml配置文件中讀取默認文本內容推送給用戶
 55             {
 56                 XmlNode autoReplyXmlNode = null;
 57                 try
 58                 {
 59                     string path = context.Server.MapPath("~/xml/sys.xml");
 60                     XmlDocument xmldom = new XmlDocument();
 61                     xmldom.Load(path);//加載xml文件
 62                     XmlNode xmlNode = xmldom.SelectSingleNode("root");//讀取第一個節點
 63                     autoReplyXmlNode = xmlNode.SelectSingleNode("autoReply");//讀取第一個節點
 64                 }
 65                 catch (Exception ex)
 66                 {
 67                     WriteLog(DateTime.Now.ToString() + "[error2:" + ex.Message + "]");
 68                 }
 69                 if (autoReplyXmlNode != null && !string.IsNullOrEmpty(autoReplyXmlNode.InnerText))
 70                     weixin.SendMsgText(autoReplyXmlNode.InnerText);//此代碼不能包含於try catch語句中,不然報錯。
 71 
 72             }
 73         }
 74         else if (msgType == "event")
 75         {
 76             //獲取事件類型(Event)、事件Key值(EventKey)
 77             string[] array = weixin.GetEventType();
 78             if (array[0] == "click" && array[1].ToLower() == "c_khgh")
 79             {
 80                 weixin.SendMsgText("抱歉,此功能暫未開通【河北華網計算機技術有限公司】");
 81             }
 82         } 
 83     }
 84 
 85     /// <summary>
 86     /// 記錄日誌
 87     /// </summary>
 88     /// <param name="strMemo">內容</param>
 89     private void WriteLog(string strMemo)
 90     {
 91         string logPath=System.Configuration.ConfigurationManager.AppSettings["SysLog"].ToString();
 92         string filename = context.Server.MapPath(logPath + "\\WeiXin.txt");
 93         if (!System.IO.Directory.Exists(context.Server.MapPath(logPath)))
 94             System.IO.Directory.CreateDirectory(context.Server.MapPath(logPath));
 95         System.IO.StreamWriter sr =null;
 96         try
 97         {
 98             if (!System.IO.File.Exists(filename))
 99             {
100                 sr =  System.IO.File.CreateText(filename);
101             }
102             else
103             {
104                 sr = System.IO.File.AppendText(filename);
105             }
106             sr.WriteLine(strMemo);
107         }
108         catch
109         {
110         }
111         finally
112         {
113             if (sr != null)
114                 sr.Close();
115         }
116     }
117 
118     public bool IsReusable
119     {
120         get
121         {
122             return false;
123         }
124     }
125 
126 }

 

注:以上接口代碼實現了,接收用戶短信、被動向用戶推送短信(自動回覆)功能。因爲我本身項目自己功能的要求,我只用到的接收用戶文本短信、接收用戶推送事件、向用戶推送文本信息的功能。因此在我封裝的類庫裏也只有這些功能。其餘功能:如接收圖片消息、接收地理位置消息、接收連接消息、推送音樂消息、推送圖文消息並未實現。api

 

二、自定義菜單微信

接口完成後,下面就該配製本身的自定義菜單了。我這裏作了一個測試頁,用於配製自定義菜單。app

現實現三個功能:獲取憑證(access_token)、建立菜單(需access_token)、刪除菜單(需access_token)
微信公衆平臺

獲取憑證所需的appid、appsecret在微信公衆平臺的接口配置信息裏。dom

 

 

代碼以下:學習

 

 1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 2 
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 4 <html xmlns="http://www.w3.org/1999/xhtml">
 5 <head runat="server">
 6     <title></title>
 7 </head>
 8 <body>
 9     <form id="form1" runat="server">
10     <div>
11         <table>
12             <tr>
13                 <td align="right">
14                     appid:
15                 </td>
16                 <td>
17                     <asp:TextBox ID="_txtAppid" runat="server"></asp:TextBox>
18                 </td>
19             </tr>
20             <tr>
21                 <td align="right">
22                     appsecret:
23                 </td>
24                 <td>
25                     <asp:TextBox ID="_txtAppsecret" runat="server"></asp:TextBox>
26                 </td>
27             </tr>
28             <tr>
29                 <td colspan="2" align="center">
30                     <asp:Button ID="_btnAccessToken" runat="server" Text="獲取access_token" OnClick="_btnAccessToken_Click" />
31                 </td>
32             </tr>
33         </table>
34         <asp:Label ID="_lblMsg" runat="server" Text=""></asp:Label>
35         <br />
36         <br />
37         <br />
38         <br />
39         <br />
40         <table>
41             <tr>
42                 <td align="right">access_token:</td>
43                 <td>
44                     <asp:TextBox ID="_txtacetoken" TextMode="MultiLine" Rows="5" Columns="40" runat="server"></asp:TextBox>
45                 </td>
46             </tr>
47 
48             <tr>
49                 <td align="right">自定義菜單內容:</td>
50                 <td>
51                     <asp:TextBox ID="_txtMenu" TextMode="MultiLine" Rows="10" Columns="40" runat="server"></asp:TextBox>
52                 </td>
53             </tr>
54             <tr>
55                 <td colspan="2" align="center">
56                     <asp:Button ID="_btnSetMenu" runat="server" Text="設置菜單" 
57                         onclick="_btnSetMenu_Click"  />
58                     <asp:Button ID="_btnDelMenu" runat="server" Text="刪除自定義菜單" 
59                         onclick="_btnDelMenu_Click"  />
60                 </td>
61             </tr>
62         </table>
63         <asp:Label ID="_lblMsg2" runat="server" Text=""></asp:Label>        
64     </div>
65     </form>
66 </body>
67 </html>

 

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 
 8 using System.Net;
 9 using System.IO;
10 using System.Text;
11 public partial class _Default : System.Web.UI.Page
12 {
13     protected void Page_Load(object sender, EventArgs e)
14     {
15 
16     }
17 
18     //獲取access_token
19     protected void _btnAccessToken_Click(object sender, EventArgs e)
20     {
21         if (string.IsNullOrEmpty(_txtAppid.Text.Trim()))
22         {
23             ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('請輸入appid');", true);
24             return;
25         }
26         if (string.IsNullOrEmpty(_txtAppsecret.Text.Trim()))
27         {
28             ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('請輸入appsecret');", true);
29             return;
30         }
31         string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + _txtAppid.Text.Trim() + "&secret=" + _txtAppsecret.Text.Trim();
32         HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
33         webRequest.Method = "get";
34         HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
35         StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
36         _lblMsg.Text = "返回結果:" + sr.ReadToEnd();
37 
38     }
39 
40 
41 
42 
43     //設置菜單
44     protected void _btnSetMenu_Click(object sender, EventArgs e)
45     {
46         if (string.IsNullOrEmpty(_txtacetoken.Text.Trim()))
47         {
48             ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('請輸入access_token');", true);
49             return;
50         }
51         if (string.IsNullOrEmpty(_txtMenu.Text.Trim()))
52         {
53             ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('請輸入自定義菜單內容');", true);
54             return;
55         }
56 
57         string padata = _txtMenu.Text.Trim();
58         string url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" + _txtacetoken.Text.Trim();//請求的URL
59         try
60         {
61             byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 轉化
62             HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
63             webRequest.Method = "POST";
64             webRequest.ContentLength = byteArray.Length;
65        
66             Stream newStream = webRequest.GetRequestStream();
67             newStream.Write(byteArray, 0, byteArray.Length); //寫入參數
68             newStream.Close();
69             HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
70             StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
71             _lblMsg2.Text = "返回結果:" + sr.ReadToEnd();
72         }
73         catch (Exception ex)
74         {
75             throw ex;
76         }
77     }
78 
79     //刪除菜單
80     protected void _btnDelMenu_Click(object sender, EventArgs e)
81     {
82         if (string.IsNullOrEmpty(_txtacetoken.Text.Trim()))
83         {
84             ScriptManager.RegisterStartupScript(this, GetType(), "", "alert('請輸入access_token');", true);
85             return;
86         }
87         string url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" + _txtacetoken.Text.Trim();
88 
89         HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
90         webRequest.Method = "get";
91         HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
92         StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.Default);
93         _lblMsg2.Text = "返回結果:" + sr.ReadToEnd();
94     }
95 
96 }

 

 

說明:這裏附上單文件dll。整個項目的源碼已放入到CSDN中,須要的朋友能夠去下,在這就不單獨上傳了。 測試

    WeiXin.dll

 

  CSDN鏈接:http://download.csdn.net/detail/xujie825/6329293

 

  還有一點就是微信的主動推送,雖然微信對外沒有公開主動推送的api接口,可是通過咱們的努力徹底是能夠實現的。個人項目裏已通過驗證。因爲微信不提倡,因此這裏也就不附上主動推送的代碼了。有學習精神的朋友們,多努力努力吧。

相關文章
相關標籤/搜索