【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单_第1页
【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单_第2页
【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单_第3页
【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单_第4页
【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单_第5页
已阅读5页,还剩16页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

【移动应用开发技术】微信公众号开发之如何实现自动消息回复和自定义菜单

class

EventHandler

:

IHandler

{

///

<summary>

///

请求的xml

///

</summary>

private

string

RequestXml

{

get;

set;

}

///

<summary>

///

构造函数

///

</summary>

///

<param

name="requestXml"></param>

public

EventHandler(string

requestXml)

{

this.RequestXml

=

requestXml;

}

///

<summary>

///

处理请求

///

</summary>

///

<returns></returns>

public

string

HandleRequest()

{

string

response

=

string.Empty;

EventMessage

em

=

EventMessage.LoadFromXml(RequestXml);

if

(em.Event.Equals("subscribe",StringComparison.OrdinalIgnoreCase))

{

//回复欢迎消息

TextMessage

tm

=

new

TextMessage();

tm.ToUserName

=

em.FromUserName;

tm.FromUserName

=

em.ToUserName;

tm.CreateTime

=

Common.GetNowTime();

tm.Content

=

"欢迎您关注我们,我是服务小二,有事您开口~\n\n";

response

=

tm.GenerateContent();

}

return

response;

}

}关注/取消关注事件

///

<summary>

///

文本信息处理类

///

</summary>

public

class

TextHandler

:

IHandler

{

///

<summary>

///

请求的XML

///

</summary>

private

string

RequestXml

{

get;

set;

}

///

<summary>

///

构造函数

///

</summary>

///

<param

name="requestXml">请求的xml</param>

public

TextHandler(string

requestXml)

{

this.RequestXml

=

requestXml;

}

///

<summary>

///

处理请求

///

</summary>

///

<returns></returns>

public

string

HandleRequest()

{

string

response

=

string.Empty;

TextMessage

tm

=

TextMessage.LoadFromXml(RequestXml);

string

content

=

tm.Content.Trim();

if

(string.IsNullOrEmpty(content))

{

response

=

"您什么都没输入,没法帮您啊,%>_<%。";

}

else

{

if

(content.StartsWith("tq",

StringComparison.OrdinalIgnoreCase))

{

string

cityName

=

content.Substring(2).Trim();

response

=

WeatherHelper.GetWeather(cityName);

}

else

{

response

=

HandleOther(content);

}

}

tm.Content

=

response;

//进行发送者、接收者转换

string

temp

=

tm.ToUserName;

tm.ToUserName

=

tm.FromUserName;

tm.FromUserName

=

temp;

response

=

tm.GenerateContent();

return

response;

}

///

<summary>

///

处理其他消息

///

</summary>

///

<param

name="tm"></param>

///

<returns></returns>

private

string

HandleOther(string

requestContent)

{

string

response

=

string.Empty;

if

(requestContent.Contains("你好")

||

requestContent.Contains("您好"))

{

response

=

"您也好~";

}

else

if

(requestContent.Contains("傻"))

{

response

=

"我不傻!哼~

";

}

else

if

(requestContent.Contains("shit")

||

requestContent.Contains("小王八蛋"))

{

response

=

"哼,你说脏话!

";

}

else

if

(requestContent.Contains("是谁"))

{

response

=

"我是大哥大,有什么能帮您的吗?~";

}

else

if

(requestContent.Contains("再见"))

{

response

=

"再见!";

}

else

if

(requestContent.Contains("bye"))

{

response

=

"Bye!";

}

else

if

(requestContent.Contains("谢谢"))

{

response

=

"不客气!嘿嘿";

}

else

if

(requestContent

==

"h"

||

requestContent

==

"H"

||

requestContent.Contains("帮助"))

{

response

=

@"有事找警察";

}

else

{

response

=

"您说的,可惜,我没明白啊,试试其他关键字吧。";

}

return

response;

}

}/upload/information/20201208/260/13842.jpg/upload/information/20201208/260/13844.jpg接口调用请求说明

{

"button":[

{

"type":"click",

"name":"今日歌曲",

"key":"V1001_TODAY_MUSIC"

},

{

"name":"菜单",

"sub_button":[

{

"type":"view",

"name":"搜索",

"url":"/"

},

{

"type":"view",

"name":"视频",

"url":"/"

},

{

"type":"click",

"name":"赞一下我们",

"key":"V1001_GOOD"

}]

}]

}参数说明1、首先获取access_token接口调用请求说明http请求方式:

GET

