欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#微信公众号与订阅号接口开发示例代码

程序员文章站 2023-11-18 12:03:46
本文实例讲述了c#微信公众号与订阅号接口开发示例代码。分享给大家供大家参考,具体如下: using system; using system.web; usi...

本文实例讲述了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#相关内容感兴趣的读者可查看本站专题:《c#常见控件用法教程》、《winform控件用法总结》、《c#数据结构与算法教程》、《c#面向对象程序设计入门教程》及《c#程序设计之线程使用技巧总结

希望本文所述对大家c#程序设计有所帮助。