使用 Twilio 宝石

假设你有 Twilio 帐户和 API 凭据 ,请将以下内容添加到你的 Gemfile:

gem 'twilio-ruby'

或者你可以 gem install twilio-ruby

要让 Twilio 将传入的 SMS 发送到应用程序中的特定路由,你需要为电话号码配置消息传递 URL。完成后,你需要在 config/routes.rb 中设置一条路线:

TwilioSample::Application.routes.draw do
  resources :messages
end

这将创建一个设置 RESTful 路由(GET /messages 列出消息,POST /messages 创建消息等),它们将向 MessagesController 发送请求。通过定义这些路由,你可以将 Twilio 仪表板中的消息传递 URL 设置为 https://your.site/messages 作为 HTTP POST Webhook。

你的控制器处理消息:

class MessagesController < ApplicationController

  def create
    # First, check to see if this message really came from Twilio
    uri, signature = [request.protocol, request.host_with_port, request.path].join, request.env['HTTP_X_TWILIO_SIGNATURE']
    validator = Twilio::Util::RequestValidator.new(ENV['TWILIO_AUTH_TOKEN'])
    
    if validator.validate(uri, request.request_parameters, signature)
      # The params hash has the data from the Twilio payload
      Rails.logger.info "I just got this message from #{params[:From]}: #{params[:Body]}"

      # Send back a response that Twilio can handle
      render xml: { Sms: "Thanks, I got your message" }.to_xml(root: 'Response')

    else
      # This request didn't come from Twilio, so return a "Forbidden" response
      head(403)
    end

  end

end