/cgi-bin/menu/create?access_token=ACCESS_TOKEN参数说明返回说明{"access_token":"ACCESS_TOKEN","expires_in":7200}{"errcode":40013,"errmsg":"invalid

appid"}创建自定义菜单3、查询菜单请求说明http请求方式:GET

/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET返回说明对应创建接口,正确的Json返回结果:

{"menu":{"button":[{"type":"click","name":"今日歌曲","key":"V1001_TODAY_MUSIC","sub_button":[]},{"type":"click","name":"歌手简介","key":"V1001_TODAY_SINGER","sub_button":[]},{"name":"菜单","sub_button":[{"type":"view","name":"搜索","url":"/","sub_button":[]},{"type":"view","name":"视频","url":"/","sub_button":[]},{"type":"click","name":"赞一下我们","key":"V1001_GOOD","sub_button":[]}]}]}}4、删除菜单请求说明http请求方式:GET

/cgi-bin/menu/get?access_token=ACCESS_TOKEN返回说明对应创建接口,正确的Json返回结果:

{"errcode":0,"errmsg":"ok"}5、事件处理<xml>

<ToUserName><![CDATA[toUser]]></ToUserName>

<FromUserName><![CDATA[FromUser]]></FromUserName>

<CreateTime>123456789</CreateTime>

<MsgType><![CDATA[event]]></MsgType>

<Event><![CDATA[CLICK]]></Event>

<EventKey><![CDATA[EVENTKEY]]></EventKey>

</xml>实例讲解1、获取access_token注意:access_token有过期时间,如果过期,需要重新获取。private

static

DateTime

GetAccessToken_Time;

///

<summary>

///

过期时间为7200秒

///

</summary>

private

static

int

Expires_Period

=

7200;

///

<summary>

///

///

</summary>

private

static

string

mAccessToken;

///

<summary>

///

///

</summary>

public

static

string

AccessToken

{

get

{

//如果为空,或者过期,需要重新获取

if

(string.IsNullOrEmpty(mAccessToken)

||

HasExpired())

{

//获取

mAccessToken

=

GetAccessToken(AppID,

AppSecret);

}

return

mAccessToken;

}

}

///

<summary>

///

///

</summary>

///

<param

name="appId"></param>

///

<param

name="appSecret"></param>

///

<returns></returns>

private

static

string

GetAccessToken(string

appId,

string

appSecret)

{

string

url

=

string.Format("/cgi-bin/token?grant_type=client_credential&appid={0}&secret={1}",

appId,

appSecret);

string

result

=

HttpUtility.GetData(url);

XDocument

doc

=

XmlUtility.ParseJson(result,

"root");

XElement

root

=

doc.Root;

if

(root

!=

null)

{

XElement

access_token

=

root.Element("access_token");

if

(access_token

!=

null)

{

GetAccessToken_Time

=

DateTime.Now;

if

(root.Element("expires_in")!=null)

{

Expires_Period

=

int.Parse(root.Element("expires_in").Value);

}

return

access_token.Value;

}

else

{

GetAccessToken_Time

=

DateTime.MinValue;

}

}

return

null;

}

///

<summary>

///

判断Access_token是否过期

///

</summary>

///

<returns>bool</returns>

private

static

bool

HasExpired()

{

if

(GetAccessToken_Time

!=

null)

{

//过期时间,允许有一定的误差,一分钟。获取时间消耗

if

(DateTime.Now

>

GetAccessToken_Time.AddSeconds(Expires_Period).AddSeconds(-60))

{

return

true;

}

}

return

false;

}2、设置菜单具体菜单如下:{

"button":

[

{

"name":

"测试跳转",

"sub_button":

[

{

"type":

"view",

"name":

"搜索",

"url":

"/"

},

{

"type":

"view",

"name":

"视频",

"url":

"/"

},

{

"type":

"click",

"name":

"赞一下我们",

"key":

"BTN_GOOD"

}

]

},

{

"type":

"view",

"name":

"设备状态",

"url":

"/weixin"

},

{

"type":

"click",

"name":

"帮助",

"key":

"BTN_HELP"

}

]

}3、管理菜单实现代码如下:public

class

MenuManager

{

///

<summary>

///

菜单文件路径

///

</summary>

private

static

readonly

string

Menu_Data_Path

=

System.AppDomain.CurrentDomain.BaseDirectory

+

"/Data/menu.txt";

///

<summary>

///

获取菜单

///

</summary>

public

static

string

GetMenu()

{

string

url

=

string.Format("/{0}",

Context.AccessToken);

return

HttpUtility.GetData(url);

}

///

<summary>

///

创建菜单

///

</summary>

public

static

void

CreateMenu(string

menu)

{

string

url

=

string.Format("/{0}",

Context.AccessToken);

//string

menu

=

FileUtility.Read(Menu_Data_Path);

HttpUtility.SendHttpRequest(url,

menu);

}

///

<summary>

///

删除菜单

///

</summary>

public

static

void

DeleteMenu()

{

string

url

=

string.Format("/{0}",

Context.AccessToken);

HttpUtility.GetData(url);

}

///

<summary>

///

加载菜单

///

</summary>

///

<returns></returns>

public

static

string

LoadMenu()

{

return

FileUtility.Read(Menu_Data_Path);

}

}4、基本方法using

System;using

System.Collections.Generic;using

System.IO;using

System.Linq;using

System.Net;using

System.Text;using

System.Threading.Tasks;namespace

WeChat.Utility

{

///

<summary>

///

帮助类

///

</summary>

class

HttpUtility

{

///

<summary>

///

发送请求

///

</summary>

///

<param

name="url">Url地址</param>

///

<param

name="data">数据</param>

public

static

string

SendHttpRequest(string

url,

string

data)

{

return

SendPostHttpRequest(url,

"application/x-www-form-urlencoded",

data);

}

///

<summary>

///

///

</summary>

///

<param

name="url"></param>

///

<returns></returns>

public

static

string

GetData(string

url)

{

return

SendGetHttpRequest(url,

"application/x-www-form-urlencoded");

}

///

<summary>

///

发送请求

///

</summary>

///

<param

name="url">Url地址</param>

///

<param

name="method">方法(post或get)</param>

///

<param

name="method">数据类型</param>

///

<param

name="requestData">数据</param>

public

static

string

SendPostHttpRequest(string

url,

string

contentType,

string

requestData)

{

WebRequest

request

=

(WebRequest)HttpWebRequest.Create(url);

request.Method

=

"POST";

byte[]

postBytes

=

null;

request.ContentType

=

contentType;

postBytes

=

Encoding.UTF8.GetBytes(requestData);

request.ContentLength

=

postBytes.Length;

using

(Stream

outstream

=

request.GetRequestStream())

{

outstream.Write(postBytes,

0,

postBytes.Length);

}

string

result

=

string.Empty;

using

(WebResponse

response

=

request.GetResponse())

{

if

(response

!=

null)

{

using

(Stream

stream

=

response.GetResponseStream())

{

using

(StreamReader

reader

=

new

StreamReader(stream,

Encoding.UTF8))

{

result

=

reader.ReadToEnd();

}

}

}

}

return

result;

}

///

<summary>

///

发送请求

///

</summary>

///

<param

name="url">Url地址</param>

///

<param

name="method">方法(post或get)</param>

///

<param

name="method">数据类型</param>

///

<param

name="requestData">数据</param>

public

static

string

SendGetHttpRequest(string

url,

string

contentType)

{

WebRequest

request

=

(WebRequest)HttpWebRequest.Create(url);

request.Method

=

"GET";

request.ContentType

=

contentType;

string

result

=

string.Empty;

using

(WebResponse

response

=

request.GetResponse())

{

if

(response

!=

null)

{

using

(Stream

stream

=

response.GetResponseStream())

{

using

(StreamReader

reader

=

new

StreamReader(stream,

Encoding.UTF8))

{

result

=

reader.ReadToEnd();

}

}

}

}

return

result;

}

}

}class

XmlUtility

{

///

<summary>

///

///

</summary>

///

<param

name="json"></param>

///

<param

name="rootName"></param>

///

<returns></returns>

public

static

XDocument

ParseJson(string

json,string

rootName)

{

return

JsonConvert.DeserializeXNode(json,

rootName);

}

}5、事件处理class

EventHandler

:

IHandler

{

///

<summary>

///

请求的xml

///

</summary>

private

string

RequestXml

{

get;

set;

}

///

<summary>

///

构造函数

///

</summary>

///

<param

name="requestXml"></param>

public

EventHandler(string

requestXml)

{

this.RequestXml

=

requestXml;

}

///

<summary>

///

处理请求

///

</summary>

///

<returns></returns>

public

string

HandleRequest()

{

string

response

=

string.Empty;

EventMessage

em

=

EventMessage.LoadFromXml(RequestXml);

if

(em

!=

null)

{

switch

(em.Event.ToLower())

{

case

("subscribe"):

response

=

SubscribeEventHandler(em);

break;

case

"click":

response

=

ClickEventHandler(em);

break;

}

}

return

response;

}

///

<summary>

///

关注

///

</summary>

///

<param

name="em"></param>

///

<returns></returns>

private

string

SubscribeEventHandler(EventMessage

em)

{

//回复欢迎消息

TextMessage

tm

=

new

TextMessage();

tm.ToUserName

=

em.FromUserName;

tm.FromUserName

=

em.ToUserName;

tm.CreateTime

=

Common.GetNowTime();

tm.Content

=

"欢迎您关注我们,我是服务小二,有事您说话~\n\n";

return

tm.GenerateContent();

}

///

<summary>

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论