微信红包接口调用(rails)
2016-05-04 本文已影响199人
村南一枝花
1.先要获取openid(略,因为发红包的时候是需要用户的openid)
2.执行发红包的action
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 = "<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