Sha256: 3c68e0199238fd79eba2861895ed0a347d9e01f35f3c43f63e33af6dfb77c514

Contents?: true

Size: 1 KB

Versions: 1

Compression:

Stored size: 1 KB

Contents

require 'digest'
require 'json'
require 'rest-client'

module Tencent
  module Ai
    class Base
      END_POINT = 'https://api.ai.qq.com/fcgi-bin/'.freeze

      attr_accessor :app_id, :app_key

      def initialize(app_id, app_key)
        self.app_id  = app_id
        self.app_key = app_key
      end

      def request_payload(data)
        params        = {
          app_id:     app_id,
          time_stamp: Time.now.to_i.to_s,
          nonce_str:  rand(999999).to_s
        }.merge data
        params[:sign] = self.class.sign(params, app_key)
        params
      end

      def post(path, payload)
        res = RestClient.post(uri(path), payload)
        JSON.parse(res.body, object_class: OpenStruct).data
      end

      def uri(path)
        "#{END_POINT}#{path}"
      end

      def self.sign(params, app_key)
        params = Hash[params.sort]
        str    = URI.encode_www_form(params)
        str    = "#{str}&app_key=#{app_key}"
        (Digest::MD5.hexdigest str).upcase
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
tencent-ai-0.1.0 lib/tencent/ai/base.rb