Skip to content

Instantly share code, notes, and snippets.

@HungYuHei
Forked from mimosz/smser.rb
Created August 24, 2012 11:49
Show Gist options
  • Save HungYuHei/3449721 to your computer and use it in GitHub Desktop.
Save HungYuHei/3449721 to your computer and use it in GitHub Desktop.
短信宝
# -*- encoding: utf-8 -*-
require 'digest/md5'
require 'nestful'
class Smsbao
attr_accessor :login, :passwd
def initialize(login, passwd)
@login = login
@passwd = Digest::MD5.hexdigest(passwd)
end
# 发送短信
def send(mobile, content, limit = 300)
if mobile.is_a?(Array)
counter = 0
mobile.each_slice(limit).to_a.each do |mobiles| # 最大支持300为一组进行发送。
response = client('send', { m: mobiles.join(','), c: content })
stat = status(response)
if stat[:success]
counter += mobiles.count
else
return stat.merge({count: counter})
end
end
return { success: true, message: '短信队列成功', count: counter}
else
response = client('send', { m: mobile, c: content })
return status(response)
end
end
# 查询余额
def balance
response = client('balance')
return status(response)
end
private
def status(resp)
arr = resp.split("\n")
code = arr[0]
message = case code
when '0'
if arr[1].nil?
'短信发送成功'
else
vals = arr[1].split(",")
{sent: vals[0].to_i, balance: vals[1].to_i}
end
when '30'
'密码错误'
when '40'
'账号不存在'
when '41'
'余额不足'
when '42'
'帐号过期'
when '43'
'IP地址限制'
when '50'
'内容含有敏感词'
when '51'
'手机号码不正确'
end
{ success: (code == '0'), message: message }
end
def gw_url
'http://api.smsbao.com'
end
def method_path
{ send: '/sms', balance: '/query' }
end
def client(method, params={})
Nestful.get gw_url + method_path[method.to_sym], params: { u: @login, p: @passwd }.merge(params)
end
end
sms = Smsbao.new('username', 'password')
puts sms.balance
puts sms.send([15021955443,13570436426,13763338399,13719229993,15921926239],'配合群发测试,请回复:草泥马。')
puts sms.balance
users = [
{name: '温叔', mobile: 13916964187},
{name: '海威', mobile: 18626898633},
{name: '瑞林', mobile: 18602166916},
]
users.each do |user|
puts sms.send( user[:mobile], "#{user[:name]},你好:配合单发测试,请回复”我爱草泥马“。" )
end
puts sms.balance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment