rails 微信申请退款

微信申请退款

微信官方文档https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_4 请先看官方文档

接口地址 接口链接:https://api.mch.weixin.qq.com/secapi/pay/refund

官方需求 请求需要双向证书 (没有加证书的话无法访问)

请求参数(详细请看官方文档)

例子

rails 微信申请退款_第1张图片

下面是我实现的代码

url = URI.parse('https://api.mch.weixin.qq.com/secapi/pay/refund') http = Net::HTTP.new(url.host, url.port) #这是我存放在配置文件里 app_id = ENV['SmallAppID']

app_key = ENV['Smallkey'] mch_id = ENV['Smallmch_id']

https双向认证

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

http.cert = OpenSSL::X509::Certificate.new(File.read("config/apiclient_cert.pem"))

http.key = OpenSSL::PKey::RSA.new((File.read("config/apiclient_key.pem")))

http.verify_mode = OpenSSL::SSL::VERIFY_NONE

req = Net::HTTP::Post.new(url, {'Content-Type' => 'application/xml'})

nonce_str = ['a'..'z','0'..'9',*'A'..'Z'].sample(32).join #随机数

#传的xml body_xml = "#{app_id}#{mch_id}#{nonce_str}#{@last_order.payment.payment_no}#{@last_order.payment.payment_no}#{Float(@last_order.payment.total_money*100).round}#{Float(@last_order.payment.total_money*100).round}"

#签名 可在https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=20_1 先测试 sign = Digest::MD5.hexdigest("appid=#{app_id}&mch_id=#{mch_id}&nonce_str=#{nonce_str}&out_refund_no=#{@last_order.payment.payment_no}&out_trade_no=#{@last_order.payment.payment_no}&refund_fee=#{Float(@last_order.payment.total_money*100).round}&total_fee=#{Float(@last_order.payment.total_money*100).round}&key=#{app_key}")

body_xml += "#{sign.upcase}" #这里的签名需要转大写

req.body = body_xml

response = http.request(req) result = Hash.from_xml(response.body)["xml"]

结果 result ["return_code"] SUCCESS/FAIL

你可能感兴趣的:(rails 微信申请退款)