module Qtpay module Service # ==== params ==== # (required) # out_user: customer uniq id # # (optional) # mobile: customer mobile number # weixin_openid: WeiXin open id # mchnt_id: merchant id # out_mchnt: developer defined merchant id # expires: token expires time in seconds (default 86400) def self.get_user_token(params, options = {}) make_request(:get, get_user_token_url(params, options)) end # ==== params ==== # (required) # total_amt: total payment amount in cents # out_sn: order serial number, must be uniq in all requests # # (optional) # mchnt_id: merchant id # out_mchnt: developer defined merchant id # token: auth token created in get_user_token # qrcode: # openid: openid when creating qrcode # expire_time: order expires time, format YYYY-mm-dd HH:MM:SS def self.create_pre_order(params, options = {}) make_request(:post, create_pre_order_url(params, options)) end GET_USER_TOKEN_REQUIRED_PARAMS = %w( out_user ) def self.get_user_token_url(params, options = {}) params = Utils.stringify_keys(params) check_required_params(params, GET_USER_TOKEN_REQUIRED_PARAMS) params = { 'caller' => 'server', 'app_code' => options[:app_code] || Qtpay.app_code, }.merge(params) request_uri('/auth/v1/token', params, options) end CREATE_PRE_ORDER_REQUIRED_PARAMS = %w( total_amt out_sn ) def self.create_pre_order_url(params, options = {}) params = Utils.stringify_keys(params) check_required_params(params, CREATE_PRE_ORDER_REQUIRED_PARAMS) params = { 'caller' => 'server', 'app_code' => options[:app_code] || Qtpay.app_code, }.merge(params) request_uri('/order/v1/pre_create', params, options) end def self.request_uri(path, params, options = {}) uri = URI("#{Qtpay.gateway_url}#{path}") uri.query = URI.encode_www_form(sign_params(params, options)) uri end def self.sign_params(params, options = {}) params.merge( 'sign' => Qtpay::Sign.generate(params, options) ) end def self.check_required_params(params, names) return if !Qtpay.debug_mode? names.each do |name| warn("Qtpay Warn: missing required option: #{name}") unless params.has_key?(name) end end def self.make_request(request_type, url) request_type = case request_type when :get :get_response when :post :post_form else request_type end if request_type == :get_response res = Net::HTTP.send(request_type, url) else res = Net::HTTP.send(request_type, url, {}) end if res.respond_to?(:body) JSON.parse(res.body) else # unknown error res end end end end