本文实例讲述了c#微信公众号与订阅号接口开发示例代码。分享给大家供大家参考,具体如下:
using system;
using system.web;
using system.io;
using system.text;
using system.web.security;
using weixin_api;
public class wxgz_api : ihttphandler
{
public void processrequest(httpcontext context)
{
context.response.contenttype = "text/plain";
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);
handle(poststring);
}
}
else
{
//微信进行的get测试(开发者认证)
wxauth();
}
}
/// <summary>
/// 处理信息并应答
/// </summary>
private void handle(string poststr)
{
messagehelp help = new messagehelp();
string responsecontent = help.returnmessage(poststr);
httpcontext.current.response.contentencoding = encoding.utf8;
httpcontext.current.response.write(responsecontent);
}
#region 微信验证
public void wxauth()
{
string token = "xxxxxxxx";
if (string.isnullorempty(token))
{
return;
}
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();
}
}
}
/// <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;
}
}
#endregion
public bool isreusable
{
get
{
return false;
}
}
}
以上就是c#开发微信公众号与订阅号接口的实例详解的详细内容。