一、申请成为开发者
条件是有对外的服务器并启用提供微信服务的web服务,目前只支持80端口
登录微信公众号,填以下的信息并提交给你的服务器认证,认证成功后就成为开发者
这里的Token要与你的服务器中Token一致
服务器上发布的网站,把处理文件(.ashx)设为默认文件,并发布在80端口,
处理文件内容如下:
using System;
using System.Web;
using System.Web.Security;
using System.IO;
using System.Text;
using System.Xml;
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
string postString = string.Empty;
if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST") //成为开发者后接收微信服务器发来的信息
{
using (Stream stream = HttpContext.Current.Request.InputStream)
{
Byte[] postBytes = new Byte[stream.Length];
stream.Read(postBytes, 0, (Int32)stream.Length);
postString = Encoding.UTF8.GetString(postBytes);
}
if (!string.IsNullOrEmpty(postString))
{
Execute(postString); //处理信息
}
}
else
{
Auth(); //认证接口,一般只用一次
}
}
private void Auth()
{
string token = "donta1234567890_123";//要与提交的Token一致
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 (CheckSignature(token, signature, timestamp, nonce))
{
if (!string.IsNullOrEmpty(echoString))
{
HttpContext.Current.Response.Write(echoString);
HttpContext.Current.Response.End();
}
}
}
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;
}
}
public bool IsReusable {
get {
return false;
}
}
private void Execute(string postStr)
{
//对微信服务器发来的信息进行处理
}
}