Skip to content

Instantly share code, notes, and snippets.

@caiguanhao
Last active November 29, 2019 05:29
Show Gist options
  • Save caiguanhao/66301a9c22e20c08c5e1857cb31c54eb to your computer and use it in GitHub Desktop.
Save caiguanhao/66301a9c22e20c08c5e1857cb31c54eb to your computer and use it in GitHub Desktop.
腾讯云短信(接口鉴权 v3 / TC3) Ruby / Rails
# gem 'http'
def send_tencent!(country_code, cellphone, code)
number = "+#{country_code}#{cellphone}"
json = {
PhoneNumberSet: [ number ],
TemplateID: '<YOUR TEMPLATE ID>',
TemplateParamSet: [ code.to_s ],
SmsSdkAppid: Rails.application.credentials.tencent_cloud_sms_app_id,
}.to_json
host = 'sms.tencentcloudapi.com'
content_type = 'application/json; charset=utf-8'
signed_headers = 'content-type;host'
timestamp = Time.now.to_i.to_s
date = Date.today.to_s
secret_id = Rails.application.credentials.tencent_cloud_sms_secret_id
secret_key = Rails.application.credentials.tencent_cloud_sms_secret_key
service = 'sms'
ending = 'tc3_request'
scope = "#{date}/#{service}/#{ending}"
algorithm = 'TC3-HMAC-SHA256'
string_to_sign = [
algorithm,
timestamp,
scope,
Digest::SHA256.hexdigest([
'POST',
'/',
'',
[
"content-type:#{content_type}\n",
"host:#{host}\n",
].join,
signed_headers,
Digest::SHA256.hexdigest(json),
].join("\n")),
].join("\n")
signature = OpenSSL::HMAC.hexdigest(
'SHA256',
OpenSSL::HMAC.digest(
'SHA256',
OpenSSL::HMAC.digest(
'SHA256',
OpenSSL::HMAC.digest(
'SHA256',
"TC3#{secret_key}",
date,
),
service,
),
ending,
),
string_to_sign,
)
HTTP.timeout(3).post("https://#{host}/", body: json, headers: {
'Authorization': "#{algorithm} Credential=#{secret_id}/#{scope}, SignedHeaders=#{signed_headers}, Signature=#{signature}",
'X-TC-Action': 'SendSms',
'X-TC-Version': '2019-07-11',
'X-TC-Timestamp': timestamp,
'Content-Type': content_type,
'Host': host,
})
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment