微信公众号接收消息和发送消息开发流程和注意事项
1.首先进行基本配置:
登录 微信公众平台 –》 开发 –》 基本配置,登录网址 https://mp.weixin.qq.com,如下图:
注意:在 http://www.xxx.com/wxmsg 页面输出 Response.Write(Request[“echostr”]),提交之后方可通过验证,通过验证之后再修改该页面为正式的业务逻辑。如果没有输出 Request[“echostr”],将会出现“token验证失败”错误。
2. 接收消息,消息格式是xml,消息接口说明 http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html ,格式如:
<xml> <ToUserName><![CDATA[toUser]]></ToUserName> <FromUserName><![CDATA[fromUser]]></FromUserName> <CreateTime>1348831860</CreateTime> <MsgType><![CDATA[text]]></MsgType> <Content><![CDATA[this is a test]]></Content> <MsgId>1234567890123456</MsgId> </xml>
注意:常规的Request是获取不到消息的,我在网上查到的方式如下:
public string PostInput(System.Web.HttpRequest request) { try { return PostInput(request, Encoding.UTF8); } catch (Exception ex) { throw ex; } } public string PostInput(System.Web.HttpRequest request, Encoding encoding) { StringBuilder builder = new StringBuilder(); try { using (System.IO.Stream s = request.InputStream) { int count = 0; byte[] buffer = new byte[1024]; while ((count = s.Read(buffer, 0, 1024)) > 0) { builder.Append(encoding.GetString(buffer, 0, count)); } s.Flush(); s.Close(); s.Dispose(); } return builder.ToString(); } catch (Exception ex) { throw ex; } }
3. 返回消息,格式也是xml,说明 http://mp.weixin.qq.com/wiki/14/89b871b5466b19b3efa4ada8e577d45e.html,直接 Response.Write() 输出即可。
注意:输出之前先要Response.Clear(),否则可能由于缓存原因不输出内容.