您的位置:首页 > 编程语言 > Ruby

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

2015-01-09 11:46 405 查看
根据自定义菜单创建的开发者文档



创建自定义菜单,创建步骤如下:
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
部署到服务器之后测试效果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