简体   繁体   中英

Rails - How to send confirmation code via SMS using nexmo api

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?.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM