Giter Site home page Giter Site logo

weixin_rails_middleware's Introduction

WeixinRailsMiddleware

Gem Version

该项目使用MIT-LICENSE.

https://rubygems.org/gems/weixin_rails_middleware

已经实现消息体签名及加解密,升级与使用,详见Wiki 实现消息体签名及加解密

微信企业版本

https://github.com/lanrion/qy_wechat

https://github.com/lanrion/qy_wechat_api

使用特别说明

支持Rails版本

已经支持 Rails 3,Rails 4,Rails 5,Rails 6

参考示例

Rails 4: https://github.com/lanrion/weixin_rails_middleware_example

Rails 3: https://github.com/lanrion/weixin_rails_3

相关gem推荐使用

使用公司列表

如果您或者您的公司正在使用当中,欢迎加入此列表:

https://github.com/lanrion/weixin_rails_middleware/wiki/gem-users-list

实现功能

  • 自动验证微信请求。

  • 无需拼接XML格式,只需要使用 ReplyWeixinMessageHelper 辅助方法,即可快速回复。 使用方法: render xml: reply_text_message("Your Message: #{current_message.Content}")

  • 支持自定义token,适合一个用户使用。

  • 支持多用户token: 适合多用户注册网站,每个用户有不同的token,通过 weixin_rails_middleware.rb 配置好存储token的Model与字段名,即可。

  • 文本回复: reply_text_message(content)

  • 音乐回复: reply_music_message(music), generate_music(title, desc, music_url, hq_music_url)

  • 图文回复: reply_news_message(articles), generate_article(title, desc, pic_url, link_url)

  • 视频回复: reply_video_message(video)

  • 语音回复: reply_voice_message(voice)

  • 图片回复: reply_image_message(image)

  • 地理位置回复: 自定义需求。

  • 其他高级API实现:weixin_authorize

如何测试?

安装 ngrok,解压后跑 ngrok 4000

然后会产生以下信息:

Tunnel Status                 online
Version                       1.6/1.5
Forwarding                    http://e0ede89.ngrok.com -> 127.0.0.1:4000
Forwarding                    https://e0ede89.ngrok.com -> 127.0.0.1:4000
Web Interface                 127.0.0.1:4040
# Conn                        67
Avg Conn Time                 839.50ms

域名为 http://e0ede89.ngrok.com。 注意非付费版本域名每次会随机生成,不是固定的。

Ngrok已墙,你懂得的,ngrok 已墙,请使用localtunnel.me,使用方法:

npm install -g localtunnel

$ lt --port 8000
# your url is: https://gqgh.localtunnel.me

贡献你的代码

  1. Fork 项目
  2. 创建自己的功能分支 (git checkout -b my-new-feature).
  3. 提交你的修改 (git commit -am 'Add some feature').
  4. 推荐到远程分支 (git push origin my-new-feature).
  5. 提交PR审核.
  6. 可使用 weixin_rails_middleware_example, 来测试

Bugs 和反馈

如果你发现有出现任何的bug,请在 https://github.com/lanrion/weixin_rails_middleware/issues 记录你的bug详细信息,

或者在 Ruby China 开帖 @ruby_sky, 个人邮箱回复速度相对慢.

推荐阅读

参考致谢

在微信回复信息XML的封装方法,借鉴了 rack-weixin 实现,特此感谢!

捐赠支持

如果你觉得我的gem对你有帮助,欢迎打赏支持,:smile:

weixin_rails_middleware's People

Contributors

akirapanda avatar denleyhsiao avatar lanrion avatar mzdz avatar u0x01 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

weixin_rails_middleware's Issues

自动回复功能

def response_text_message(options={})
      message = @weixin_public_account.find_autoreply_by(@keyword)
      reply_text_message(message) if message.present?
end

我希望如果没有message, 就不回复,但是会报错 weixin_controller_decorator.rb:8:inreply' `

关注之后存储openid

