[英]How to send SMS via Twilio in Rails?
我正在嘗試創建一個簡單的 rails 應用程序,用戶可以在其中通過 Twilio 向我發送短信。 用戶只需要在主頁上填寫他的姓名、電子郵件、一些文本並提交。 我需要創建一個函數來從參數中獲取這 3 條信息,創建一條短信並將其發送到我的電話號碼,但我不知道該怎么做。
這些是我試圖為此創建的形式和路線:
查看: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>
路線:
Rails.application.routes.draw do
root 'home#index'
post 'home/send_text'
end
只需按照以下步驟操作:-
步驟 1 : 創建和配置 Twilio 帳戶
第 2 步:要在 Rails 上集成 Twilio,您必須將 twilio-ruby gem 添加到 Gemfile。
gem ‘twilio-ruby’
第 3 步:捆綁安裝后,您必須使用以下代碼
配置/初始化程序/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
第 4 步:從您要調用控制器或模型的位置調用此方法。
TwilioSms.send_text("+91*******", "Hello")
就是這樣... :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.