[Rails + LINE] Phần 2: Gửi Push Message với LINE Messaging API bằng Ruby on Rails
Tiếp nối series Rails + LINE
Ở phần trước mình đã chia sẻ cách đăng nhập/đăng ký tài khoản Rails bằng LINE Login. Hôm nay, chúng ta sẽ “level up” — cho Rails biết cách trò chuyện trực tiếp với LINE.
Tức là: ứng dụng Rails của bạn có thể gửi tin nhắn LINE tự động đến người dùng chỉ với vài dòng code.
Cực kỳ hữu ích khi bạn muốn:
- Gửi thông báo xác nhận đơn hàng
- Nhắc lịch hẹn
- Báo lỗi hệ thống
1. Chuẩn bị “vũ khí” — gem line-bot-api
Cài gem:
gem "line-bot-api"
Rồi chạy:
2. Tạo LINE Messaging API
Truy cập https://developers.line.biz/console/
-
Tạo Provider (nếu chưa có)
-
Tạo Channel mới, chọn loại Messaging API
-
Ở phần “Channel settings”, ghi lại:
- Channel Secret
- Channel Access Token
-
Trong phần “Messaging API”, bật “Allow bot to send messages”
Sau đó, tạo file .env để lưu thông tin này:
LINE_CHANNEL_ACCESS_TOKEN=xxxxxxxxxxxxxxx
3. Gửi tin nhắn LINE chỉ bằng vài dòng Ruby
Tạo thử một service class trong Rails: ở đây mình sẽ tạo ra một service là app/services/line_message_service.rb
require "faraday"
require "json"
require "line/bot"
class LineNotifyService
def initialize(user)
@user = user
end
def send_message(text)
return false if @user.uid.blank?
request_body = {
to: @user.uid,
messages: [
{ type: "text", text: text }
]
}
Rails.logger.info("LINE: Preparing to send message to UID=#{@user.uid}, body=#{request_body}")
begin
# Production / normal SDK call
response = LINE_V2_CLIENT.push_message(
push_message_request: Line::Bot::V2::MessagingApi::PushMessageRequest.new(
to: @user.uid,
messages: [Line::Bot::V2::MessagingApi::TextMessage.new(text: text)]
)
)
Rails.logger.info("LINE SDK response: #{response.inspect}")
response
rescue OpenSSL::SSL::SSLError => e
Rails.logger.warn("LINE SDK SSL failed: #{e.class}: #{e.message}.")
if Rails.env.development?
# Dev-only fallback
send_via_faraday_fallback(request_body)
else
raise
end
end
end
private
# Dev-only fallback: POST directly and disable SSL verification
def send_via_faraday_fallback(body)
token = ENV.fetch("LINE_CHANNEL_ACCESS_TOKEN")
conn = Faraday.new(url: "https://api.line.me", ssl: { verify: false }) do |f|
f.request :json
f.response :logger
f.adapter Faraday.default_adapter
end
resp = conn.post("/v2/bot/message/push") do |req|
req.headers["Content-Type"] = "application/json"
req.headers["Authorization"] = "Bearer #{token}"
req.body = body.to_json
end
Rails.logger.info("LINE fallback response: #{resp.status} #{resp.body}")
resp
end
end
Sau khi làm những bước trên, mình chỉ cần gọi serice vừa tạo ở bất kì controller nào mình muốn, ở đây mình demo nên mình sẽ vô HomeController và tạo một method send_line_notification
def send_line_notification
if current_user.uid.present?
LineNotifyService.new(current_user).send_message("hello world!")
flash[:notice] = "Notification sent to LINE!"
else
flash[:alert] = "LINE ID not found. Can't send notification."
end
redirect_to root_path
end
bên router thì chúng ta sẽ thêm:
post "send_line_notification", to: "home#send_line_notification"
4. Tích hợp với sự kiện thực tế
class Booking < ApplicationRecord
after_create :notify_user
private
def notify_user
return unless user.uid.present?
LineNotifyService.new(user).send_message("Lịch hẹn của bạn vào #{start_time.strftime('%H:%M %d/%m')} đã được xác nhận!")
end
end
Kết quả: → Người dùng sẽ nhận tin nhắn LINE tự động ngay sau khi đặt lịch
5. Kết luận
Chỉ với vài bước, Rails đã “nói chuyện” được với LINE! Từ đây, bạn có thể:
- Tự động gửi thông báo đặt lịch
- Gửi tin nhắn khuyến mãi
- Thậm chí… gửi lời chúc sinh nhật
All rights reserved