因为 我要用这个 openid 与 页面登陆的用户 进行绑定(那是走网页授权绑定的吧

小视频消息

微信接收普通消息api多了一种小视频消息,现在没法正确传递到server,会出现ArgumentError (Unknown Weixin Message)

<xml>
<ToUserName><![CDATA[toUser]]></ToUserName>
<FromUserName><![CDATA[fromUser]]></FromUserName>
<CreateTime>1357290913</CreateTime>
<MsgType><![CDATA[shortvideo]]></MsgType>
<MediaId><![CDATA[media_id]]></MediaId>
<ThumbMediaId><![CDATA[thumb_media_id]]></ThumbMediaId>
<MsgId>1234567890123456</MsgId>
</xml>

refactor and fix bugs for reply_weixin_message_helper.rb

目前 “发送被动响应消息”的辅助方法,仍然有bug,已知reply_video_message 方法回复后,log并没有显示错误,同时渲染出来的XML也是正确的,但是微信客户端却收不到信息。其他暂未发现bug。

重构reply_music_message辅助方法的可选参数,微信需要的XML中,部分参数是不需要的。有部分参数也没有完善。

refactor with Adapter

现在的情况 单个公众账号与多个公众账号的处理逻辑是通过if else来处理的,重构的目标是通过适配器的方法分离两种逻辑,代码会更清晰。。

如何在weixin_controller_decorator.rb文件以外使用reply方法

需要在weixin_controller_decorator.rb以外使用reply_news_message(articles)方法,是否只需要

include WeixinRailsMiddleware::ReplyWeixinMessageHelper 即可?

目前在 一个class中 include过,但还是找不到该方法


class Notify

  include WeixinRailsMiddleware::ReplyWeixinMessageHelper

  def self.send_shop_message(articles)
    reply_news_message(articles)
  end


end

rails3.2 版本下,执行报错

rails generate weixin_rails_middleware:install
/Users/zhangqinjian/.rvm/gems/[email protected]/gems/weixin_rails_middleware-1.0.5/lib/weixin_rails_middleware/helpers/weixin_token_form_helper.rb:6:in `module:Tags': uninitialized constant ActionView::Helpers::Tags::TextField (NameError)

无法看到log

之前通过weixin_rails_middleware生成好的项目,由于出现问题然后将之前复制的一份项目放入之后,测试微信自动回复或者转客服回复都是无法看到log的

对weixin_rails_middleware Rspec测试的时候, WeixinRailsMiddleware::WeixinController#default_url_options 报错

我改了default_url_options 方法,测试是通过的(否则是@weixin_message 为 nil ,FromUserName不存在):
https://github.com/lanrion/weixin_rails_middleware/blob/master/app/controllers/weixin_rails_middleware/weixin_controller.rb#L66-L68

      def default_url_options(options={})
        #{ weichat_id: @weixin_message.FromUserName }
        { weichat_id: "o17q2s7mMOrwcFC8WT1BFgBJzAPE"}  # 我的修改
      end

routes.rb

post 'reply' =>  'myweixin#reply'

myweixin_controller_spec.rb

it "...." do
scaner = "<xml>
  <ToUserName>gh_7376db11d3a2</ToUserName>
  <FromUserName>o17q2s7mMOrwcFC8WT1BFgBJzAPE</FromUserName>
  <CreateTime>1430825981</CreateTime>
  <MsgType>event</MsgType>
  <Event>SCAN</Event>
  <EventKey>123</EventKey>
 <Ticket>gQEl8ToAAAAAAAAAASxodHRwOi8vd2VpeGluLnFxLmNvbS9xL3IwaE9VN2prb3pIYWgtdE4zMllUAAIEqKtIVQMEgDoJAA</Ticket> </xml>"
     post "reply", scaner
# 得到 response 的测试返回是正确的: 
#@weixin_message
#=> #<WeixinRailsMiddleware::Message:0x007f9a4c0e8560
# @source=
#  #<OpenStruct ToUserName="gh_7376db11d3a2", FromUserName="o17q2s7mMOrwcFC8WT1BFgBJzAPE", CreateTime="1430810714", MsgType="text", Content="Cvvc", MsgId="6145285223601690279">>

end

我不修改 default_url_options 方法,请问如何测试通过?

@lanrion

貌似 rails 5 开始不鼓励使用 before_filter 了

DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at ... .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at ... .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at ... .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at ... .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)

取消关注 报错 NoMethodError (undefined method `empty?' for true:TrueClass):

NoMethodError (undefined method `empty?' for true:TrueClass):
  rack (1.6.4) lib/rack/etag.rb:67:in `block in digest_body'
  actionpack (4.2.3) lib/action_dispatch/http/response.rb:97:in `each'
  actionpack (4.2.3) lib/action_dispatch/http/response.rb:97:in `each'
  actionpack (4.2.3) lib/action_dispatch/http/response.rb:52:in `each'
  actionpack (4.2.3) lib/action_dispatch/http/response.rb:361:in `each'
  rack (1.6.4) lib/rack/etag.rb:65:in `digest_body'
  rack (1.6.4) lib/rack/etag.rb:28:in `call'
  rack (1.6.4) lib/rack/conditionalget.rb:38:in `call'
  rack (1.6.4) lib/rack/head.rb:13:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/params_parser.rb:27:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/flash.rb:260:in `call'
  rack (1.6.4) lib/rack/session/abstract/id.rb:225:in `context'
  rack (1.6.4) lib/rack/session/abstract/id.rb:220:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/cookies.rb:560:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:29:in `block in call'
  activesupport (4.2.3) lib/active_support/callbacks.rb:84:in `run_callbacks'
  actionpack (4.2.3) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/reloader.rb:73:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/remote_ip.rb:78:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/debug_exceptions.rb:17:in `call'
  web-console (2.1.3) lib/web_console/middleware.rb:29:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.2.3) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.2.3) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `block in tagged'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:26:in `tagged'
  activesupport (4.2.3) lib/active_support/tagged_logging.rb:68:in `tagged'
  railties (4.2.3) lib/rails/rack/logger.rb:20:in `call'
  quiet_assets (1.1.0) lib/quiet_assets.rb:27:in `call_with_quiet_assets'
  actionpack (4.2.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.6.4) lib/rack/methodoverride.rb:22:in `call'
  rack (1.6.4) lib/rack/runtime.rb:18:in `call'
  activesupport (4.2.3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  actionpack (4.2.3) lib/action_dispatch/middleware/static.rb:116:in `call'
  rack (1.6.4) lib/rack/sendfile.rb:113:in `call'
  railties (4.2.3) lib/rails/engine.rb:518:in `call'
  railties (4.2.3) lib/rails/application.rb:165:in `call'
  rack (1.6.4) lib/rack/lock.rb:17:in `call'
  rack (1.6.4) lib/rack/content_length.rb:15:in `call'
  rack (1.6.4) lib/rack/handler/webrick.rb:88:in `service'
  /Users/bobo/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
  /Users/bobo/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
  /Users/bobo/.rvm/rubies/ruby-2.2.2/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'


  Rendered /Users/bobo/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_source.erb (2.7ms)
  Rendered /Users/bobo/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.5ms)
  Rendered /Users/bobo/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.8ms)
  Rendered /Users/bobo/.rvm/gems/ruby-2.2.2/gems/actionpack-4.2.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (46.3ms)

