Commit 3d3d058f by lra

淘宝短信接口添加

parents
/.bundle/
/.yardoc
/Gemfile.lock
/_yardoc/
/coverage/
/doc/
/pkg/
/spec/reports/
/tmp/
language: ruby
rvm:
- 2.1.5
source 'https://ruby.taobao.org'
# Specify your gem's dependencies in sms.gemspec
gemspec
# Sms
Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/ikcrm_sms`. To experiment with that code, run `bin/console` for an interactive prompt.
TODO: Delete this and the text above, and describe your gem
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'sms'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install sms
## Usage
TODO: Write usage instructions here
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.
To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Contributing
1. Fork it ( https://github.com/[my-github-username]/ikcrm_sms/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request
require "bundler/gem_tasks"
load "tasks/sms.rake"
\ No newline at end of file
#!/usr/bin/env ruby
require "optparse"
require "pp"
$:.unshift File.join(File.dirname(__FILE__), *%w[.. lib])
require 'sms'
options = {source: 'zucp', method: 'single'}
OptionParser.new do |o|
o.banner = <<-EOF
Usage:
Starting:
sms [-p <phone>] [-c <content>] [-m <model>] [-t <type>]
Querying:
sms -v
Options:
EOF
o.on("-p", "--phone=phone", String, "send sms phone") do |x|
options[:phone] = x
end
o.on("-c", "--content=content", String, "send sms content") do |x|
options[:content] = x
end
o.on("-s", "--source=source", String, "send sms source [zucp|taobao] (Default: zucp)") do |x|
options[:source] = x
end
o.on("-m", "--m=method", String, "send sms method [single|batch] (Default: single)") do |x|
options[:method] = x
end
o.on("-h", "--help", "Show help documentation") do |h|
puts o
exit
end
o.on("-v", "--version", "Show Sms version") do |ver|
puts "Version: #{Sms::VERSION}"
exit
end
end.parse!
begin
puts options.inspect
if options[:phone].present? && options[:content].present?
puts SmsSender.new({source: options[:source]}).send("#{options[:method]}Send", options[:phone], options[:content])
end
rescue => e
puts 'Uncaught exception'
puts e.message
puts e.backtrace.join("\n")
end
$:.unshift File.expand_path('../../lib', __FILE__)
require 'pp'
require "active_support/all"
require "sms/version"
require "sms/zucp"
require "sms/taobao"
require 'redis' unless defined? Redis
require 'yaml' unless defined? YMAL
def redis
if $redis && $redis.class.to_s =~ /Redis/
$redis
else
Redis.new(host: 'localhost', port: 6379)
end
end
def load_config
if defined? ::Rails
config = HashWithIndifferentAccess.new(YAML.load_file("#{::Rails.root}/config/sms.yml")[::Rails.env] || {})
else
{}
end
end
class SmsSender
SOURCES = %w(zucp taobao)
attr_accessor :source
def initialize(options = {})
options[:source] = redis.get('sms:source') || SOURCES.first if options[:model].blank?
return unless options[:source].in?(SOURCES)
if load_config.present? && load_config[options[:source]].present?
options = load_config[options[:source]].merge(options)
end
options = HashWithIndifferentAccess.new(options)
@source = "Sms/#{options[:source]}".camelize.constantize.new(options)
end
def singleSend(number, content)
return unless @source
@source.singleSend(number, content) if number.present? && content.present?
end
def batchSend(numbers, content)
return unless @source
_numbers = numbers.is_a?(String) ? numbers.split(',') : (numbers.is_a?(Array) ? numbers : [])
_numbers = _numbers.compact.uniq
@source.batchSend(_numbers, content) if _numbers.present? && content.present?
end
end
if defined? ::Rails
module Sms
module Rails
class Railtie < ::Rails::Railtie
rake_tasks do
load "tasks/sms.rake"
end
end
end
end
end
\ No newline at end of file
require 'json'
require 'digest'
require 'net/http'
module Sms
class Taobao
attr_accessor :app_secret, :app_key, :sms_free_sign_name, :sms_template_code, :sms_param
def initialize(options = {})
self.app_secret = options[:app_secret]
self.app_key = options[:app_key]
self.sms_free_sign_name = options[:sms_free_sign_name]
self.sms_template_code = options[:sms_template_code]
self.sms_param = options[:sms_param]
end
def singleSend(number, content = nil)
send(number.split, content)
end
def batchSend(numbers, content = nil)
send(numbers, content)
end
def defaultParams(numbers, content = nil)
{
method: 'alibaba.aliqin.fc.sms.num.send',
app_key: self.app_key,
timestamp: Time.now.strftime("%Y-%m-%d %H:%M:%S"),
format: 'json',
v: 2.0,
sign_method: 'md5',
sms_type: 'normal',
sms_free_sign_name: self.sms_free_sign_name,
rec_num: numbers.join(','),
sms_param: (self.sms_param || {content: content}).to_json,
sms_template_code: self.sms_template_code
}
end
def generate_sign(params)
str = params.to_a.map{|m| m.map(&:to_s).join }.sort.join
Digest::MD5.hexdigest("#{app_secret.to_s}#{str}#{app_secret.to_s}").upcase
end
def send(numbers, content)
params = defaultParams(numbers, content)
params = params.merge(sign: generate_sign(params))
data = request_api(params)
result = JSON.parse(data.body)
end
def request_api(params)
Net::HTTP.post_form(URI.parse('http://gw.api.taobao.com/router/rest'), params)
end
end
end
# options = {app_secret: '5aff003ac3c7243da65adef1e7c9c363', app_key: '23272925', sms_free_sign_name: '爱客验证码', sms_template_code: 'SMS_2575137', sms_param: {code: 'xxx', product: 'ddd'}}
# puts Sms::Taobao.new(options).singleSend('13262902619')
\ No newline at end of file
module Sms
VERSION = "0.1.0"
end
require 'net/http'
require "rexml/document"
require 'digest'
module Sms
class Zucp
include REXML
attr_accessor :messages, :sn, :pwd, :suffix
def initialize(options = {})
self.sn = options[:sn]
self.pwd = options[:pwd]
self.suffix = options[:suffix]
self.messages = {
1 => "没有需要取得的数据 取用户回复就出现1的返回值,表示没有回复数据",
-1 =>"重复注册 多次点击“注册”按钮或注册方法(Register)的“调用”按钮",
-2 =>"帐号/密码不正确 1.序列号未注册2.密码加密不正确3.密码已被修改4.序列号已注销",
-4 =>"余额不足支持本次发送 直接调用查询看是否余额为0或不足",
-5 =>"数据格式错误 只能自行调试了。或与技术支持联系",
-6 =>"参数有误 看参数传的是否均正常,请调试程序查看各参数",
-7 =>"权限受限 该序列号是否已经开通了调用该方法的权限",
-8 =>"流量控制错误",
-9 =>"扩展码权限错误 该序列号是否已经开通了扩展子号的权限,把ext这个参数置空。",
-10 => "内容长度长 短信内容过长,纯单字节不能超过1000个,双字节不能超过500个字符2.彩信不得超过50KB",
-11 => "内部数据库错误",
-12 => "序列号状态错误 序列号是否被禁用",
-13 => "没有提交增值内容 提交时,无文本或无图片",
-14 => "服务器写文件失败",
-15 => "文件内容base64编码错误",
-16 => "返回报告库参数错误",
-17 => "没有权限 如发送彩信仅限于SDK3",
-18 => "上次提交没有等待返回不能继续提交默认不支持多线程",
-19 => "禁止同时使用多个接口地址 每个序列号提交只能使用一个接口地址",
-20 => "相同手机号,相同内容重复提交",
-22 => "Ip鉴权失败 提交的IP不是所绑定的IP"
}
end
# 批量发送 numbers是个数组
def batchSend(numbers, content)
params = defaultParams( numbers, content)
data = send(params)
puts "data ************* #{data}"
# VcoolineLog::SmsApi.add("sms api batchSend data: #{data}")
body = parseResBody data.body
ret = body.to_i
message = messages[ret]
# VcoolineLog::SmsApi.add("sms api batchSend error message: #{message}")
ret
rescue => e
# VcoolineLog::SmsApi.add("sms api batchSend error message: #{e}")
-100
end
# 单次发送(用户名,密码,接收方号码,内容)
def singleSend(number, content)
params = defaultParams(number.split, content)
data = send(params)
# VcoolineLog::SmsApi.add("sms api singleSend data: #{data}")
body = parseResBody data.body
ret = body.to_i
message = messages[ret]
# VcoolineLog::SmsApi.add("sms api batchSend error message: #{message}")
ret
#rescue => e
# VcoolineLog::SmsApi.add("sms api batchSend error message: #{e}")
#-100
end
def balance
params = { sn: self.sn, pwd: self.pwd }
data = Net::HTTP.post_form(URI.parse("http://sdk2.zucp.net:8060/webservice.asmx/balance?sn=#{self.sn}&pwd=#{self.pwd}"), params)
body = parseResBody data.body
ret = body.to_i
ret
end
private
def md5password(sn, pwd)
Digest::MD5.hexdigest("#{sn}#{pwd}").upcase
end
def parseResBody(string)
doc = Document.new(string)
root = doc.root
root.text
end
def defaultParams(numbers, content)
params = {}
content = content + suffix.to_s
params["sn"] = sn
params["pwd"] = md5password(sn, pwd)
params["mobile"] = numbers.join(',')
params["content"] = content.encode('gb18030')
# params["ext"] = "" #Time.now.to_i
params["ext"] = "2" #Time.now.to_i
params["stime"] = ""
params["rrid"] = ""
# params["sign"] = "vcooline"
return params
end
def send(params)
Net::HTTP.post_form(URI.parse('http://sdk2.zucp.net:8060/webservice.asmx/mt'), params)
end
end
#s = Sms::Zucp.new
#s.singleSend("13052359606","hello world 你好世界")
end
namespace :sms do
task :create_default_config_file do
if File.exist?("#{::Rails.root}/config/sms.yml")
else
FileUtils.cp(File.expand_path("../../templates/sms.yml", __FILE__), "#{::Rails.root}/config/sms.yml")
end
end
end
\ No newline at end of file
defaults: &defaults
zucp:
sn: xxxx
pwd: xxxx
suffix: xxxx
taobao:
app_secret: xxxx
app_key: xxxx
sms_free_sign_name: xxxx
sms_template_code: xxxx
development:
<<: *defaults
test:
<<: *defaults
production:
<<: *defaults
# coding: utf-8
lib = File.expand_path('../lib', __FILE__)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
require 'sms/version'
Gem::Specification.new do |spec|
spec.name = "sms"
spec.version = Sms::VERSION
spec.authors = ["lra"]
spec.email = ["1261847034@qq.com"]
spec.summary = %q{sms send.}
spec.description = %q{sms send.}
spec.homepage = ""
spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
spec.bindir = "bin"
spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
spec.require_paths = ["lib"]
# if spec.respond_to?(:metadata)
# spec.metadata['allowed_push_host'] = "Set to 'http://mygemserver.com' to prevent pushes to rubygems.org, or delete to allow pushes to any server."
# end
spec.add_development_dependency "bundler", "~> 1.9"
spec.add_development_dependency "rake", "~> 10.0"
spec.add_development_dependency "activesupport", "~> 4.1.12"
spec.add_development_dependency 'redis', '~> 3.2', '>= 3.2.1'
end
$:.unshift File.expand_path('../../lib', __FILE__)
require 'minitest/autorun'
require 'sms'
\ No newline at end of file
# require_relative "test_helper"
# $:.unshift File.expand_path('../../test', __FILE__)
require 'test_helper'
class ZucpTest < Minitest::Test
describe 'Sms::Zucp test' do
before do
@options = {source: "zucp", phone: "13262902619", content: Time.now.to_i.to_s, sn: "SDK-WSS-010-05925x", pwd: "123456x", suffix: '[test]'}
end
it 'SmsSender singleSend' do
obj = SmsSender.new(@options)
assert_instance_of Sms::Zucp, obj.source
result = obj.singleSend(@options[:phone], @options[:content])
assert result.to_i > 0
end
it 'SmsSender batchSend' do
obj = SmsSender.new(@options)
assert_instance_of Sms::Zucp, obj.source
result = obj.batchSend(@options[:phone], @options[:content])
assert result.to_i > 0
end
it 'Sms::Zucp singleSend' do
obj = Sms::Zucp.new(@options)
assert obj.sn.present?
assert obj.pwd.present?
result = obj.singleSend(@options[:phone], @options[:content])
assert result.to_i > 0
end
it 'Sms::Zucp batchSend' do
obj = Sms::Zucp.new(@options)
assert obj.sn.present?
assert obj.pwd.present?
result = obj.batchSend(@options[:phone].split, @options[:content])
assert result.to_i > 0
end
end
end
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment