Coder Social home page Coder Social logo

aliyun-sms's Introduction

Aliyun::Sms Ruby Gem for Aliyun Short Message Service(aliyun-sms)

Comfortable to aliyun sms 2017-05-25 version api

Notice

Currently, aliyun has three services of short message,named:

  1. ali-dayu(阿里大于)
  2. aliyun-mq(阿里云消息队列)
  3. aliyun-sms(阿里云短信服务)

They all are usable, and will merge togather in future. But before merged, they are Independent, and every user only use one between them.

This gem only for aliyun-sms(阿里云短信服务), and you must confirm that you just use it. If you can't confirm, please see the document 阿里云短信业务说明 to get guidance.

Before

Before use aliyun-sms, you must apply and open the aliyun-sms, and get the parameters as follows:

  1. ACCESS_KEY_SECRET: apply on aliyun console
  2. ACCESS_KEY_ID: apply on aliyun console
  3. SIGN_NAME: get when open the aliyun-sms
  4. TEMPLATE_CODE: get when open the aliyun-sms

Installation

Ruby Common Method

gem install aliyun-sms

Rails Method

Add in Gemfile :

gem 'aliyun-sms'   # Ruby Gems 安装源

Run command:

bundle

Download Method

Clone and install by rake.

git clone https://github.com/VICTOR-LUO-F/aliyun-sms.git

cd aliyun-sms

rake build

rake install

Problem and Resolve

require 'aliyun/sms'

If you get a error as follows, when running above command:

./config/initializers/aliyun-sms.rb:1:in `<top (required)>': uninitialized constant Aliyun::Sms (NameError)

You could switch to github resource, and modify the the Rails Gemfile to:

gem 'aliyun-sms', '1.1.1', git: 'https://github.com/VICTOR-LUO-F/aliyun-sms.git'

Usage

Ruby Common Program(irb)

First Step:

$ require 'aliyun/sms'

return

=> true

Second Step:

$ Aliyun::Sms.configure do |config|
    config.access_key_secret = ACCESS_KEY_SECRET    
    config.access_key_id = ACCESS_KEY_ID            
    config.action = 'SendSms'                       # default value
    config.format = 'XML'                           # http return format, value is 'JSON' or 'XML'
    config.region_id = 'cn-hangzhou'                # default value      
    config.sign_name = SIGN_NAME                  
    config.signature_method = 'HMAC-SHA1'           # default value
    config.signature_version = '1.0'                # default value
    config.version = '2017-05-25'                   # default value
  end

return

  => "2017-05-25"

Third Step:

Send message:

$ Aliyun::Sms.send(phone_numbers, template_code, template_param, out_id)

Explanation:

  1. phone_numbers: the phone number, string type, such as '1234567890'. You can use multiple phone numbers devided by comma, such as '1234567890,12388888888'.
  2. template_code: message template code, string type, such as 'SMS_12345678'.
  3. template_param: message template params, tring type, such as '{"code":"666666", "product":"content" }'.
  4. out_id:out extension id,string type,could be null。

Rails Application

First Step:

In Rails direction 'config/initializers/', create file 'aliyun-sms.rb', and add code:

config/initializers/aliyun-sms.rb

Aliyun::Sms.configure do |config|
  config.access_key_secret = ACCESS_KEY_SECRET    
  config.access_key_id = ACCESS_KEY_ID            
  config.action = 'SendSms'                       # default value
  config.format = 'XML'                           # http return format, value is 'JSON' or 'XML'
  config.region_id = 'cn-hangzhou'                # default value      
  config.sign_name = SIGN_NAME                    
  config.signature_method = 'HMAC-SHA1'           # default value
  config.signature_version = '1.0'                # default value
  config.version = '2017-05-25'                   # default value
end

then, restart Rails application。

Second Step:

Send message in your program:

Aliyun::Sms.send(phone_numbers, template_code, template_param, out_id)

Explanation:

  1. phone_numbers: the phone number, string type, such as '1234567890'. You can use multiple phone numbers devided by comma, such as '1234567890,12388888888'.
  2. template_code: message template code, string type, such as 'SMS_12345678'.
  3. template_param: message template params, tring type, such as '{"code":"666666", "product":"content" }'.
  4. out_id:out extension id,string type,could be null。

Specially:

In Rails application program, you could organize your message content as a hash, and trans it bo be a param of Aliyun::Sms.send by to_json method. For instance:

...
phone_number = '1234567890'
template_code = 'SMS_12345678'
template_param = {"code"=>"666666", "product"=>"conten" }.to_json
Aliyun::Sms.send(phone_numbers, template_code, template_param)
...

Development

According to Aliyun Official Document example, I had written spect test. You could run the test after clone as follows:

$ bundle exec rspec spec

License

MIT License。 MIT License.

aliyun-sms's People

Contributors

qwlong avatar victor-luo-f avatar wxjzeke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

aliyun-sms's Issues

兼容ruby版本是1.9.3的参数排序

# Canonicalized Query String/使用请求参数构造规范化的请求字符串
        # 按照参数名称的字典顺序对请求中所有的请求参数进行排序
        params = params.sort.to_h

可改为

params = Hash[params.sort]

Error: uninitialized constant Aliyun (NameError)

Hi there,
I used your gem to send Aliyun SMS. But after add gem and config step "在 rails 应用目录 config/initializers/ 下创建脚本文件 aliyun-sms.rb,在文件中加入以下内容"
=> I got error when try run rails console
config/initializers/aliyun_sms.rb:1:in `<top (required)>': uninitialized constant Aliyun (NameError)

