1348831860
1234567890123456
type = doc.xml.MsgType.content #解析MsgType标签内的内容
微信开发Rails3.0参考
Rails3.0 XML格式自带解析,可直接接收,4.0+已经去除,可以用gem包或者Nokogiri
微信开发Post/Get
def self.sent_to_wechat(url,body)
uri = URI(url)
Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https') do |http|
request= Net::HTTP::Post.new(uri,{'Content-Type'=>'application/json'})
request.body=body
puts request.body
response=http.request request
response.body
#获取access_token
def get_access_token
if Rails.cache.read("access_token").nil?
uri = URI('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx')
res = Net::HTTP.get(uri)
result = JSON.parse(res)#parse用于从一个字符串中解析出json对象
access_token = result['access_token']
Rails.cache.write("access_token", access_token, expires_in: 5.minutes)
access_token = Rails.cache.read("access_token")
WxPay.key = 'YOUR_KEY'
WxPay.mch_id = 'YOUR_MCH_ID'
# optional - configurations for RestClient timeout,etc.
WxPay.extra_rest_client_options = {timeout: 2, open_timeout: 3}
3.创建pay方法
# required fields
params = {
body: '测试商品',
out_trade_no: 'test003',
total_fee: 1,
spbill_create_ip: request.remote_ip, #获取支付方IP
notify_url: 'http://making.dev/notify',
trade_type: 'JSAPI', # could be "JSAPI", "NATIVE" or "APP",
openid: 'OPENID' # required when trade_type is `JSAPI`
r = WxPay::Service.invoke_unifiedorder params
WechatHelper
#向微信发送json数据
def send_json(url,body)
uri = URI(url)
Net::HTTP.start(uri.host, uri.port,:use_ssl => uri.scheme == 'https') do |http|
request= Net::HTTP::Post.new(uri,{'Content-Type'=>'application/json'})
request.body=body
puts request.body
response=http.request request
puts response.body
#加密校验,确认来自微信服务器,返回echostr参数内容
def valid(token,nonce,stimestamp)
if check_weixin_legality(token,nonce,stimestamp)
return true
reutrn false
#signature 校验
#1.将token、timestamp、nonce三个参数进行字典序排序
#2.将三个参数字符串拼接成一个字符串进行sha1加密
#3.开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
def check_weixin_legality(t,n,s)
timestamp = t
nonce = n
signature = s
array = [@token,timestamp,nonce].sort
if signature == Digest::SHA1.hexdigest(array.join)
return true
return false
#获取access_token
def get_access_token(appid,secret)
if Rails.cache.read("access_token").nil?
uri = URI('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=#{appid}&secret=#{}')
res = Net::HTTP.get(uri)
result = JSON.parse(res)
Rails.cache.write("access_token",result['access_token'],expires_in: 2.hours)
Rails.cache.read("access_token")
#通过code换取网页授权access_token,网页授权access_token的同时,也获取到了openid
def code_access_token(appid,sercet,code)
uri = URI("https://api.weixin.qq.com/sns/oauth2/access_token?appid=#{appid}&secret=#{sercet}&code=#{code}&grant_type=authorization_code")
res = Net::HTTP.get(uri)
result = JSON.parse(res)
send && eval(查询时,字段为变量时使用)
region = Region.first
key = "regions_NAME"
region.send(key) || eval('region.#{key}')