Skip to content

Instantly share code, notes, and snippets.

@jay16
Last active September 28, 2017 15:58
Show Gist options
  • Save jay16/98380a8f0dfca8ada89e99fe832ee78d to your computer and use it in GitHub Desktop.
Save jay16/98380a8f0dfca8ada89e99fe832ee78d to your computer and use it in GitHub Desktop.
# encoding: utf-8
#
# - [HTTP协议及签名](https://help.aliyun.com/document_detail/56189.html)
# - [OpenSSL::HMAC](https://ruby-doc.org/stdlib-2.1.0/libdoc/openssl/rdoc/OpenSSL/HMAC.html)
#
require 'uri'
require 'cgi'
require 'base64'
require 'openssl'
require 'httparty'
require 'securerandom'
access_id = 'access_id'
access_token = 'access_token'
system_params = {
AccessKeyId: access_id,
Timestamp: Time.now.getgm.strftime("%Y-%m-%dT%H:%M:%SZ"),
Format: 'JSON',
SignatureMethod: 'HMAC-SHA1',
SignatureVersion: '1.0',
SignatureNonce: SecureRandom.uuid
}
bussiness_params = {
Action: 'SendSms',
Version: '2017-05-25',
RegionId: 'cn-hangzhou',
PhoneNumbers: '13564379606',
SignName: '生意人',
TemplateCode: 'SMS_95610390',
TemplateParam: "{\"code\":\"666666\"}"
}
def pop_escape(str)
CGI::escape(str.to_s.strip).gsub("+", "%20").gsub("*", "%2A").gsub("%7E", "~")
end
params = system_params.merge(bussiness_params)
params_string = params.sort.to_h.each_with_object([]) { |(k, v), arr| arr.push([pop_escape(k), pop_escape(v)].join("=")) }.join("&")
sign_string = "GET&#{pop_escape('/')}&#{pop_escape(params_string)}"
digest = OpenSSL::Digest.new('sha1')
hmac = OpenSSL::HMAC.digest(digest, access_token + "&", sign_string)
sign = Base64.encode64(hmac)
sign = pop_escape(sign)
url = "http://dysmsapi.aliyuncs.com/?Signature=#{sign}&#{params_string}"
response = HTTParty.get(url)
puts url
puts response.code
puts response.message
puts response.body
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment