Skip to content

Instantly share code, notes, and snippets.

@lanrion
Last active December 5, 2023 08:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lanrion/9479631 to your computer and use it in GitHub Desktop.
Save lanrion/9479631 to your computer and use it in GitHub Desktop.
浅析微信信息信息接收与信息回复

微信的信息接收与回复,两者是独立的。

信息接收

共同点在于:都有 ToUserName,FromUserName,CreateTime,MsgType, 这四个字段。

在信息接收方面,分为“普通消息”、“事件推送”,“语音识别结果(微信用户发送语音,微信服务器翻译成文本,只不过比语音消息多一个识别结果字段:Recognition)”。

  • 文本消息(通过“Content”关键字来获取文本内容,这点比较重要,也是使用比较多的场合)
  • 图片消息
  • 语音消息
  • 视频消息
  • 地理位置消息
  • 链接消息

“事件推送”

  • 关注/取消关注事件(Event: subscribe(订阅)、unsubscribe(取消订阅))
  • 扫描带参数二维码事件
    • 用户未关注时,进行关注后的事件推送(Event: subscribe)
    • 用户已关注时的事件推送(Event: SCAN)
  • 上报地理位置事件(Event: LOCATION)
  • 自定义菜单事件(自定义菜单有url(view类型)与keyword(click),但是会触发自定义事件的只有click类型,Event: CLICK) 除上述共同字段,同时还有一个共同的“Event”,主要用于定义这次事件属于什么样的事件类型,开发者应该根据这些Event来做业务的逻辑判断。

消息回复

因为在上述描述中已知MsgType这个字段都是必有的,因些可以根据这个字段来调用不同的方法来处理相应的微信用户发来的信息。 比如:

    def response_text_message(options={})
     reply_text_message("Your Message: #{@weixin_message.Content}")
   end

   def response_location_message(options={})
     reply_text_message("Your Location: #{@weixin_message.Location_X}, #{@weixin_message.Location_Y}")
   end

   def response_image_message(options={})
     # image message handler
   end

   def response_link_message(options={})
     # link message handler
   end

   def response_event_message(options={})
     # event messge handler
   end

   def response_voice_message(options={})
     # voice message handler
   end

   def response_video_message(options={})
     # video message handler
   end

开发者根据每条信息的特殊关键字来做业务处理,比较在“文本信息”中,会有一个“Content”,那个可以用“Content”做keyword来查询需要回复的信息。

用户回复信息中包含:http://mp.weixin.qq.com/wiki/index.php?title=发送被动响应消息

  • 回复文本消息
  • 回复图片消息
  • 回复语音消息
  • 回复视频消息
  • 回复音乐消息
  • 回复图文消息

回复信息的XML格式必须根据官方要求格式返回。其实回复的ToUserName就是接收信息中的FromUserName,而FromUserName就是接收信息的ToUserName

需要注意的地方

接收到的微信用户发过来的消息,不管是哪种类型,你都可以回复任何类型的信息。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment