Skip to content

Instantly share code, notes, and snippets.

@chen1i
Created April 21, 2018 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chen1i/32ffff12a228187d2c00f834127db9b5 to your computer and use it in GitHub Desktop.
Save chen1i/32ffff12a228187d2c00f834127db9b5 to your computer and use it in GitHub Desktop.
Simple wrapper for using Alidayu API. Works with Alidayu till 2017.6
# encoding: utf-8
module VendorSvc
class Alidayu
def initialize(options)
@app_key = AppConfig.alidayu_settings['app_key']
@app_secret = AppConfig.alidayu_settings['app_secret']
@svc_gateway = AppConfig.alidayu_settings['svc_gateway_https']
@sms_template = options[:sms_template]
@sms_sign = options[:sms_sign]
@app_product_name = options[:app_product_name] || AppConfig.alidayu_settings['app_product_name']
@params = { app_key: @app_key,
v: '2.0',
sign_method: 'md5',
format: 'json' }
@conn = Faraday.new(url: "https://#{@svc_gateway}") do |faraday|
faraday.request :url_encoded
faraday.response :logger
faraday.adapter Faraday.default_adapter
end
end
def send_sms(reciever, params = {})
Timeout::timeout(3) do
temp_content_json_str = params.merge(product: @app_product_name).to_json
request_params = @params.merge(method: 'alibaba.aliqin.fc.sms.num.send',
timestamp: current_time_for_aliyun,
sms_type: 'normal',
sms_free_sign_name: @sms_sign,
sms_template_code: @sms_template,
rec_num: reciever.to_s,
sms_param: temp_content_json_str)
signed_str = sign(request_params)
request_params[:sign] = signed_str
result = JSON.parse(@conn.post('', request_params).body)
if result['alibaba_aliqin_fc_sms_num_send_response'].present?
result = result['alibaba_aliqin_fc_sms_num_send_response']
raise result['result']['err_code'] if !result['result']['success']
return [result['result']['success'], result['result']['err_code']]
else
raise result['error_response']['sub_code']
end
end
end
def send_verification_code(code, reciever)
send_sms(reciever, { code: code })
end
private
# format should be yyyy-MM-dd HH:mm:ss,timezone is always GMT+8
def current_time_for_aliyun
Time.now.in_time_zone('Beijing').strftime('%F %T')
end
def sign(params)
sorted_keys = params.keys.sort
tmp_txt = @app_secret.dup
sorted_keys.each { |k| tmp_txt << k.to_s << params[k].to_s }
tmp_txt << @app_secret
Digest::MD5.hexdigest(tmp_txt).upcase
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment