原文:微信公众平台接口,asp.net实现

我为自己的笑话网开发了一个微信公众平台的接口,在这里分享给大家,希望能对朋友们有帮助,如果有什么地方写的不好,好请大家指点!

首先是要进行认证,认证的时候,只需要在Page_Load事件里面单独去执行 认证的方法就可以了,具体代码见下面的RenZheng()

认证通过之后就可以对网友的消息进行处理,可以根据微信平台推送过来的数据进行分析!我相信大家在看到这篇文章的时候,在此之前肯定对平台都有所了解了,所以,废话不多说,直接上代码! 如果有什么疑问的欢迎加群:242384606 进行讨论!

    protected void Page_Load(object sender, EventArgs e)
{
wxmessage wx = GetWxMessage();
string res = "";
//新用户添加
if (!string.IsNullOrEmpty(wx.EventName) && wx.EventName.Trim() == "subscribe")
{
string content = "";
content = "/:rose欢迎关注52冷笑话/:rose\n看笑话请直接回复“x”\n无聊时候还可以找我聊聊天哦!";
res = sendTextMessage(wx, content);
}
else
{
bool sendJoke = false;
//看笑话
List<string> xhList = new List<string>() { "x", "笑话", "笑話" };
foreach (string item in xhList)
{
if (wx.Content.Trim().ToLower().Contains(item))
{
sendJoke = true;
break;
}
}
if (sendJoke)
{
JokeDemo joke = GetJoke(wx.FromUserName);
if (string.IsNullOrEmpty(joke.Img))
{
string title = string.Format("编号{0}:{1}\n-----------------\n", joke.ID, joke.Title);
string content = joke.Content;
if (content.Length > 300)
{
content = GetSubString(content, 300) + "\n-----------------\n点击连接阅读全文:URL" }
res = sendTextMessage(wx, title + content);
}
else
{
res = sendPictureMessage(wx, joke);
}
}
//智能学聊天
if (res == "" && Regex.IsMatch(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase))
{
string content = "";
string key = Regex.Match(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase).Groups[2].Value.Trim();
int startIndex = wx.Content.IndexOf("答:") + 2;
if (startIndex < 3)
{
startIndex = wx.Content.IndexOf("答:") + 2;
}
string rep = wx.Content.Substring(startIndex, wx.Content.Length - startIndex).Trim(); // Regex.Match(wx.Content, "问(:|:)(.+?)答(:|:)(.+?)", RegexOptions.IgnoreCase).Groups[4].Value;
if ((new ChatBLL()).isExists(key))
{
content = "/::)O啦!学会啦\n不信你问问!";
}
else
{
if ((new ChatBLL()).Add(key, rep) > 0)
{
content = "好啦,这个问题我学会啦!\n你现在提问我吧!/::P";
}
else
{
content = "糟糕了,系统出了点儿小意外!\n麻烦你再试一次!";
}
}
res = sendTextMessage(wx, content);
}
//未知情况
if (res == "")
{
string content = (new ChatBLL()).GetReplyByKey(wx.Content.Trim());
if (content == "")
{
content = "/:,@-D啊哦,你在说什么?\n你可以按照下面的格式告诉我:\n问:你说的话 答:你想让我说什么\n看笑话请直接回复“x”!";
}
res = sendTextMessage(wx, content);
}
}
Response.Write(res);
} /// <summary>
/// 发送文字消息
/// </summary>
/// <param name="wx">获取的收发者信息</param>
/// <param name="content">笑话内容</param>
/// <returns></returns>
private string sendTextMessage(wxmessage wx, string content)
{
string res = string.Format("<xml><ToUserName><![CDATA[{0}]]></ToUserName><FromUserName><![CDATA[{1}]]></FromUserName><CreateTime>{2}</CreateTime><MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[{3}]]></Content> <FuncFlag>0</FuncFlag></xml> ",
wx.FromUserName, wx.ToUserName, DateTime.Now, 内容);
return res;
} /// <summary>
/// 发送图文消息
/// </summary>
/// <param name="wx">获取的收发者信息</param>
/// <param name="joke">笑话信息</param>
/// <returns></returns>
private string sendPictureMessage(wxmessage wx, JokeDemo joke)
{
StringBuilder sb = new StringBuilder();
sb.AppendFormat("<xml><ToUserName><![CDATA[{0}]]></ToUserName>", wx.FromUserName);
sb.AppendFormat("<FromUserName><![CDATA[{0}]]></FromUserName>", wx.ToUserName);
sb.AppendFormat("<CreateTime>{0}</CreateTime>", DateTime.Now);
sb.AppendFormat("<MsgType><![CDATA[news]]></MsgType><Content><![CDATA[]]></Content>");
sb.AppendFormat("<ArticleCount>1</ArticleCount>");
sb.AppendFormat("<Articles><item>");
sb.AppendFormat("<Title><![CDATA[{0}]]></Title>", 标题);
sb.AppendFormat("<Description><![CDATA[{0}]]></Description>", 说明文字);
sb.AppendFormat("<PicUrl><![CDATA[{0}]]></PicUrl>", 图片地址);
sb.AppendFormat("<Url><![CDATA[{0}]]></Url>", 连接地址);
sb.AppendFormat("</item></Articles><FuncFlag>0</FuncFlag></xml>");
return sb.ToString();
} /// <summary>
/// 获取请求过来的微信信息
/// </summary>
/// <returns></returns>
private wxmessage GetWxMessage()
{
wxmessage wx = new wxmessage();
StreamReader str = new StreamReader(Request.InputStream, System.Text.Encoding.UTF8);
XmlDocument xml = new XmlDocument();
xml.Load(str);
wx.ToUserName = xml.SelectSingleNode("xml").SelectSingleNode("ToUserName").InnerText;
wx.FromUserName = xml.SelectSingleNode("xml").SelectSingleNode("FromUserName").InnerText;
wx.MsgType = xml.SelectSingleNode("xml").SelectSingleNode("MsgType").InnerText;
if (wx.MsgType.Trim() == "text")
{
wx.Content = xml.SelectSingleNode("xml").SelectSingleNode("Content").InnerText;
}
if (wx.MsgType.Trim() == "event")
{
wx.EventName = xml.SelectSingleNode("xml").SelectSingleNode("Event").InnerText;
}
return wx;
} /// <summary>
/// 微信认证
/// </summary>
private void RenZheng()
{
#region 微信认证
//string res = "";
//string token = "52lxh";
//string signature = Request["signature"];
//string timestamp = Request["timestamp"];
//string nonce = Request["nonce"];
//string echostr = Request["echostr"];
//if (string.IsNullOrEmpty(token) || string.IsNullOrEmpty(signature) || string.IsNullOrEmpty(timestamp) || string.IsNullOrEmpty(nonce) || string.IsNullOrEmpty(echostr))
//{
// using (StreamWriter sw = new StreamWriter(Server.MapPath("wx.txt")))
// {
// sw.Write("参数错误" + Request.Url);
// }
//}
//else
//{
// ArrayList arr = new ArrayList() { token, timestamp, nonce };
// arr.Sort();
// string signature1 = GetSHA1(arr[0].ToString() + arr[1].ToString() + arr[2].ToString());
// if (signature == signature1.ToLower())
// {
// res = echostr;
// }
// else
// {
// res = "error";
// } // Response.Write(res);
//}
#endregion
} /// <summary>
/// 加密字符串
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
private string GetSHA1(string password)
{
string shh1string = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(password, "SHA1");
return shh1string;
} /// <summary>
/// 截取字符串
/// </summary>
/// <param name="content"></param>
/// <param name="length"></param>
/// <returns></returns>
private string GetSubString(string content, int length)
{
if (content.Length >= length)
{
return content.Substring(0, length);
}
else
{
return content;
}
} //自定义一个微信消息实体类
class wxmessage
{
public string FromUserName { get; set; }
public string ToUserName { get; set; }
public string MsgType { get; set; }
public string EventName { get; set; }
public string Content { get; set; }
}

