Ngoài cách xác nhận tài khoản hay gửi thông báo bằng email thì hôm nay mình sẽ hướng dẫn các bạn 1 cách nữa là thông qua SMS/Voice
Công cụ sử dụng sẽ là gem Twilio
Installation
Để cài đặt bằng Bundler, hãy lấy phiên bản mới nhất:
gem 'twilio-ruby', '~> 5.47.0'
Để cài đặt thủ công twilio-ruby thông qua Rubygems, bạn chỉ cần cài đặt gem:
gem install twilio-ruby -v 5.47.0
Để tự xây dựng và cài đặt nhánh phát triển từ nguồn mới nhất:
1 2 3 4 | git clone <a href="/cdn-cgi/l/email-protection" class="__cf_email__">[email protected]</a>:twilio/twilio-ruby.git cd twilio-ruby make install |
Getting Started
Get API key
Truy cập https://www.twilio.com/ để đăng kí tài khoản và chọn các option phù hợp
Vào dashboard để lấy api key cần thiết cho bước tiếp theo
Setup Work
1 2 3 4 5 6 7 8 | require 'twilio-ruby' # put your own credentials here account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' auth_token = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' # set up a client to talk to the Twilio REST API @client = Twilio::REST::Client.new account_sid, auth_token |
Use An API Key
1 2 3 4 5 6 7 8 9 10 | require 'twilio-ruby' # put your own credentials here account_sid = 'ACxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' api_key_sid = 'zzzzzzzzzzzzzzzzzzzzzz' api_key_secret = 'yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy' # set up a client to talk to the Twilio REST API using an API Key @client = Twilio::REST::Client.new api_key_sid, api_key_secret, account_sid |
Specify a Region and/or Edge
Để tận dụng Cơ sở hạ tầng toàn cầu của Twilio, hãy chỉ định Region hoặc Edge cho client:
https://www.twilio.com/docs/global-infrastructure
1 2 3 4 5 6 7 8 9 | # set up a client to talk to the Twilio REST API over a specific region and edge @client = Twilio::REST::Client.new account_sid, auth_token, nil, 'au1' @client.edge = 'sydney' # you may also specify the region and/or edge after client creation @client = Twilio::REST::Client.new account_sid, auth_token @client.region = 'au1' @client.edge = 'sydney' |
Enable Debug logging
1 2 3 4 5 6 7 8 9 10 | @client = Twilio::REST::Client.new account_sid, auth_token myLogger = Logger.new(STDOUT) myLogger.level = Logger::DEBUG @client.logger = myLogger @client = Twilio::REST::Client.new account_sid, auth_token myLogger = Logger.new('my_log.log') myLogger.level = Logger::DEBUG @client.logger = myLogger |
Make a Call
Trước tiên hãy chọn 1 trial phone number
1 2 3 4 5 6 | @client.calls.create( from: '+14704358494', to: '+84987113442', url: 'http://example.com' ) |
Sẽ nhận được cuộc gọi từ số mình vừa chọn ở trên từ Hoa Kỳ bắt mình upgrade account =))
Send an SMS
1 2 3 4 5 6 | @client.messages.create( from: '+14704358494', to: '+84987113442', body: 'Vuong oi! Test Twilio ne :D' ) |
Nhận được tin nhắn rồi nè
List your SMS Messages
@client.messages.list(limit: 20)
Handling Errors
1 2 3 4 5 6 | begin messages = @client.messages.list(limit: 20) rescue Twilio::REST::RestError => e puts e.message end |
Lưu ý to bự là Twilio sẽ cho dùng thử với Trial Balance = $15.50
References: