Class: Xip::Services::Facebook::Client

Inherits:
BaseClient
  • Object
show all
Defined in:
lib/xip/services/facebook/client.rb

Constant Summary collapse

FB_ENDPOINT =
if ENV['FACEBOOK_API_VERSION'].present?
  "https://graph.facebook.com/v#{ENV['FACEBOOK_API_VERSION']}/me"
else
  "https://graph.facebook.com/v3.2/me"
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(reply:, endpoint: 'messages') ⇒ Client

Returns a new instance of Client.



22
23
24
25
26
# File 'lib/xip/services/facebook/client.rb', line 22

def initialize(reply:, endpoint: 'messages')
  @reply = reply
  access_token = "access_token=#{Xip.config.facebook.page_access_token}"
  @api_endpoint = [[FB_ENDPOINT, endpoint].join('/'), access_token].join('?')
end

Instance Attribute Details

#api_endpointObject (readonly)

Returns the value of attribute api_endpoint.



20
21
22
# File 'lib/xip/services/facebook/client.rb', line 20

def api_endpoint
  @api_endpoint
end

#replyObject (readonly)

Returns the value of attribute reply.



20
21
22
# File 'lib/xip/services/facebook/client.rb', line 20

def reply
  @reply
end

Class Method Details

.fetch_profile(recipient_id:, fields: nil) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/xip/services/facebook/client.rb', line 59

def self.fetch_profile(recipient_id:, fields: nil)
  if fields.blank?
    fields = [:id, :name, :first_name, :last_name, :profile_pic]
  end

  query_hash = {
    fields: fields.join(','),
    access_token: Xip.config.facebook.page_access_token
  }

  uri = URI::HTTPS.build(
    host: "graph.facebook.com",
    path: "/#{recipient_id}",
    query: query_hash.to_query
  )

  res = http_client.get(uri.to_s)
  Xip::Logger.l(topic:
    'facebook',
    message: "Requested user profile for #{recipient_id}. Response: #{res.status.code}: #{res.body}"
  )

  if res.status.success?
    MultiJson.load(res.body.to_s)
  else
    raise(
      Xip::Errors::ServiceError,
      "Facebook error #{res.status}: #{res.body}"
    )
  end
end

.http_clientObject



52
53
54
55
56
57
# File 'lib/xip/services/facebook/client.rb', line 52

def self.http_client
  headers = {
    'Content-Type' => 'application/json'
  }
  HTTP.timeout(connect: 15, read: 60).headers(headers)
end

.track(recipient_id:, metric:, value:, options: {}) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# File 'lib/xip/services/facebook/client.rb', line 91

def self.track(recipient_id:, metric:, value:, options: {})
  metric_values = [{
    '_eventName' => metric,
    '_valueToSum' => value
  }]

  metric_values.first.merge!(options)

  params = {
    event: 'CUSTOM_APP_EVENTS',
    custom_events: MultiJson.dump(metric_values),
    advertiser_tracking_enabled: 1,
    application_tracking_enabled: 1,
    extinfo: MultiJson.dump(['mb1']),
    page_scoped_user_id: recipient_id,
    page_id: Xip.config.facebook.page_id
  }

  uri = URI::HTTPS.build(
    host: "graph.facebook.com",
    path: "/#{Xip.config.facebook.app_id}/activities"
  )

  res = http_client.post(uri.to_s, body: MultiJson.dump(params))
  Xip::Logger.l(
    topic: "facebook",
    message: "Sent custom event for metric: #{metric} and value: #{value}. Response: #{res.status}: #{res.body}"
  )

  if res.status.success?
    MultiJson.load(res.body.to_s)
  else
    raise(
      Xip::Errors::ServiceError,
      "Facebook error #{res.status}: #{res.body}"
    )
  end
end

Instance Method Details

#transmitObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/xip/services/facebook/client.rb', line 28

def transmit
  res = self
          .class
          .http_client
          .post(api_endpoint, body: MultiJson.dump(reply))

  if res.status.client_error? # HTTP 4xx error
    # Messenger error sub-codes (https://developers.facebook.com/docs/messenger-platform/reference/send-api/error-codes)
    case res.body
    when /1545041/
      raise Xip::Errors::UserOptOut
    when /2018108/
      raise Xip::Errors::UserOptOut
    when /2018028/
      raise Xip::Errors::InvalidSessionID.new('Cannot message users who are not admins, developers or testers of the app until pages_messaging permission is reviewed and the app is live.')
    end
  end

  Xip::Logger.l(
    topic: "facebook",
    message: "Transmitted. Response: #{res.status.code}: #{res.body}"
  )
end