Sha256: bb9df652568687e6ecca0091914a1c07ccbdd09dfb8c81a2dfce4f7438fa76e3

Contents?: true

Size: 1.38 KB

Versions: 2

Compression:

Stored size: 1.38 KB

Contents

module Qpay
  class << self
    def sign(params, config)
      Digest::MD5.hexdigest(string_params_without_sign(params, config)).upcase
    end

    # https://qpay.qq.com/qpaywiki/showdocument.php?pid=38&docid=165
    def sign_app(params, config)
      key = "#{config.app_key}&"
      data = preprocess_params(params, keep_blank: true).sort_by { |k, _| k }.map { |x| x.join('=') }.join('&')
      digest = OpenSSL::Digest.new('sha1')
      hmac = OpenSSL::HMAC.digest(digest, key, data)
      Base64.encode64(hmac).strip
    end

    def string_params_without_sign(params, config)
      sorted_params = preprocess_params(params).sort_by { |k, _| k }
      (sorted_params << ['key', config.api_key]).map { |x| x.join('=') }.join('&')
    end

    def params_with_sign(params, config)
      params_dup = preprocess_params(params)
      params_dup.merge('sign' => Qpay.sign(params, config))
    end

    private
    def random_string
      SecureRandom.urlsafe_base64.tr('-_', '')
    end

    def preprocess_params(params, keep_blank: false)
      params_dup = params.dup
      stringified_keys_params = {}
      params_dup.each do |k, v|
        next if !keep_blank && blank?(v)
        stringified_keys_params[k.to_s] = v
      end
      stringified_keys_params.delete('key')
      stringified_keys_params
    end

    def blank?(v)
      !v || v.nil? || (v.respond_to?(:empty?) && v.empty?)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
qpay-1.6.0 lib/qpay/sign.rb
qpay-1.5.0 lib/qpay/sign.rb