Class: ChatSDK::WhatsApp::ApiClient

Inherits:
ApiClient::Base
  • Object
show all
Defined in:
lib/chat_sdk/whatsapp/api_client.rb

Constant Summary collapse

BASE_URL =
"https://graph.facebook.com/v25.0"

Instance Method Summary collapse

Constructor Details

#initialize(access_token, phone_number_id) ⇒ ApiClient

Returns a new instance of ApiClient.



8
9
10
11
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 8

def initialize(access_token, phone_number_id)
  @access_token = access_token
  @phone_number_id = phone_number_id
end

Instance Method Details

#download_media(url:) ⇒ Object



58
59
60
61
62
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 58

def download_media(url:)
  Faraday.get(url) do |req|
    req.headers["Authorization"] = "Bearer #{@access_token}"
  end
end

#get_media_url(media_id:) ⇒ Object



54
55
56
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 54

def get_media_url(media_id:)
  request(:get, media_id.to_s)
end

#mark_as_read(message_id:) ⇒ Object



46
47
48
49
50
51
52
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 46

def mark_as_read(message_id:)
  request(:post, "#{@phone_number_id}/messages", {
    "messaging_product" => "whatsapp",
    "status" => "read",
    "message_id" => message_id
  })
end

#send_message(to:, type:, **payload) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 13

def send_message(to:, type:, **payload)
  body = {
    "messaging_product" => "whatsapp",
    "recipient_type" => "individual",
    "to" => to,
    "type" => type
  }.merge(payload)

  request(:post, "#{@phone_number_id}/messages", body)
end

#send_reaction(to:, message_id:, emoji:) ⇒ Object



24
25
26
27
28
29
30
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 24

def send_reaction(to:, message_id:, emoji:)
  send_message(
    to: to,
    type: "reaction",
    reaction: {message_id: message_id, emoji: emoji}
  )
end

#send_template(to:, template_name:, language_code: "en", components: nil) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 32

def send_template(to:, template_name:, language_code: "en", components: nil)
  body = {
    "messaging_product" => "whatsapp",
    "to" => to,
    "type" => "template",
    "template" => {
      "name" => template_name,
      "language" => {"code" => language_code}
    }
  }
  body["template"]["components"] = components if components
  request(:post, "#{@phone_number_id}/messages", body)
end

#upload_media(io:, filename:, content_type:) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
# File 'lib/chat_sdk/whatsapp/api_client.rb', line 64

def upload_media(io:, filename:, content_type:)
  response = upload_connection.post("#{@phone_number_id}/media") do |req|
    req.body = {
      "messaging_product" => "whatsapp",
      "file" => Faraday::Multipart::FilePart.new(io, content_type, filename),
      "type" => content_type
    }
  end

  handle_response(response)
end