service.rb
1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
require 'cgi'
require 'open-uri'
module WxPay
module Service
GATEWAY_URL = 'https://api.mch.weixin.qq.com/pay'
INVOKE_UNIFIEDORDER_REQUIRED_FIELDS = %i(body out_trade_no total_fee spbill_create_ip notify_url trade_type)
def self.invoke_unifiedorder(params)
params = {
appid: WxPay.appid,
mch_id: WxPay.mch_id,
nonce_str: SecureRandom.uuid.tr('-', ''),
}.merge(params)
check_required_options(params, INVOKE_UNIFIEDORDER_REQUIRED_FIELDS)
r = invoke_remote("#{GATEWAY_URL}/unifiedorder", make_payload(params))
yield r if block_given?
r
end
private
def self.check_required_options(options, names)
names.each do |name|
warn("WxPay Warn: missing required option: #{name}") unless options.has_key?(name)
end
end
def self.make_payload(params)
"<xml>#{params.map { |k, v| "<#{k}>#{v}</#{k}>" }.join}<sign>#{WxPay::Sign.generate(params)}</sign></xml>"
end
def self.invoke_remote(url, payload)
r = RestClient::Request.execute(
{
method: :post,
url: url,
payload: payload,
headers: { content_type: 'application/xml' }
}.merge(WxPay.extra_rest_client_options)
)
if r
WxPay::Result.new Hash.from_xml(r)
else
nil
end
end
end
end