Ruby on Rails微信开发3——自定义菜单的创建

根据自定义菜单创建的开发者文档


创建自定义菜单,创建步骤如下:
1、获取access_token 
  def get_access_token
    response=Typhoeus.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#{get_app_id}&secret=#{get_app_secret}")
    response_json=JSON.parse(response.options[:response_body])
    response_json["access_token"]
  end

2、将自定义菜单内容定义在yml中,例如如下格式


3、向微信服务器发送post请求,创建自定义菜单

  def create_menu
    post_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=#{get_access_token}"
    wechat_button_yml = load_yml_file "wechat_button.yml"
    post_hash = wechat_button_yml['menu']
    Typhoeus::Request.post(post_url, body: generate_post_hash(post_hash))
  end

  def load_yml_file file_name
    yml_name = Rails.root.join(Rails.root, ‘yml文件位置', file_name)
    YAML.load_file(yml_name)
  end

  #处理菜单中文问题
  def generate_post_hash post_hash
    post_hash.to_json.gsub!(/\\u([0-9a-z]{4})/) { |s| [$1.to_i(16)].pack("U") }
  end
创建结果如下:


自定义菜单事件的响应:
如上“旅行是正室”按钮对应的key为TRAVEL,对应的处理代码如下 

  #接收微信服务器信息
  def process_request
    if check_signature?(params[:signature], params[:timestamp], params[:nonce])
      if params[:xml][:MsgType] == "event" && params[:xml][:Event] == "CLICK"
        if params[:xml][:EventKey] == "TRAVEL"
          render "wechat/building", layout: false, :formats => :xml
        end
      end
    end
  end
部署到服务器之后测试效果如下:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值