module AliyunSms

Constants

API_URL
VERSION

Public Class Methods

build_params(args={}) click to toggle source
# File lib/aliyun_sms.rb, line 58
def build_params(args={})
  {
    "Format":configuration.format,
    "SignatureMethod":configuration.signature_method,
    "SignatureVersion":configuration.signature_version,
    "Version":configuration.version,
    "AccessKeyId":configuration.access_key_id,
    "Action":"SingleSendSms",
    "ParamString":args[:params].to_json,
    "SignName":args[:sign_name],
    "RegionId":configuration.region_id,
    "SignatureNonce":args[:nonce]||SecureRandom.uuid,
    "TemplateCode":args[:tpl_id],
    "Timestamp":args[:timestamp]||timestamp,
    "RecNum":args[:phone],
  }.sort.to_h
end
configuration() click to toggle source
# File lib/aliyun_sms.rb, line 32
def configuration
  @configuration ||= Configuration.new
end
configure() { |configuration| ... } click to toggle source
# File lib/aliyun_sms.rb, line 28
def configure
  yield(configuration)
end
signature(params={}) click to toggle source
# File lib/aliyun_sms.rb, line 52
def signature(params={})
  canonicalized_query_string = URI.encode_www_form_component URI.encode_www_form(params)
  hmac_result = OpenSSL::HMAC.digest("sha1","#{configuration.access_key_secret}&","POST&%2F&#{canonicalized_query_string}")
  URI.encode_www_form_component Base64.encode64(hmac_result).chomp
end
to(opts={}) click to toggle source
# File lib/aliyun_sms.rb, line 36
def to(opts={})
  params = build_params(opts)
  params = params.delete_if { |k,v| v.nil? or v.to_s.empty? }
  begin 
    res = RestClient.post(API_URL, generate_query_body_str(params), :headers=>{"Content-Type":"application/x-www-form-urlencoded"})
    result = JSON.parse(res)
    if res.code==200 and result["Model"] and result["RequestId"]
      return {code:0, msg: "发送成功"}
    else
      return {code:res.code, msg: "发送失败"}
    end
  rescue=>e
    return {code:-1, msg:e.message}
  end
end

Private Class Methods

generate_query_body_str(params={}) click to toggle source
# File lib/aliyun_sms.rb, line 82
def generate_query_body_str(params={})
  str = params.map { |k,v| "#{k}=#{v}" }.join("&")
  "Signature=#{signature(params)}&#{str}"
end
timestamp() click to toggle source
# File lib/aliyun_sms.rb, line 78
def timestamp
  Time.now.utc.strftime("%FT%TZ")
end