Rails

作者: ShindouHiro | 来源:发表于2015-09-17 17:02 被阅读390次
    • Rails.cache.store
    1. 写入
    Rails.cache.write('temp',Date.today,:expires_in => 60.seconds)
    - 第一个参数key
    - 第二个参数value
    - 第三个参数有效期
    
    2. 读取
    Rails.cache.read('temp')   or Rails.cache.fetch('temp')
    
    
    3. 删除
    Rails.cache.delete('temp')
    
    • Ruby的HTML/XML解析库 Nokogiri
    require 'nokogiri 
    str  = request.body.read #接收微信发过来的xml
    doc  = Nokogiri::Slop(str) #解析xml
    XML如下:
    
     <xml>
     <ToUserName><![CDATA[toUser]]></ToUserName>
     <FromUserName><![CDATA[fromUser]]></FromUserName> 
     <CreateTime>1348831860</CreateTime>
     <MsgType><![CDATA[text]]></MsgType>
     <Content><![CDATA[this is a test]]></Content>
     <MsgId>1234567890123456</MsgId>
     </xml>
    
    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
     end
    end
    
    #获取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)
          else
            access_token = Rails.cache.read("access_token")
          end
     end
    
    
    
    
    1.
    gem 'wx_pay' #Gemfile
    bundle 
    
    2.config/initializers/wx_pay.rb
    # required
    WxPay.appid = 'YOUR_APPID' 
    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
        end
      end
    
    #加密校验,确认来自微信服务器,返回echostr参数内容
    
    def valid(token,nonce,stimestamp)
      if check_weixin_legality(token,nonce,stimestamp)
         return true
       else
         reutrn false
       end
    end
    
    #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
          else
            return false
          end
        end
    
    
     #获取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)
            else
              Rails.cache.read("access_token")
            end
         end
    
    #通过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)
     end
    
    • send && eval(查询时,字段为变量时使用)
      region = Region.first
      key = "regions_NAME"
      region.send(key)  || eval('region.#{key}')
    
    • 转时间戳
    Time.now.to_datetime.strftime '%Q' #转时间戳
    DateTime.strptime "1422258129106", '%Q' #时间戳转日期
    

    相关文章

      网友评论

          本文标题:Rails

          本文链接:https://www.haomeiwen.com/subject/vwebcttx.html