Rails - How to send confirmation code via SMS usin

2019-08-05 18:06发布

问题:

We are creating a Rails application for implement the Nexmo API. In registration process, we need to send confirmation code through SMS to the user from server-side using Nexmo API. But we don't have any idea about this. We wanted to implement this feature for India only.

I have used https://github.com/dotpromo/nexmos gem and my code is:

# Gemfile
gem 'nexmos'


#sms_controller.rb:

class SmsController < ApplicationController
  def new
    @sms = Sms.new
  end
  def createclient = ::Nexmos::Message.new('#', '#')
    res = client.send_text(from: '+910000000000', to: '+910000000000', text: 'Hello world!') 
    if res.success?
      puts "ok"
    else
      puts "fail"
    end
  end 
end

I have used my credentials for "key" and "Secret" in-place of "#" and replace from and to with my phone numbers. but it doesn't works. Even after not delivering the SMS to other numbers, the success block is being executed.

Can anybody guide us to implement this?.

回答1:

Well it looks like you'd want to use the Ruby library built for Nexmo.

Essentially what you'd do is put this sample code:

nexmo = Nexmo::Client.new('...API KEY...', '...API SECRET...')

response = nexmo.send_message({
  from: 'RUBY',
  to: '...NUMBER...',
  text: 'Hello world'
})

if response.success?
  puts "Sent message: #{response.message_id}"
elsif response.failure?
  raise response.error
end

..inside an action in your controller. Let's say it's your TextsController, and you put it under the create action. So in your config/routes.rb, put something like:

match "/sendtext" => "texts#create"

Then, you just hit mydomain.com/sendtext and the command should fire.

via varatis