Please you help me to resolve it.
Thanks you

404报错

麻烦大佬帮忙看下 :

#<Typhoeus::Response:0x00007ff7085ed308
 @options=
  {:httpauth_avail=>0,
   :total_time=>0.122419,
   :starttransfer_time=>0.122037,
   :appconnect_time=>0.0,
   :pretransfer_time=>0.055867,
   :connect_time=>0.055749,
   :namelookup_time=>0.001119,
   :redirect_time=>0.0,
   :effective_url=>
    "http://dysmsapi.aliyuncs.com/?Signature=fWjVpLhvJYm%2B5a6fXFzt%2FKxDcOI%3D&AccessKeyId=ACCESS_KEY_ID&Action=SendSms&Format=JSON&OutId=&PhoneNumbers=phone_numbers&RegionId=cn-shenzhen&SignName=%E4%BC%A0%E9%9F%B3%E7%BD%91%E7%BB%9C&SignatureMethod=HMAC-SHA1&SignatureNonce=20220329065145485&SignatureVersion=1.0&TemplateCode=template_code&TemplateParam=template_param%2C%20out_id&Timestamp=2022-03-29T06%3A51%3A45Z&Version=2017-05-25",
   :primary_ip=>"106.11.45.35",
   :response_code=>404,
   :request_size=>522,
   :redirect_count=>0,
   :size_upload=>0.0,
   :size_download=>266.0,
   :speed_upload=>0.0,
   :speed_download=>2180.0,
   :return_code=>:ok,
   :response_headers=>
    "HTTP/1.1 404 Not Found\r\nDate: Tue, 29 Mar 2022 06:51:45 GMT\r\nContent-Type: application/json;charset=utf-8\r\nContent-Length: 266\r\nConnection: keep-alive\r\nAccess-Control-Allow-Origin: *\r\nAccess-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE\r\nAccess-Control-Allow-Headers: X-Requested-With, X-Sequence, _aop_secret, _aop_signature, x-acs-action, x-acs-version, x-acs-date, Content-Type\r\nAccess-Control-Max-Age: 172800\r\nx-acs-request-id: 4731D7AA-4167-560A-98C1-8E670FF65350\r\nx-acs-trace-id: 65f4fad1786e12a59439134cfe55f760\r\n\r\n",
   :response_body=>
    "{\"RequestId\":\"4731D7AA-4167-560A-98C1-8E670FF65350\",\"Message\":\"Specified access key is not found.\",\"Recommend\":\"https://troubleshoot.api.aliyun.com?q=InvalidAccessKeyId.NotFound&product=Dysmsapi\",\"HostId\":\"dysmsapi.aliyuncs.com\",\"Code\":\"InvalidAccessKeyId.NotFound\"}",
   :debug_info=>#<Ethon::Easy::DebugInfo:0x00007ff708744cb0 @messages=[]>},
 @request=
  #<Typhoeus::Request:0x00007ff7087351c0
   @base_url=
    "http://dysmsapi.aliyuncs.com/?Signature=fWjVpLhvJYm%2B5a6fXFzt%2FKxDcOI%3D&AccessKeyId=ACCESS_KEY_ID&Action=SendSms&Format=JSON&OutId=&PhoneNumbers=phone_numbers&RegionId=cn-shenzhen&SignName=%E4%BC%A0%E9%9F%B3%E7%BD%91%E7%BB%9C&SignatureMethod=HMAC-SHA1&SignatureNonce=20220329065145485&SignatureVersion=1.0&TemplateCode=template_code&TemplateParam=template_param%2C%20out_id&Timestamp=2022-03-29T06%3A51%3A45Z&Version=2017-05-25",
   @on_complete=[],
   @on_failure=[],
   @on_headers=[],
   @on_progress=[],
   @options=
    {:method=>:get,
     :headers=>{"User-Agent"=>"Typhoeus - https://github.com/typhoeus/typhoeus", "Expect"=>""},
     :maxredirs=>50},
   @original_options={:method=>:get},
   @response=#<Typhoeus::Response:0x00007ff7085ed308 ...>>> 

SMS won't send - no error

I have this

Aliyun::Sms.configure do |config|
    config.access_key_id = ENV['ALIYUN_SMS_ID']            
    config.access_key_secret = ENV['ALIYUN_SMS_SECRET']    
    config.action = 'SendSms'                       # default value
    config.format = 'JSON'                           # http return format, value is 'JSON' or 'XML'
    config.region_id = 'cn-hangzhou'                # default value      
    config.sign_name = 'Plain'                  
    config.signature_method = 'HMAC-SHA1'           # default value
    config.signature_version = '1.0'                # default value
    config.version = '2017-05-25'                   # default value

    puts config.access_key_id, config.access_key_secret
end

phone_number = '15618928329'
template_code = 'SMS_180765444'
template_param = {"name"=>"hello"}.to_json
Aliyun::Sms.send(phone_number, template_code, template_param)

But I don't receive anything. I can find my sms templates on this address: https://dysms.console.aliyun.com/dysms.htm

and my credentials are fine.

Why doesn't it send? Where can I see the error?

一个重构的版本

class AliyunSmsService

  API_URL = 'https://sms.aliyuncs.com/'

  DEFAULT_PARAMS = {
    'Format'          => 'JSON',
    'SignatureMethod'  => 'HMAC-SHA1',
    'SignatureVersion' => '1.0',
    'Version'         => '2016-09-27'
  }

  class << self

    attr_accessor :access_key, :secret_key
    attr_accessor :sign_name


    def send_sms(opts = {})
      RestClient.post(API_URL, build_params({
        'Action'      => 'SingleSendSms',
        'RecNum'      => opts[:phone],
        'SignName'    => opts[:sign_name],
        'TemplateCode'=> opts[:template_id],
        'ParamString' => opts[:params].try(:to_json)
      }), headers: {'Content-Type'=> "application/x-www-form-urlencoded"})
    end

    private

      def build_params(params = {})
        DEFAULT_PARAMS.merge({
          'AccessKeyId'     => self.access_key,
          'SignName'        => self.sign_name,
          'SignatureNonce'  => SecureRandom.uuid,
          'Timestamp'       => Time.now.utc.strftime("%FT%TZ")
        }).merge(params).tap {|p| p.merge!({'Signature' => generate_signature(p)}) }
      end

      def generate_signature(params)
        Base64.encode64(OpenSSL::HMAC.digest('sha1', "#{self.secret_key}&", "POST&%2F&#{ERB::Util.url_encode(params.to_query)}")).chomp
      end
  end
end

这个实现还存在一些小问题,仅是抛砖引玉,为了更好的代码。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.