最近在玩微信公共平台的开发,分享一下心得
1、封装细节,客户端只关注业务逻辑。
这个是客户端代码,客户端只需要根据请求消息体进行处理,并返回响应消息即可。
这里关于token,还可以进行一层封装,这样就不用每次都要实现Token属性了;或者直接写入配置文件。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace wx
{
public class QuestionAnswer:MpWeixinService
{
/// <summary>
/// 处理请求消息,并返回响应消息
/// </summary>
/// <param name="msg">请求消息</param>
/// <returns>响应消息</returns>
public override WxResponseMsg ProcessMessage(WxRequestMsg msg)
{
WxTextResponseMsg resMsg = new WxTextResponseMsg(
msg.FromUserName, msg.ToUserName, System.DateTime.Now.Ticks, "Test");
return resMsg;
}
/// <summary>
/// 返回token
/// </summary>
public override string Token
{
get { return "mytoken"; }
}
}
}
2、结合数据库和反射,完成业务逻辑的配置和自动加载,无须停止应用。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Xml;
using System.IO;
using System.Text;
using log4net;
using System.Data;
using System.Data.SqlClient;
using System.Reflection;
namespace wx
{
/// <summary>
/// 根据路由表中的路由消息,将指定的消息交给指定的处理程序进行处理,并返回相应的处理结果
/// </summary>
public class WxRoute : MpWeixinService
{
private DataTable routeTable = new DataTable();
public override WxResponseMsg ProcessMessage(WxRequestMsg msg)
{
WxResponseMsg resMsg = null;
string appName = SearchRouteAppName(msg);
if (!string.IsNullOrEmpty(appName))
{
Type t = Type.GetType(appName);
object o = Activator.CreateInstance(t);
resMsg = (WxResponseMsg)t.GetMethod("ProcessMessage").Invoke(o, new WxRequestMsg[] { msg });
}
return resMsg;
}
public WxRoute()
{
LoadRouteTable();
}
private void LoadRouteTable()
{
//加载路由表
string strSelect = "SELECT route_id, msgtype, msgtext, appurl, remark " +
"FROM tbwx_Route";
SqlConnection conn = Common.GetConnection();
SqlCommand cmd = new SqlCommand(strSelect, conn);
conn.Open();
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(routeTable);
ada.Dispose();
conn.Close();
}
private string SearchRouteAppName(WxRequestMsg msg) //查找路由处理appname
{
string appName = "";
foreach (DataRow row in routeTable.Rows)
{
switch (msg.MsgType)
{
case MsgTypes.Text:
{
if (row["msgtype"].ToString() == "text" &&
row["msgtext"].ToString() == ((WxTextRequestMsg)msg).Content.ToLower())
{
appName = row["appname"].ToString();
}
}
break;
default:
break;
}
}
return appName;
}
public override string Token
{
get
{
return "sjfxsoft";
}
}
}
}
路由表结构
create table dbo.tbwx_Route (
route_id bigint not null,
msgtype varchar(50) null,
msgtext varchar(50) null,
appname varchar(500) not null,
remark varchar(255) collate Chinese_PRC_CI_AS null,
constraint PK_tbWxRoute primary key (route_id)
on "PRIMARY"
)