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

本文介绍如何通过获取access_token并定义菜单内容来创建微信公众号的自定义菜单,并展示了如何响应菜单点击事件。


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


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

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


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

  1. def create_menu  
  2.   post_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=#{get_access_token}"  
  3.   wechat_button_yml = load_yml_file "wechat_button.yml"  
  4.   post_hash = wechat_button_yml['menu']  
  5.   Typhoeus::Request.post(post_url, body: generate_post_hash(post_hash))  
  6. end  
  7.   
  8. def load_yml_file file_name  
  9.   yml_name = Rails.root.join(Rails.root, ‘yml文件位置', file_name)  
  10.   YAML.load_file(yml_name)  
  11. end  
  12.   
  13. #处理菜单中文问题  
  14. def generate_post_hash post_hash  
  15.   post_hash.to_json.gsub!(/\\u([0-9a-z]{4})/) { |s| [$1.to_i(16)].pack("U") }  
  16. end  
创建结果如下:


自定义菜单事件的响应:
如上“旅行是正室”按钮对应的key为TRAVEL,对应的处理代码如下 
  1. #接收微信服务器信息  
  2. def process_request  
  3.   if check_signature?(params[:signature], params[:timestamp], params[:nonce])  
  4.     if params[:xml][:MsgType] == "event" && params[:xml][:Event] == "CLICK"  
  5.       if params[:xml][:EventKey] == "TRAVEL"  
  6.         render "wechat/building", layout: false:formats => :xml  
  7.       end  
  8.     end  
  9.   end  
  10. end  
部署到服务器之后测试效果如下:
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值