NameError: uninitialized constant

不知道为什么报这个错误,对rails还不太熟
环境ruby2.5.6
rails6.0.0
NameError: uninitialized constant Controllers::WeixinRailsMiddleware::WeixinControllerDecorator
Did you mean? Controllers::WeixinRailsMiddleware::WeixinControllerDecorator

版本 1.3.2,初始配置校验,报MissTemplate错误

WeixinRailsMiddleware::WeixinController里面的check_weixin_legality 方法

检查后发现
check_result={ :plain => "xxxx", :status => "yyy"}
render check_result # 这个会返回 missTemplate 的错误

当我把 check_result 的 "plain" key_name 改为 "text" 时
即 check_result => { :text => "xxx", :status => "yyy"}
才能正常执行

咨询:请问这是rails版本的原因吗? 我的rails版本 4.0.0

Rails5.1 貌似会取消这个 before_filter

DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)
DEPRECATION WARNING: before_filter is deprecated and will be removed in Rails 5.1. Use before_action instead. (called from <top (required)> at .../app/decorators/controllers/weixin_rails_middleware/weixin_controller_decorator.rb:5)

Filter chain halted as :check_weixin_legality rendered or redirected

Started GET "/weixin/cdfmulkvwatasbbuqj2iuuwfcdrmjk3greuibzkial0?signature=b22be15e6264f93c513a4e92371ebe1e42acc132&echostr=4388870053512687609&timestamp=1488519361&nonce=2011909813" for 127.0.0.1 at 2017-03-03 13:36:01 +0800
Processing by WeixinRailsMiddleware::WeixinController#index as /
Parameters: {"signature"=>"b22be15e6264f93c513a4e92371ebe1e42acc132", "echostr"=>"4388870053512687609", "timestamp"=>"1488519361", "nonce"=>"2011909813", "weixin_secret_key"=>"cdfmulkvwatasbbuqj2iuuwfcdrmjk3greuibzkial0"}
Merchant Load (0.5ms) SELECT merchants.* FROM merchants WHERE merchants.weixin_secret_key = 'cdfmulkvwatasbbuqj2iuuwfcdrmjk3greuibzkial0' ORDER BY merchants.id ASC LIMIT 1
Rendering text template
Rendered text template (0.0ms)
Filter chain halted as :check_weixin_legality rendered or redirected
Completed 200 OK in 3ms (Views: 0.5ms | ActiveRecord: 0.5ms)

@keyword 为空

在master下
weixin_rails_middleware (1.1.1) from git://github.com/lanrion/weixin_rails_middleware.git (at master)

怎样设置@weixin_public_account都是获取nil

2: public_account_class instance if you setup, otherwise return nil
@weixin_public_account

要这样设置呢?
weixin_rails_middleware.rb
文件里已经设置了
config.public_account_class = "Wechat"

转发多客服消息

在response_text_message方法里调用 reply_transfer_customer_service_message(@weixin_message.Content) 进行多客服消息转发,转发完之后微信公众号会自动回复一条系统消息,说“该公众号暂时无法提供服务,请稍候再试”。
貌似这个方法并没有自动结束response_text_message方法的调用。

weixin_token_string 验证失败

自动生成的config/initializers/weixin_rails_middleware.rb文件中,会有注释掉的两行:

config.weixin_token_string = '5065183751f7a25a73eca72f'
config.weixin_secret_string = 'FSaRWRZ-1NxVF4q8Wx9sK1YGV4o3yScr'

这里面的token是无法通过weixin验证的

添加微信服务器链接helper。

如果是通过token_model形式,那么实现一个实例方法;
如果是字符串,给一个helper。
同时给两种情况都提供一个公用helper。

日志中出现找不到Template的错误

ActionView::MissingTemplate (Missing template weixin_rails_middleware/weixin/reply with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :jbuilder, :coffee]}. Searched in: - "/Users/byte/RailsProject/heer-shop/app/views" 报错log如上。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.