1.先要獲取openid(略沃测,因為發(fā)紅包的時候是需要用戶的openid)
2.執(zhí)行發(fā)紅包的action
def confirm
opetions = {
mch_billno: _record.no_num,
total_amount: 1 * 100, # money * 100
client_ip: request.remote_ip
}
end
因為在微信接口中的金額都是用分計算的,而紅包最低是一元發(fā)送在辆。所以測試的時候都搞一元好了工闺。
3.發(fā)紅包的方法
def self.send_reward(openid, opetions={})
options = {
mch_id: ,#商戶編號
nonce_str: ,#隨機字符串
mch_billno: , # 商戶訂單號
wxappid: , # 公眾賬號appid
nick_name: , # 提供方名稱
send_name: , # 發(fā)送方名稱
re_openid: openid, # 用戶openid
total_amount: opetions[:total_amount], # 付款金額
min_value: opetions[:total_amount], # 最小紅包金額
max_value: opetions[:total_amount], # 最大紅包金額
total_num: 1, # 紅包發(fā)放總?cè)藬?shù)
wishing: , # 紅包祝福語
client_ip: opetions[:client_ip], # Ip地址
act_name: , # 活動名稱
remark: , # 備注
}
_sign = Weixin.md5_with_partner_key(options)#簽名
xml = "<xml>
<mch_id>#{ options[:mch_id] }</mch_id>
<nonce_str>#{ options[:nonce_str] }</nonce_str>
<mch_billno>#{ options[:mch_billno] }</mch_billno>
<wxappid>#{ options[:wxappid] }</wxappid>
<nick_name>#{ options[:nick_name] }</nick_name>
<send_name>#{ options[:send_name] }</send_name>
<re_openid>#{ options[:re_openid] }</re_openid>
<total_amount>#{ options[:total_amount] }</total_amount>
<min_value>#{ options[:min_value] }</min_value>
<max_value>#{ options[:max_value] }</max_value>
<total_num>#{ options[:total_num] }</total_num>
<wishing>#{ options[:wishing] }</wishing>
<client_ip>#{ options[:client_ip] }</client_ip>
<act_name>#{ options[:act_name] }</act_name>
<remark>#{ options[:remark] }</remark>
<sign>#{ _sign }</sign>
</xml>"
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