简体   繁体   English

如何在 Rails 中通过 Twilio 发送短信?

[英]How to send SMS via Twilio in Rails?

I'm trying to create a simple rails app where user can send me a SMS via Twilio.我正在尝试创建一个简单的 rails 应用程序,用户可以在其中通过 Twilio 向我发送短信。 A user just needs to fill in the form on the home page with his name, email, some text and submit it.用户只需要在主页上填写他的姓名、电子邮件、一些文本并提交。 I need to create a function that would grab those 3 pieces of information from params, create a text message and send it to my phone number, but I have no idea how to do that.我需要创建一个函数来从参数中获取这 3 条信息,创建一条短信并将其发送到我的电话号码,但我不知道该怎么做。

Those are the form and routes that I tried to create for this:这些是我试图为此创建的形式和路线:

View: app/views/home/index.html.erb查看:app/views/home/index.html.erb

    <div>
        <%= form_for @phone, url: 'home/send_text' do |f| %>
        <%= f.label :name %>
        <%= f.text_field :name %>
        <%= f.label :email %>
        <%= f.text_field :email %>
        <%= f.label :message %>
        <%= f.text_field :message %>
        <%= f.submit 'Submit', class: "btn btn-primary" %>
        <% end %>
    </div>

Routes:路线:

Rails.application.routes.draw do
  root 'home#index'
  post 'home/send_text'
end

Just follow the below steps :-只需按照以下步骤操作:-

Step 1 : Create and Configure Twilio Account步骤 1创建和配置 Twilio 帐户

Step 2 : To integrate Twilio on Rails you have to add twilio-ruby gem to your Gemfile.第 2 步:要在 Rails 上集成 Twilio,您必须将 twilio-ruby gem 添加到 Gemfile。

gem ‘twilio-ruby’

Step 3 : After bundle install you have to use below code第 3 步:捆绑安装后,您必须使用以下代码

config/initializers/twilio.rb配置/初始化程序/twilio.rb

require 'rubygems' 
require 'twilio-ruby'

module TwilioSms
  def self.send_text(phone, content) 
    # phone :- phone number to which you want to send sms 
    # content :- Message text which you want to send
    twilio_sid = "*****" # paste twilio sid
    twilio_token = "*****" # paste twilio token
    twilio_phone_number = "+1******" # paste twilio number
    begin
      @twilio_client = Twilio::REST::Client.new twilio_sid, twilio_token

      @twilio_client.api.account.messages.create(
      :from => twilio_phone_number,
      :to => phone, 
      :body=> content

      )
    rescue Twilio::REST::TwilioError => e
       return e.message
    end
    return "send"
  end
end

Step 4 : call this method from where you want to call either controller or model.第 4 步:从您要调用控制器或模型的位置调用此方法。

TwilioSms.send_text("+91*******", "Hello") 

that's it... :)就是这样... :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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