Skip to content

Instantly share code, notes, and snippets.

@jay16
Created September 28, 2017 15:59
Show Gist options
  • Save jay16/87e560a48000aaf2399b2a8632e3260b to your computer and use it in GitHub Desktop.
Save jay16/87e560a48000aaf2399b2a8632e3260b 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'
module SMS
class Aliyun
class << self
def send(options = {})
system_params = {
AccessKeyId: options[: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: options[:receivers],
SignName: options[:signature],
TemplateCode: options[:template_code],
TemplateParam: options[:template_param] || ''
}
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, options[: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)
{receivers: options[:receivers], send_state: response.body}
rescue => e
{receivers: options[:receivers], send_state: format('Error#SMS.send: %s', e.message)}
end
def pop_escape(str)
::CGI::escape(str.to_s.strip).gsub("+", "%20").gsub("*", "%2A").gsub("%7E", "~")
end
end
end
end
options = {
access_id: 'access_id',
access_token: 'access_token',
receivers: '13564379606',
signature: '生意人',
template_code: 'SMS_95610390',
template_param: "{\"code\":\"666666\"}"
}
puts SMS::Aliyun.send(options)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment