微信お年玉インタフェース呼び出し(rails)

2933 ワード

1.まずopenidを取得する(略、お年玉を出すときはユーザーのopenidが必要だから).お年玉のアクションを実行
def confirm
    opetions = {
                 mch_billno: _record.no_num,
                 total_amount: 1 * 100, # money * 100
                 client_ip: request.remote_ip
               }
end
, 。 。 3.お年玉の出し方
def self.send_reward(openid, opetions={})
    options = {
                mch_id: ,# 
                nonce_str: ,# 
                mch_billno: , #  
                wxappid: , #  appid
                nick_name: , #  
                send_name: , #  
                re_openid: openid, #  openid
                total_amount: opetions[:total_amount], #  
                min_value: opetions[:total_amount], #  
                max_value: opetions[:total_amount], #  
                total_num: 1, #  
                wishing: , #  
                client_ip: opetions[:client_ip], # Ip 
                act_name: , #  
                remark: , #  
              }

    _sign = Weixin.md5_with_partner_key(options)# 

    xml = "
           #{ options[:mch_id] }
           #{ options[:nonce_str] }
           #{ options[:mch_billno] }
           #{ options[:wxappid] }
           #{ options[:nick_name] }
           #{ options[:send_name] }
           #{ options[:re_openid] }
           #{ options[:total_amount] }
           #{ options[:min_value] }
           #{ options[:max_value] }
           #{ options[:total_num] }
           #{ options[:wishing] }
           #{ options[:client_ip] }
           #{ options[:act_name] }
           #{ options[:remark] }
           #{ _sign }
          "

    xml = Nokogiri::XML xml

    uri = URI.parse('https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack')

    cert = File.read("#{ Rails.root }/lib/jingyou_cert/apiclient_cert.pem")

    key = File.read("#{ Rails.root }/lib/jingyou_cert/apiclient_key.pem")

    http = Net::HTTP.new(uri.host, uri.port)

    http.use_ssl = true if uri.scheme == 'https'

    http.cert = OpenSSL::X509::Certificate.new(cert)

    http.key = OpenSSL::PKey::RSA.new(key, ' ')

    http.ca_file = File.join("#{ Rails.root }/lib/jingyou_cert/rootca.pem")

    http.verify_mode = OpenSSL::SSL::VERIFY_PEER

    http.start { http.request_post(uri.path, xml.to_xml) { |res| res.body } }
end

def self.md5_with_partner_key(params)
    str = params.sort.map { |item| item.join('=') }.join('&')
    str << "&key=#{ app_secret }"
    Digest::MD5.hexdigest(str).upcase
end