52冷笑话官网:http://www.52lxh.com 随时欢迎您!

欢迎关注52冷笑话微信看笑话!

微信公众平台接口,asp.net实现的更多相关文章

  1. Java微信公众平台接口封装源码分享

    前言:      这篇博客是在三月初动手项目的时候准备写的,但是为了完成项目只好拖延时间写这篇博客,顺便也可以在项目中应用我自己总结的的一些经验.今天看来,这些方法的应用还是可以的,至少实现了我之前的 ...

  2. 微信公众平台接口API

    <?php /** * Author: helen * CreateTime: 2015/12/9 20:14 * description: 微信公众平台接口API */ class Wecha ...

  3. the5fire博客对接微信公众平台接口 | the5fire的技术博客

    the5fire博客对接微信公众平台接口 | the5fire的技术博客 the5fire博客对接微信公众平台接口

  4. C#-微信公众平台接口-上传临时素材

    最烦做微信公众平台的东西..文档说得不清不楚,又没示例代码,只能自己 慢慢搜索,弄了一晚上,基本弄出来了,把本地的图片上传到微信的临时素材那里,返回媒体ID,用于其他操作,代码如下 :(自己导入相应的 ...

  5. 微信公众平台接口调用第一步(获取access_token)

    最近公司需要开发微信公众号,闲着无聊就写写博客,希望能帮到你我 上代码: package test; import java.util.List; import java.util.ArrayList ...

  6. .net 后台以post方式调用微信公众平台接口

    public class Fresult { public int errcode { get; set; } public string errmsg { get; set; } public st ...

  7. 微信公众平台接口获取时间戳为10位,java开发需转为13位

    问题1:为什么会生成13位的时间戳,13位的时间戳和10时间戳分别是怎么来的 ? java的date默认精度是毫秒,也就是说生成的时间戳就是13位的,而像c++或者php生成的时间戳默认就是10位的, ...

  8. asp.net微信公众平台开发

    http://mp.weixin.qq.com/wiki/index.php?title=%E6%B6%88%E6%81%AF%E6%8E%A5%E5%8F%A3%E6%8C%87%E5%8D%97 ...

  9. .NET 微信开放平台接口(接收短信、发送短信)

    .NET 微信开放平台接口(接收短信.发送短信) 前两天做个项目用到了微信api功能.项目完成后经过整理封装如下微信操作类. 以下功能的实现需要开发者已有微信的公众平台账号,并且开发模式已开启.接口配 ...

随机推荐

  1. nginx随着passenger构造ruby on rails页

    1.备份nginx简介 cp /opt/nginx/html/nginx.conf /opt/nginx/html/nginx.conf.bak 2.编者nginx简介 server { listen ...

  2. ios崩溃日志1

    Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not loa ...

  3. Memcahce(MC)系列(三)Memcached它PHP转让

    由PHP转让Memcahce,首先,需要在server安装Memcache,如何安装Memcache这不是本文的重点, 大约memcache安装,谁的朋友有兴趣,请参阅这里:http://blog.c ...

  4. ubuntu突然卡住

    ctrl+alt+f1.进username和password.然后进入: killall gnome-sesseion sudo pkill X 版权声明:本文博主原创文章,博客,未经同意不得转载.

  5. windows屏幕保护程序opengl模板

    Visual Studio 2013 屏幕保护程序opengl模板 ScreenSaver.cpp #define VC_EXTRALEAN #include <windows.h> #i ...

  6. js 性能优化整理之 高频优化

    mousemove 拖拽操作 var count = 0; elem.onmousemove = function(){ count++; // 当计数器为偶数的时候不执行mousemove if( ...

  7. MPQ Storm库 源代码分析 一个

    MPQ什么? MPQ维基上说的非常明确. 简而言之,它是暴雪公司用于游戏数据打包的工具.星际争霸,魔兽争霸游戏中都有使用.该工具内含游戏资源加密和压缩等功能.         git下载地址:http ...

  8. sql语句like的使用方法

    在SQL结构化查询语言中,LIKE语句有着至关关键的数据. LIKE语句的语法格式是:select * from 表名 where 字段名 like 相应值(子串),它主要是针对字符型字段的,它的作用 ...

  9. Initialising Memories

    The file_name and memory_nameare memory_start and memory_finish are optional, it missed out they def ...

  10. Oracle实践--PL/SQL表分区的基础

    PL/SQL基础入门之表分区 PL/SQL:过程语言(Procedure  Language)和结构化语言(Structured Query Language)结合而成的编程语言.是对SQL的扩展.支 ...