Custom Websites. Quality Communication.

Use Ruby to send an SMS in Australia

By on Dec 7, 2016 in Code | 0 comments

Perhaps you use Ruby for your server scripts, or you have a rails project that needs to send SMSes?

SMS Broadcast is a decent provider and one that provides an API. You’ll need to register and get an API username and password from SMS Broadcast.

Unfortunately they don’t provide a code example to use HTTPS to send the SMS. This means sending your API username and password in the clear, which is not really an acceptable security practice.


 

require 'net/http'
require 'uri'
require 'cgi'
require 'openssl'

def send_sms(username, password, to_string, from_string, content)
    uri_domain = 'https://api.smsbroadcast.com.au'
    uri_path =
    '/api-adv.php'
    params =
    {:username => username, 
    :password => password, 
    :to =>to_string, 
    :from=>from_string, 
    :message=>content}
    uri_string =
    uri_domain +
    uri_path +
    "?" +
    params.map{|k,v| "#{k}=#{CGI::escape(v.to_s)}"}.join('&')
    uri = URI(uri_string)
    Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') 
        do |http|
        request = Net::HTTP::Get.new uri.request_uri
        response = http.request request
        #puts response.inspect
    end
return response
end

Explanation

The function send_sms takes:

:username – API username

:password – API password

:to – SMS recipient phone number

:from – SMS recipient name/number (you can put what you want there, no spaces),

:content – SMS message.

It then constructs the API url to “GET” from the API address and the parameters above.

Then it uses the Net/HTTP library to post an HTTPS request to that uri. You can optionally do something with the response, which informs you of the status of the send attempt.

You will need to have the server’s certificate in the trusted store for the SSL request to work.