原文:微信公众平台接口,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. 关系数据库的基本概念和MySQL说明

    关系数据库的基本概念 数据库: 大量的信息化解决方案的高效管理. 根据数据结构来组织.存储和管理数据的库. 数据库系统(DBS,DATABASE SYSTEM): 数据库(DB,DATABASE) + ...

  2. CodeForces 396C 树状数组 + DFS

    本主题开始看到以为段树或树状数组,但是,对于一个节点的有疑问的所有子节点的加权,这一条件被视为树的根,像 然后1号是肯定在第一层中,然后建立一个单向侧倒查,然后记录下来 其中每个节点 层,终于 两个节 ...

  3. 简单QT应用了可实现手动布局QT应用

     新建QT项目 watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdG90b3R1enVvcXVhbg==/font/5a6L5L2T/fontsize/4 ...

  4. C#枚举数和迭代器

    大道至简,始终认为简洁是一门优秀的编程语言的一个必要条件.相对来说,C#是比较简洁的,也越来越简洁.在C#中,一个关键字或者语法糖在编译器层面为我们做了很多乏味的工作,可能实现的是一个设计模式,甚至是 ...

  5. STL 清除模板容器 clear.h

    #pragma once #include "GeometricMacro.h" #include "GeometricEnum.h" #include &qu ...

  6. Cocos2d-x 3.0 Lua编程 之 响应物理引擎的Contact事件回调不运行的问题

    在较早的版本号如3.0beta使用例如以下代码的话: -- add ground local groudNode = cc.Node:create() groudNode:setPhysicsBody ...

  7. DotNetOpenAuth实践

    DotNetOpenAuth实践之搭建验证服务器 DotNetOpenAuth是OAuth2的.net版本,利用DotNetOpenAuth我们可以轻松的搭建OAuth2验证服务器,不废话,下面我们来 ...

  8. C++ - 派生类访问模板基类(templatized base class)命名

    派生类访问模板基类(templatized base class)命名 本文地址: http://blog.csdn.net/caroline_wendy/article/details/239936 ...

  9. 怎么样CSDN Blog投机和增加流量?

    所谓推测装置,以提高它们的可见性,最近比较顾得上,这样一来打字游戏.一方面,练习打字速度 .在又一个方面中,以了解诱导的理论 版权声明:本文博客原创文章,博客,未经同意,不得转载.

  10. 初探boost之progress_display库学习笔记

    progress_display 用途 progress_display能够在控制台上显示程序的运行进度,假设程序运行非常耗费时间,那么它能提供一个友好的用户界 面,不至于让用户在等待中失去耐心,甚至 ...