Class: Line::Bot::V2::WebhookParser

Inherits:
Object
  • Object
show all
Defined in:
lib/line/bot/v2/webhook_parser.rb

Defined Under Namespace

Classes: InvalidSignatureError

Instance Method Summary collapse

Constructor Details

#initialize(channel_secret:) ⇒ WebhookParser

Returns a new instance of WebhookParser.



14
15
16
# File 'lib/line/bot/v2/webhook_parser.rb', line 14

def initialize(channel_secret:)
  @channel_secret = channel_secret
end

Instance Method Details

#parse(body:, signature:) ⇒ Array<Line::Bot::V2::Webhook::Event>

Parse events from the raw request body and validate the signature.

Examples:

Sinatra usage

def parser
  @parser ||= Line::Bot::V2::WebhookParser.new(channel_secret: ENV.fetch("LINE_CHANNEL_SECRET"))
end

post '/callback' do
  body = request.body.read
  signature = request.env['HTTP_X_LINE_SIGNATURE']

  begin
    events = parser.parse(body: body, signature: signature)
  rescue Line::Bot::V2::WebhookParser::InvalidSignatureError
    halt 400, { 'Content-Type' => 'text/plain' }, 'Bad Request'
  end

  # Handle events...
  events.each do |event|
    case event
    when Line::Bot::V2::Webhook::MessageEvent
      handle_message_event(event)
    ...
  end
  "OK"
end

Parameters:

  • body (String)

    The unmodified request body (exactly as received).

  • signature (String)

    The value of the ‘X-LINE-Signature’ header.

Returns:

  • (Array<Line::Bot::V2::Webhook::Event>)

    An array of event objects. Recognized events become instances of classes under ‘Line::Bot::V2::Webhook::*Event`; `Line::Bot::V2::Webhook::Event` is returned as fallback only when the event class is not defined in line-bot-sdk library. When you update the SDK, you may not need to handle `Line::Bot::V2::Webhook::Event` anymore.

Raises:



56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/line/bot/v2/webhook_parser.rb', line 56

def parse(body:, signature:)
  raise InvalidSignatureError.new("Invalid signature: #{signature}") unless verify_signature(body: body, signature: signature)

  data = JSON.parse(body.chomp, symbolize_names: true)
  data = Line::Bot::V2::Utils.deep_underscore(data)
  data = Line::Bot::V2::Utils.deep_convert_reserved_words(data)
  data = Line::Bot::V2::Utils.deep_symbolize(data)

  data[:events].map do |event|
    Line::Bot::V2::Webhook::Event.create(**event) # steep:ignore
  end
end