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

六眼飞鱼酱① 提交于 2020-01-05 15:15:40

问题


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



来源:https://stackoverflow.com/questions/24226139/rails-how-to-send-confirmation-code-via-sms-using-nexmo-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!