Skip to content

Instantly share code, notes, and snippets.

@keithpitty
Forked from toolmantim/direct_sms.rb
Last active December 19, 2015 11:19
Show Gist options
  • Save keithpitty/5947010 to your computer and use it in GitHub Desktop.
Save keithpitty/5947010 to your computer and use it in GitHub Desktop.
# License
#
# Copyright (c) 2010 Tim Lucas <t.lucas@toolmantim.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
#
# Modified in July 2013 by Keith Pitty to work with the current API.
require 'net/https'
# A simple API wrapper for DirectSMS's HTTPS API (http://www.directsms.com.au/api/HTTP_API.pdf)
class DirectSMS
class UnknownError < StandardError; end
class ErrorResponse < StandardError; end
def initialize(username, password)
@connection_id = post '/connect', :username => username, :password => password
end
def send(message, to, from)
post '/send_message', connectionid: @connection_id,
message: message,
to: Array(to).join(","),
senderid: from,
type: '1-way'
end
private
def post(path, params={})
http = Net::HTTP.new('api.directsms.com.au', 443)
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE # Heroku needed this :(
http.start do |http|
req = Net::HTTP::Post.new("/s3/https#{path}")
req.set_form_data(params)
resp = http.request(req)
raise UnknownError.new(resp.body) unless resp.is_a?(Net::HTTPSuccess)
return parse(resp.body)
end
end
def parse(body)
match = body.match(/(.*?):(.*)/)
raise UnknownError.new(body) if !match
type, content = body.match(/(.*?): (.*)/).captures
raise ErrorResponse.new(content) if type != "id"
content.strip
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment