.NET 微信开放平台接口(接收短信、发送短信)

时间:2022-06-20 14:03:20

.NET 微信开放平台接口(接收短信、发送短信)

前两天做个项目用到了微信api功能。项目完成后经过整理封装如下微信操作类。

以下功能的实现需要开发者已有微信的公众平台账号,并且开发模式已开启、接口配置信息已设置完毕。废话不多说直接上代码。

1、公众平台账号接口配置信息中URL接口代码如下:

.NET 微信开放平台接口(接收短信、发送短信)
  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 }
.NET 微信开放平台接口(接收短信、发送短信)

注:以上接口代码实现了,接收用户短信、被动向用户推送短信(自动回复)功能。由于我自己项目本身功能的要求,我只用到的接收用户文本短信、接收用户推送事件、向用户推送文本信息的功能。所以在我封装的类库里也只有这些功能。其他功能:如接收图片消息、接收地理位置消息、接收链接消息、推送音乐消息、推送图文消息并未实现。

2、自定义菜单

接口完成后,下面就该配制自己的自定义菜单了。我这里做了一个测试页,用于配制自定义菜单。

现实现三个功能:获取凭证(access_token)、创建菜单(需access_token)、删除菜单(需access_token)

获取凭证所需的appid、appsecret在微信公众平台的接口配置信息里。

.NET 微信开放平台接口(接收短信、发送短信)

代码如下:

.NET 微信开放平台接口(接收短信、发送短信)
 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>
.NET 微信开放平台接口(接收短信、发送短信)
.NET 微信开放平台接口(接收短信、发送短信)
 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 }
.NET 微信开放平台接口(接收短信、发送短信)

说明:这里附上单文件dll。整个项目的源码已放入到CSDN中,需要的朋友可以去下,在这就不单独上传了。

WeiXin.dll

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

  还有一点就是微信的主动推送,虽然微信对外没有公开主动推送的api接口,但是经过我们的努力完全是可以实现的。我的项目里已经过验证。由于微信不提倡,所以这里也就不附上主动推送的代码了。有学习精神的朋友们,多努力努力吧。

分类: .Net