一、服务器处理程序
在上篇文章中的测试号服务器配置中就需要,写处理程序的url,下面贴出的就是处理程序的代码了。当然了这个地址必须是外网才行,如果是自己搭建的一个服务器,可以使用外网穿透。它里面有免费服务器申请,再下载一个客户端,把隧道id输进去,直接enter,这样本机服务器就是一个外网的了,就是网速慢...但就测试是够用了。
1.外网穿透
下面就是关于它简单操作的一些截图,具体操作就不说了,它本身就有一个详细的文档,可以自己去看看
二、处理程序源代码
<%@ WebHandler Language="C#" Class="wxapi" %>
using System;
using System.Web;
using System.Xml;
using System.Text;
public class wxapi : IHttpHandler
{
public void ProcessRequest (HttpContext context) {
string postString = string.Empty;
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")
{
using (System.IO.Stream stream = HttpContext.Current.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = System.Text.Encoding.UTF8.GetString(postBytes);
}
if (!string.IsNullOrEmpty(postString))
{
Handle(postString);//事件处理
}
}
else
{
ConnectTest(); //微信接入的测试
}
}
/// <summary>
/// 处理信息并应答
/// </summary>
private void Handle(string postStr)
{
MessageHelper help = new MessageHelper();
string responseContent = help.ReturnMessage(postStr);
HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;
HttpContext.Current.Response.Write(responseContent);
}
/// <summary>
/// 服务链接测试
/// </summary>
private void ConnectTest()
{
string token = System.Configuration.ConfigurationManager.AppSettings["WeixinToken"];//从配置文件获取Token
if (string.IsNullOrEmpty(token))
{
MessageHelper.WriteLog(string.Format("WeixinToken 配置项没有配置!"));
}
string echoString = HttpContext.Current.Request.QueryString["echoStr"];
string signature = HttpContext.Current.Request.QueryString["signature"];
string timestamp = HttpContext.Current.Request.QueryString["timestamp"];
string nonce = HttpContext.Current.Request.QueryString["nonce"];
if (new BasicApi().CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoString))
{
HttpContext.Current.Response.Write(echoString);
HttpContext.Current.Response.End();
}
}
}
public bool IsReusable {
get {
return false;
}
}
}
三、签名代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
/// <summary>
/// BasicApi 的摘要说明
/// </summary>
public class BasicApi
{
public BasicApi()
{
//
// TODO: 在此处添加构造函数逻辑
//
}
/// <summary>
/// 验证微信签名
/// </summary>
public bool CheckSignature(string token, string signature, string timestamp, string nonce)
{
string[] ArrTmp = { token, timestamp, nonce };
Array.Sort(ArrTmp);
string tmpStr = string.Join("", ArrTmp);
tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");
tmpStr = tmpStr.ToLower();
if (tmpStr == signature)
{
return true;
}
else
{
return false;
}
}
}