Пример использования ePochta SMS api 3.0 на языке Ruby

Отправка смс
Получения статуса отправленной смс
Получение цены отправки
Получение баланса


Отправка смс:

require 'uri'
require 'net/http'
require 'active_support/all'
require 'digest/md5'

#
# Epochta REST API Ruby class
#
# Documentation
# /api/v3.php
#
class EpochtaApi3

  #
  # Epochta API constructor
  #
  # @param [String] username
  # @param [String] password
  # @raise [Exception]
  #
  def initialize(public_key, secret_key)
    raise 'Empty public_key or secret_key' if public_key.to_s.empty? || secret_key.to_s.empty?

    @public_key = public_key
    @secret_key = secret_key
    @protocol = 'http'
    @url = @protocol + "://api.atompark.com/api/sms/3.0/"

  end

  #
  # Form and send request to API service
  #
  # @param [Hash] data
  # @return [Hash]
  # @raise [Exception]
  #
  def send_request(action, data = {})
    request_data = {}
    uri = URI.parse("#{@url}/#{action}")
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true if @protocol == 'http'
    request = Net::HTTP::Post.new(uri.request_uri)
    request.set_form_data(data)
    
    begin
        response = http.request(request)
        request_data[:data] = JSON.parse(response.body)
        request_data[:http_code] = response.code
    rescue Exception => e
        puts "Exception \n  message: #{e.message} \n  backtrace: #{e.backtrace}"
    end

    handle_result(request_data)
  end
  private :send_request

  #
  # Process results
  #
  # @param [String] custom_message
  # @return [Hash]
  #
  def handle_error (custom_message = nil)
    data = { is_error: true }
    data[:message] = custom_message unless custom_message.nil?
    data
  end
  private :handle_error

  #
  # Process errors
  #
  # @param [Hash] data
  # @return [Hash]
  #
  def handle_result (data)
    unless data[:http_code].to_i == 200
      data[:is_error] = true
    end
    data
  end
  private :handle_result
  
  # 
  # Calc sum for request
  # 
  # @param [Hash] data
  # @param [String] action
  # @return [String]
  #
  def calc_sum(data, action)
    raise "Empty data or action" if data.empty? || action.empty?
    data["version"]="3.0"
    data["action"]=action
    sum = ""
    sorted_data = data.sort.to_h  
    sorted_data.each { |key,value| sum += value.to_s }
    sum += @secret_key
    Digest::MD5.hexdigest(sum)   
  end
  private :calc_sum

  #
  # Send sms
  #
  # @param [String] book_name
  # @return [Hash]
  #
  def send_sms(sender, text, number, datetime = "", sms_lifetime = 0)
    return handle_error('Empty sender or text or phones') if sender.empty? || text.empty? || number.empty?
    action="sendSMS"
    data = { 
      "sender"=> sender,
      "text"=> text,
      "phone"=> number,
      "datetime"=> datetime,
      "sms_lifetime"=> sms_lifetime,
      "key"=> @public_key
    }
    data[:sum] = calc_sum(data, action)
    send_request(action, data)
  end

  #
  # Add addressbook
  #
  # @param [String] name
  # @param [String] description
  # @return [Hash]
  #
  def add_addressbook(name, description = "")
    return handle_error('Empty name') if name.empty?
    action="addAddressbook"
    data = { 
      "name"=> name,
      "description"=> description,
      "key"=> @public_key
    }
    data[:sum] = calc_sum(data, action)
    send_request(action, data)
  end

  #
  # Add phone to addressbook
  #
  # @param [Fixnum] id_addressbook
  # @param [String] phone
  # @param [String] variables
  # @return [Hash]
  #
  def add_phone_to_addressbook(id_addressbook, phone, variables = "")
    return handle_error('Empty id_addressbook or phone') if id_addressbook.nil? || id_addressbook == 0 || phone.empty?
    action="addPhoneToAddressBook"
    data = { 
      "idAddressBook"=> id_addressbook,
      "phone"=> phone,
      "variables"=> variables,
      "key"=> @public_key
    }
    data[:sum] = calc_sum(data, action)
    send_request(action, data)
  end

  #
  # Get user balance
  #
  # @param [String] currency
  # @return [Hash]
  #
  def get_user_balance(currency = "USD")
    action="getUserBalance"
    data = { 
      "currency"=> currency,
      "key"=> @public_key
    }
    puts data
    
    data[:sum] = calc_sum(data, action)
    send_request(action, data)
  end

  #
  # Create campaign
  #
  # @param [String] sender
  # @param [String] text
  # @param [Fixnum] list_id
  # @param [String] datetime
  # @param [Fixnum] batch
  # @param [Fixnum] batchinterval
  # @param [Fixnum] sms_lifetime
  # @param [String] control_phone
  # @return [Hash]
  #
  def create_campaign(sender, text, list_id, datetime = "", batch = 0, batchinterval = 0, sms_lifetime = 0, control_phone = "")
    return handle_error('Empty sender or text or list_id') if sender.empty? || text.empty? || list_id.to_s.empty?
    action="createCampaign"
    data = { 
      "sender"=> sender,
      "text"=> text,
      "list_id"=> list_id,
      "datetime"=> datetime,
      "batch" => batch,
      "batchinterval" => batchinterval,
      "sms_lifetime"=> sms_lifetime,
      "control_phone"=> control_phone,
      "key"=> @public_key
    }
    data[:sum] = calc_sum(data, action)
    send_request(action, data)
  end

end


#usage
public_key = 'your public key'
private_key = 'your private key'

epochta_api3 = EpochtaApi3.new(public_key, private_key)

puts "get_user_balance"
puts epochta_api3.get_user_balance
puts "\n"

#puts "add_addressbook"
#puts epochta_api3.add_addressbook("ruby book 1") # 1481422
#puts "\n"

#puts "add_phone_to_addressbook"
#puts epochta_api3.add_phone_to_addressbook(1481422, "380933630000") # 457106233
#puts "\n"

#puts "create_campaign"
#puts epochta_api3.create_campaign("SmSender", "text", 1481422) # {:data=>{"result"=>{"id"=>118554988, "price"=>0.013300399011970358, "currency"=>"USD"}}, :http_code=>"200"}
#puts "\n"

puts "send_sms"
puts epochta_api3.send_sms("TeSender", "ruby send sms 1", "380933630000") # {:data=>{"result"=>{"id"=>118555219, "price"=>0.013300399011970358, "currency"=>"USD"}}, :http_code=>"200"}
puts "\n"

По запросу предоставляется необходимое количество дополнительных смс для тестирования сервиса массовых смс-уведомлений ePochta SMS.

Есть вопрос?

  • 8 (800) 555-09-63
  • Бесплатно по России

Александр



skype: alexandr.romanow26
[email protected]

Людмила



skype: liudmilaatompark
[email protected]