whatsapp_sdk 1.2.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 6e1bc509c72a21009421ece7489cc79d178abec74db4445d84cf579fe374d5d3
4
- data.tar.gz: b547704f8654b49e389547d27014089fdf1583583e57c6f567bf1193dbfc72aa
3
+ metadata.gz: 202653d687745c5eb823ee6695f81b957d61ab71483a1b634fcc220950e8308b
4
+ data.tar.gz: 7c0c90da847bb1d09ce19e2427c6da83e10ff999e7ffcffe63a9faf684cf472f
5
5
  SHA512:
6
- metadata.gz: f302ce6f5126585be265c8a0bdcc7c7681cd27e6838ce6c961a0b196eb66ba0cc3522c87407cbc69af7d95f8adeca02f7dbcf76ee646fddff49e3e50ba6c62b3
7
- data.tar.gz: d7a97fa6bc6de65711c1d1698cd38863650dfc7f2dd0ef5ec743d2c938e15bca6511f6481c5fd72ee2972ec258466c9066817a9a3ea378f98c0d2db26a05e186
6
+ metadata.gz: c5f66afee0a839d25a167241d8e9df918330f12a42badbb7d300e774b2400127836358075a769a726a085bfac0a059bdbed450c9c879c2ee0b90df098c2bff90
7
+ data.tar.gz: d34b6ac016775f7a7d9a8fb3431d4cea9b9bff2abecf8a1bc04136b5ed4be4dda4ea60fc943e51ca0ee7848b933588cfa6cfdbeb9f0328cfbae60c3ec4232652
data/CHANGELOG.md CHANGED
@@ -1,5 +1,17 @@
1
1
  # Unreleased
2
2
 
3
+ # v 2.0.0
4
+ - Add support for v26.0 and v27.0 API. @dominikklein [213](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/213)
5
+ - Accept an `after` cursor in `templates.list` to read past the first page of message templates. @afonso-aguas [211](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/211)
6
+ - **Breaking:** Raise `HttpResponseError` for every HTTP response with status >= 400 in the default parsed mode (previously only >= 500 or bodies with a Graph `error` key). Use `raw_response: true` to inspect 4xx bodies yourself. @oitedi [209](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/209)
7
+ - Add explicit WhatsApp phone onboarding operations: `phone_numbers.add`, `request_code`, `verify_code`, `set_public_key`/`get_public_key`, and `business_accounts.subscribe_app` @oitedi [208](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/208)
8
+ - **Breaking:** Send marketing templates through the Marketing Messages API via `messages.send_marketing_template`, and expose `message_status` on message responses. `send_template` now raises on a blank `language` and when both `components` and `components_json` are given @oitedi [207](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/207)
9
+ - Add explicit WhatsApp Flow management operations through `client.flows` (`list`, `get`, `create`, `upload_json`, `publish`, `assets`) @oitedi [206](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/206)
10
+ - Configure and reuse the HTTP transport per client: connection reuse per origin, configurable `adapter`, `request_options`, `multipart_request_options`, and `middleware`, plus `Client#close` @oitedi [205](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/205)
11
+ - Allow callers to inspect the complete HTTP response with `raw_response: true` @oitedi [203](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/203)
12
+ - Stream upload session files and close them after requests @guizaols [202](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/202)
13
+ - Document public SDK contracts with YARD @guizaols [201](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/201)
14
+
3
15
  # v 1.2.0
4
16
  - Expose Graph media upload sessions through the configured client @oitedi [199](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/199)
5
17
  - Support BSUID recipients and preserve user IDs in message responses @oitedi [198](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/198)
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- whatsapp_sdk (1.2.0)
4
+ whatsapp_sdk (2.0.0)
5
5
  faraday (~> 2.0, > 2.0.1)
6
6
  faraday-multipart (~> 1)
7
7
  zeitwerk (~> 2)
@@ -9,7 +9,7 @@ PATH
9
9
  GEM
10
10
  remote: https://rubygems.org/
11
11
  specs:
12
- addressable (2.9.0)
12
+ addressable (2.9.1)
13
13
  public_suffix (>= 2.0.2, < 8.0)
14
14
  ast (2.4.2)
15
15
  base64 (0.2.0)
@@ -43,7 +43,7 @@ GEM
43
43
  pry (>= 0.9.10, < 0.15)
44
44
  public_suffix (5.1.1)
45
45
  rainbow (3.1.1)
46
- rake (12.3.3)
46
+ rake (13.4.2)
47
47
  regexp_parser (2.5.0)
48
48
  rexml (3.4.2)
49
49
  rubocop (1.30.1)
@@ -89,7 +89,7 @@ DEPENDENCIES
89
89
  mocha
90
90
  pry
91
91
  pry-nav
92
- rake (~> 12.3)
92
+ rake (~> 13.0)
93
93
  rubocop
94
94
  rubocop-minitest
95
95
  rubocop-performance
data/README.md CHANGED
@@ -99,6 +99,55 @@ logger_options = { bodies: true }
99
99
  client = WhatsappSdk::Api::Client.new("<ACCESS TOKEN>", "<API VERSION>", logger, logger_options)
100
100
  ```
101
101
 
102
+ Clients reuse Faraday connections per host and multipart mode. To use persistent
103
+ HTTP connections, install `faraday-net_http_persistent` in your application and require
104
+ it before selecting the adapter:
105
+
106
+ ```ruby
107
+ require "faraday/net_http_persistent"
108
+
109
+ client = WhatsappSdk::Api::Client.new(
110
+ "<ACCESS TOKEN>", "v25.0",
111
+ adapter: :net_http_persistent,
112
+ request_options: { open_timeout: 5, timeout: 15 },
113
+ multipart_request_options: { timeout: 60 }
114
+ )
115
+ # Make requests with this client. At shutdown, when no request is running, release its connections.
116
+ client.close
117
+ ```
118
+
119
+ The default adapter and its timeout defaults are unchanged. These options apply to
120
+ Faraday API requests; `download_file` uses Net::HTTP separately. The SDK does not
121
+ retry requests automatically. Each client keeps its own token and connection cache.
122
+
123
+ To add Faraday middleware, such as `faraday-retry`, pass `middleware:`. It is called
124
+ with each new Faraday builder, before the adapter is set:
125
+
126
+ ```ruby
127
+ require "faraday/retry"
128
+
129
+ client = WhatsappSdk::Api::Client.new(
130
+ "<ACCESS TOKEN>", "v25.0",
131
+ middleware: ->(builder) { builder.request(:retry, max: 2) }
132
+ )
133
+ ```
134
+
135
+ The same options work with the global configuration, which shares one client across
136
+ API objects. `Client.new` also uses them as defaults, so clients built without these
137
+ keywords get the configured transport:
138
+
139
+ ```ruby
140
+ WhatsappSdk.configure do |config|
141
+ config.access_token = "<ACCESS TOKEN>"
142
+ config.adapter = :net_http_persistent
143
+ config.request_options = { open_timeout: 5, timeout: 15 }
144
+ config.middleware = ->(builder) { builder.request(:retry, max: 2) }
145
+ end
146
+ ```
147
+
148
+ Hash settings are stored frozen. Assign a new hash to change them, so the shared
149
+ client is rebuilt; unknown request options raise `ArgumentError` when assigned.
150
+
102
151
  ## Set up a Meta app
103
152
 
104
153
  <details><summary>1) Create a Meta Business app </summary>
@@ -266,6 +315,39 @@ client.phone_numbers.deregister_number(SENDER_ID)
266
315
 
267
316
  </details>
268
317
 
318
+ ### Onboard a phone number
319
+
320
+ ```ruby
321
+ phone = client.phone_numbers.add(
322
+ business_id: WABA_ID, country_code: "55", phone_number: "11999999999", verified_name: "Example Store"
323
+ )
324
+ client.phone_numbers.request_code(phone_number_id: phone.id, code_method: "SMS", language: "pt_BR")
325
+ client.phone_numbers.verify_code(phone_number_id: phone.id, code: "001234")
326
+ client.phone_numbers.register_number(phone.id, "123456")
327
+ client.business_accounts.subscribe_app(business_id: WABA_ID)
328
+ ```
329
+
330
+ Each call is explicit. Adding a number does not request a code, verify it, or register it.
331
+ Code delivery accepts `SMS` or `VOICE` and is not retried automatically. Account permissions,
332
+ onboarding state, and storage of identifiers remain the application's responsibility.
333
+ See [Meta onboarding](https://developers.facebook.com/documentation/business-messaging/whatsapp/embedded-signup/onboarding-customers-as-a-tech-provider/).
334
+
335
+ Configure the public key used by a phone number's Flow data exchange endpoint:
336
+
337
+ ```ruby
338
+ client.phone_numbers.set_public_key(phone_number_id: PHONE_NUMBER_ID,
339
+ business_public_key: File.read("public.pem"))
340
+ key = client.phone_numbers.get_public_key(phone_number_id: PHONE_NUMBER_ID)
341
+ key.dig("data", 0, "business_public_key_signature_status") # VALID or MISMATCH
342
+ ```
343
+
344
+ Pass the PEM text of a 2048-bit RSA public key. Private key storage and request decryption
345
+ remain in your application. See [Meta's encryption setup](https://developers.facebook.com/documentation/business-messaging/whatsapp/flows/guides/whatsapp-business-encryption).
346
+
347
+ The onboarding operations (`phone_numbers.add`, `request_code`, `verify_code`, `register_number`,
348
+ `business_accounts.subscribe_app`) and `phone_numbers.set_public_key` also accept `raw_response: true`,
349
+ which returns the unmodified `Faraday::Response`. Their default return values stay the same.
350
+
269
351
  ### Media API
270
352
 
271
353
  <details>
@@ -583,6 +665,68 @@ selected destinations raise `WhatsappSdk::Resource::Errors::MissingArgumentError
583
665
  Authentication templates require a phone number; the SDK does not infer template category from its name or buttons.
584
666
  See [Meta's BSUID documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/).
585
667
 
668
+ ### Send marketing templates
669
+
670
+ ```ruby
671
+ response = client.messages.send_marketing_template(
672
+ sender_id: SENDER_ID, recipient_number: RECIPIENT_NUMBER,
673
+ name: "special_offer", language: "en_US", components_json: [],
674
+ product_policy: "STRICT"
675
+ )
676
+ response.messages.first.id
677
+ response.messages.first.message_status # Present only when returned by Meta.
678
+ ```
679
+
680
+ This explicitly calls `/marketing_messages`; ordinary `send_template` continues to
681
+ call `/messages`. Use `recipient:` for a BSUID when no phone number is available;
682
+ a supplied phone number takes precedence. Meta disables delivery optimization for
683
+ BSUID sends and rejects templates using `bid_spec` for those recipients.
684
+
685
+ `product_policy: "CLOUD_API_FALLBACK"` asks Meta to handle fallback; `"STRICT"` forbids
686
+ it; symbols and lowercase are accepted. Pass `message_activity_sharing: true` or `false`
687
+ to set Meta's activity sharing; omitting either option leaves Meta's default unchanged. The SDK never retries a
688
+ failed send or sends a second request to `/messages` after a timeout. Template
689
+ category and account eligibility are enforced by Meta, not inferred from names.
690
+ See [Marketing Messages](https://developers.facebook.com/documentation/business-messaging/whatsapp/marketing-messages/send-marketing-messages/).
691
+
692
+ ### Inspect the complete HTTP response
693
+
694
+ ```ruby
695
+ response = client.send_request(endpoint: "#{SENDER_ID}/messages", params: message_payload,
696
+ headers: { "Content-Type" => "application/json" }, raw_response: true)
697
+ response.status
698
+ response.headers
699
+ response.body
700
+ ```
701
+
702
+ `raw_response: true` returns the Faraday response unchanged, including empty or non-JSON
703
+ error bodies. The caller must check the HTTP status and parse the body. The default mode
704
+ returns parsed JSON and raises `HttpResponseError` for Graph API errors and for any HTTP status of 400 or above. Transport exceptions still propagate.
705
+
706
+ ### Manage WhatsApp Flows
707
+
708
+ ```ruby
709
+ page = client.flows.list(business_id: WABA_ID, limit: 20, fields: %w[id name status])
710
+ page.records # Raw Flow hashes; use page.after as the after: cursor for the next page.
711
+ flow = client.flows.create(business_id: WABA_ID, name: "Customer survey", categories: ["SURVEY"])
712
+ validation = client.flows.upload_json(flow_id: flow["id"], file_path: "flow.json")
713
+ details = client.flows.get(flow_id: flow["id"], fields: %w[id status validation_errors])
714
+ # Inspect validation errors and review the draft before publishing explicitly.
715
+ client.flows.publish(flow_id: flow["id"])
716
+ ```
717
+
718
+ Creation leaves the Flow in draft status. Upload returns Graph's raw response, including
719
+ `validation_errors` even when `success` is true. Individual calls do not retry or publish
720
+ implicitly. Business templates, draft recovery, and data exchange endpoint encryption
721
+ remain in the application. See the [Flows API reference](https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi).
722
+
723
+ List the assets uploaded to a Flow:
724
+
725
+ ```ruby
726
+ assets = client.flows.assets(flow_id: flow["id"], limit: 20)
727
+ assets.records # Raw asset hashes with name, asset_type, and download_url; no automatic download.
728
+ ```
729
+
586
730
  ## Development
587
731
 
588
732
  After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests.
@@ -5,6 +5,9 @@ require_relative "../resource/business_account"
5
5
 
6
6
  module WhatsappSdk
7
7
  module Api
8
+ # Reads and updates WhatsApp Business Accounts through the configured client.
9
+ # @see Client#business_accounts
10
+ # @see Resource::BusinessAccount
8
11
  class BusinessAccount < Request
9
12
  DEFAULT_FIELDS = %w[id name timezone_id message_template_namespace account_review_status
10
13
  business_verification_status country ownership_type primary_business_location]
@@ -31,6 +34,18 @@ module WhatsappSdk
31
34
  Resource::BusinessAccount.from_hash(response)
32
35
  end
33
36
 
37
+ # Subscribe the authenticated app to webhook events for a WABA.
38
+ # @param business_id [String, Integer] WhatsApp Business Account ID.
39
+ # @return [Boolean] Whether the subscription succeeded.
40
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
41
+ def subscribe_app(business_id:, raw_response: false)
42
+ response = send_request(endpoint: "#{business_id}/subscribed_apps",
43
+ **(raw_response ? { raw_response: true } : {}))
44
+ return response if raw_response
45
+
46
+ Responses::SuccessResponse.success_response?(response: response)
47
+ end
48
+
34
49
  # Update the details of business account.
35
50
  #
36
51
  # @param business_id [Integer] Business Account Id.
@@ -7,26 +7,65 @@ module WhatsappSdk
7
7
  module Api
8
8
  class Client
9
9
  API_VERSIONS = [
10
- 'v25.0', 'v24.0', 'v23.0', 'v22.0', 'v21.0', 'v20.0', 'v19.0', 'v18.0', 'v17.0', 'v16.0', 'v15.0', 'v14.0',
11
- 'v13.0', 'v12.0', 'v11.0', 'v10.0', 'v9.0', 'v8.0', 'v7.0', 'v6.0', 'v5.0', 'v4.0',
10
+ 'v27.0', 'v26.0', 'v25.0', 'v24.0', 'v23.0', 'v22.0', 'v21.0', 'v20.0', 'v19.0', 'v18.0', 'v17.0', 'v16.0',
11
+ 'v15.0', 'v14.0', 'v13.0', 'v12.0', 'v11.0', 'v10.0', 'v9.0', 'v8.0', 'v7.0', 'v6.0', 'v5.0', 'v4.0',
12
12
  'v3.3', 'v3.2', 'v3.1', 'v3.0', 'v2.12', 'v2.11', 'v2.10', 'v2.9', 'v2.8', 'v2.7',
13
13
  'v2.6', 'v2.5', 'v2.4', 'v2.3', 'v2.2', 'v2.1'
14
14
  ].freeze
15
-
15
+ LOGGER_OPTION_KEYS = %i[headers bodies errors log_level formatter].freeze
16
+
17
+ # @param access_token [String, nil] Token used by this client.
18
+ # @param api_version [String] Graph API version.
19
+ # @param logger [Logger, nil] Optional Faraday logger.
20
+ # @param logger_options [Hash] Faraday logging options.
21
+ # Transport keywords default to WhatsappSdk.configuration, like access_token and api_version.
22
+ # @param adapter [Symbol, Class, nil] Faraday adapter; nil means Faraday.default_adapter at connection build.
23
+ # Require optional adapters before constructing the client.
24
+ # @param request_options [Hash] Faraday request options, such as open_timeout and timeout in seconds.
25
+ # @param multipart_request_options [Hash] Overrides applied only to multipart requests.
26
+ # @param middleware [Proc, nil] Called with each new Faraday builder to add middleware, such as faraday-retry.
27
+ # @param legacy_logger_options [Hash] Logger options supplied as keywords. With a logger, every key is passed to
28
+ # Faraday's logger, so custom formatter options keep working. Without one, only logger keys are accepted.
29
+ # @raise [ArgumentError] If a keyword, request option, or API version is unsupported.
16
30
  def initialize(
17
31
  access_token = WhatsappSdk.configuration.access_token,
18
32
  api_version = WhatsappSdk.configuration.api_version,
19
33
  logger = nil,
20
- logger_options = {}
34
+ logger_options = {},
35
+ adapter: WhatsappSdk.configuration.adapter,
36
+ request_options: WhatsappSdk.configuration.request_options,
37
+ multipart_request_options: WhatsappSdk.configuration.multipart_request_options,
38
+ middleware: WhatsappSdk.configuration.middleware,
39
+ **legacy_logger_options
21
40
  )
41
+ # Ruby 2.x turns a positional logger_options hash into keywords, so with a logger every key is a logger option.
42
+ unknown_options = logger ? [] : legacy_logger_options.keys - LOGGER_OPTION_KEYS
43
+ raise ArgumentError, "Unknown keyword(s): #{unknown_options.join(', ')}" unless unknown_options.empty?
44
+
45
+ self.class.validate_request_options(request_options)
46
+ self.class.validate_request_options(multipart_request_options)
47
+
22
48
  @access_token = access_token
23
49
  @logger = logger
24
- @logger_options = logger_options
50
+ @logger_options = (logger_options || {}).merge(legacy_logger_options)
51
+ @adapter = adapter
52
+ @request_options = request_options.dup.freeze
53
+ @multipart_request_options = multipart_request_options.dup.freeze
54
+ @middleware = middleware
55
+ @connections = {}
56
+ @connections_mutex = Mutex.new
25
57
 
26
58
  validate_api_version(api_version)
27
59
  @api_version = api_version
28
60
  end
29
61
 
62
+ # @api private
63
+ # @raise [ArgumentError] If a key is not a Faraday request option.
64
+ def self.validate_request_options(options)
65
+ unknown = options.keys.map(&:to_sym) - ::Faraday::RequestOptions.members
66
+ raise ArgumentError, "Unknown request option(s): #{unknown.join(', ')}" unless unknown.empty?
67
+ end
68
+
30
69
  def media
31
70
  @media ||= WhatsappSdk::Api::Medias.new(self)
32
71
  end
@@ -43,24 +82,37 @@ module WhatsappSdk
43
82
  @business_profiles ||= WhatsappSdk::Api::BusinessProfile.new(self)
44
83
  end
45
84
 
85
+ # Access business account operations using this client's configuration.
86
+ #
87
+ # @return [Api::BusinessAccount] Cached business account API accessor.
46
88
  def business_accounts
47
89
  @business_accounts ||= WhatsappSdk::Api::BusinessAccount.new(self)
48
90
  end
49
91
 
92
+ # @return [Api::Flows] Flow management using this client's configuration.
93
+ def flows
94
+ @flows ||= WhatsappSdk::Api::Flows.new(self)
95
+ end
96
+
50
97
  def templates
51
98
  @templates ||= WhatsappSdk::Api::Templates.new(self)
52
99
  end
53
100
 
54
- def send_request(endpoint: "", full_url: nil, http_method: "post", params: {}, headers: {}, multipart: false)
55
- url = full_url || "#{ApiConfiguration::API_URL}/#{@api_version}/"
101
+ # @param raw_response [Boolean] Return the Faraday response without JSON parsing or HTTP error raising.
102
+ # @return [Hash, Array, nil, Faraday::Response] Parsed JSON, or the unmodified HTTP response when requested.
103
+ # @raise [Api::Responses::HttpResponseError] For HTTP or Graph errors in the default parsed mode.
104
+ def send_request(endpoint: "", full_url: nil, http_method: "post", params: {}, headers: {}, multipart: false,
105
+ raw_response: false)
106
+ url = request_url(full_url || "#{ApiConfiguration::API_URL}/#{@api_version}/", endpoint)
56
107
 
57
- faraday_request = faraday(url: url, multipart: multipart)
108
+ response = connection_for(url, multipart).public_send(http_method, url.to_s, request_params(params, headers),
109
+ headers)
58
110
 
59
- response = faraday_request.public_send(http_method, endpoint, request_params(params, headers), headers)
111
+ return response if raw_response
60
112
 
61
113
  parsed_body = parse_response_body(response.body)
62
114
 
63
- if response.status > 499 || Api::Responses::GenericErrorResponse.response_error?(response: parsed_body)
115
+ if response.status >= 400 || Api::Responses::GenericErrorResponse.response_error?(response: parsed_body)
64
116
  raise Api::Responses::HttpResponseError.new(http_status: response.status, body: parsed_body)
65
117
  end
66
118
 
@@ -83,6 +135,23 @@ module WhatsappSdk
83
135
  response
84
136
  end
85
137
 
138
+ # Close cached Faraday connections, for example at shutdown. Call it when no request is running on this
139
+ # client: it does not wait for in-flight requests. Later requests create fresh connections.
140
+ # @return [void]
141
+ # @raise [StandardError] The first adapter error, after all connections have been closed or attempted.
142
+ def close
143
+ connections = @connections_mutex.synchronize do
144
+ @connections.values.tap { @connections.clear }
145
+ end
146
+ error = nil
147
+ connections.each do |connection|
148
+ connection.close
149
+ rescue StandardError => e
150
+ error ||= e
151
+ end
152
+ raise error if error
153
+ end
154
+
86
155
  private
87
156
 
88
157
  def parse_response_body(body)
@@ -97,11 +166,37 @@ module WhatsappSdk
97
166
  params
98
167
  end
99
168
 
100
- def faraday(url:, multipart: false)
101
- ::Faraday.new(url) do |client|
169
+ # Same join rules as Faraday::Connection#build_exclusive_url (copied from Faraday 2.14.1), so endpoints like
170
+ # "./upload:abc" stay relative.
171
+ def request_url(base_url, endpoint)
172
+ base = URI(base_url)
173
+ return base if endpoint.nil? || endpoint.empty?
174
+
175
+ base.path += '/' unless base.path.end_with?('/')
176
+ if !endpoint.start_with?('http://', 'https://', '/', './', '../') || endpoint.start_with?('//')
177
+ endpoint = "./#{endpoint}"
178
+ end
179
+ url = base + endpoint
180
+ url.query ||= base.query
181
+ url
182
+ end
183
+
184
+ # Connections are cached per origin, so paging URLs and API versions share one pool.
185
+ def connection_for(url, multipart)
186
+ origin = "#{url.scheme}://#{url.host}:#{url.port}"
187
+ @connections_mutex.synchronize do
188
+ # Faraday also builds its adapter lazily; initialize it before sharing the connection.
189
+ @connections[[origin, multipart]] ||= build_faraday(origin, multipart).tap(&:app)
190
+ end
191
+ end
192
+
193
+ def build_faraday(url, multipart)
194
+ options = multipart ? @request_options.merge(@multipart_request_options) : @request_options
195
+ ::Faraday.new(url, request: options) do |client|
102
196
  client.request(:multipart) if multipart
103
197
  client.request(:url_encoded)
104
- client.adapter(::Faraday.default_adapter)
198
+ @middleware&.call(client)
199
+ client.adapter(@adapter || ::Faraday.default_adapter)
105
200
  client.headers['Authorization'] = "Bearer #{@access_token}" unless @access_token.nil?
106
201
  client.response(:logger, @logger, @logger_options) unless @logger.nil?
107
202
  end
@@ -0,0 +1,95 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'request'
4
+
5
+ module WhatsappSdk
6
+ module Api
7
+ # Manage Flow drafts and publish them explicitly through the configured client.
8
+ # @see https://developers.facebook.com/docs/whatsapp/flows/reference/flowsapi
9
+ class Flows < Request
10
+ # @param business_id [String, Integer] WhatsApp Business Account ID.
11
+ # @param limit [Integer] Maximum records per page.
12
+ # @param after [String, nil] Cursor from the previous page.
13
+ # @param fields [Array<String>, nil] Optional Graph fields to retrieve.
14
+ # @return [Responses::PaginationRecords] Page containing raw Flow hashes and cursors.
15
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
16
+ def list(business_id:, limit: 100, after: nil, fields: nil)
17
+ params = { limit: limit }
18
+ params[:after] = after if after
19
+ params[:fields] = fields.join(',') if fields
20
+ response = send_request(endpoint: "#{business_id}/flows", http_method: 'get', params: params)
21
+
22
+ Responses::PaginationRecords.new(
23
+ records: response['data'],
24
+ before: response.dig('paging', 'cursors', 'before'),
25
+ after: response.dig('paging', 'cursors', 'after')
26
+ )
27
+ end
28
+
29
+ # @param flow_id [String, Integer] Flow ID.
30
+ # @param fields [Array<String>, nil] Fields to retrieve; nil uses Graph's default fields.
31
+ # @return [Hash] Raw Flow details, including status and validation errors.
32
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
33
+ def get(flow_id:, fields: nil)
34
+ params = fields ? { fields: fields.join(',') } : {}
35
+ send_request(endpoint: flow_id.to_s, http_method: 'get', params: params)
36
+ end
37
+
38
+ # Create a draft; upload_json and publish are separate, explicit operations.
39
+ # @param business_id [String, Integer] WhatsApp Business Account ID.
40
+ # @param name [String] Flow name.
41
+ # @param categories [Array<String>] Flow categories accepted by Graph, such as SURVEY.
42
+ # @param endpoint_uri [String, nil] Optional data exchange endpoint URL.
43
+ # @return [Hash] Raw creation response, including id and any validation errors.
44
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
45
+ def create(business_id:, name:, categories:, endpoint_uri: nil)
46
+ params = { name: name, categories: categories }
47
+ params[:endpoint_uri] = endpoint_uri if endpoint_uri
48
+ send_request(endpoint: "#{business_id}/flows", params: params,
49
+ headers: { 'Content-Type' => 'application/json' })
50
+ end
51
+
52
+ # List assets without downloading their contents.
53
+ # @param flow_id [String, Integer] Flow ID.
54
+ # @param limit [Integer] Maximum records per page.
55
+ # @param after [String, nil] Cursor from the previous page.
56
+ # @return [Responses::PaginationRecords] Page of raw asset hashes, including download_url, and cursors.
57
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
58
+ def assets(flow_id:, limit: 100, after: nil)
59
+ params = { limit: limit }
60
+ params[:after] = after if after
61
+ response = send_request(endpoint: "#{flow_id}/assets", http_method: 'get', params: params)
62
+
63
+ Responses::PaginationRecords.new(
64
+ records: response['data'],
65
+ before: response.dig('paging', 'cursors', 'before'),
66
+ after: response.dig('paging', 'cursors', 'after')
67
+ )
68
+ end
69
+
70
+ # Upload Flow JSON as multipart data. The file is closed after the request, including on errors.
71
+ # @param flow_id [String, Integer] Draft Flow ID.
72
+ # @param file_path [String] Path to the Flow JSON file.
73
+ # @return [Hash] Raw response; inspect validation_errors even when success is true.
74
+ # @raise [Medias::FileNotFoundError] If the path does not identify a regular file.
75
+ # @raise [SystemCallError] If the file cannot be opened or read.
76
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
77
+ def upload_json(flow_id:, file_path:)
78
+ raise Medias::FileNotFoundError.new(file_path: file_path) unless File.file?(file_path)
79
+
80
+ File.open(file_path, 'rb') do |file|
81
+ params = { name: 'flow.json', asset_type: 'FLOW_JSON',
82
+ file: Faraday::FilePart.new(file, 'application/json', 'flow.json') }
83
+ send_request(endpoint: "#{flow_id}/assets", params: params, multipart: true)
84
+ end
85
+ end
86
+
87
+ # @param flow_id [String, Integer] Draft Flow ID to publish.
88
+ # @return [Hash] Raw publish response containing success.
89
+ # @raise [Responses::HttpResponseError] If Graph rejects publication.
90
+ def publish(flow_id:)
91
+ send_request(endpoint: "#{flow_id}/publish")
92
+ end
93
+ end
94
+ end
95
+ end
@@ -120,6 +120,15 @@ module WhatsappSdk
120
120
  # Create a Graph upload session for template media or a business profile photo.
121
121
  # Returns the raw response containing the upload session "id".
122
122
  # Uses the client's API version and token unless access_token is supplied.
123
+ #
124
+ # @param app_id [String, Integer] Meta app ID that owns the upload session.
125
+ # @param file_path [String] Path to the local file whose name and size are sent.
126
+ # @param type [String] File MIME type, such as image/jpeg.
127
+ # @param access_token [String, nil] Token override; nil uses the client's token.
128
+ # @return [Hash] Raw Graph response containing the upload session "id".
129
+ # @raise [FileNotFoundError] If file_path does not identify a regular file.
130
+ # @raise [Api::Responses::HttpResponseError] If Graph returns an API error or a server error.
131
+ # @raise [SystemCallError] If the file metadata cannot be read.
123
132
  def create_upload_session(app_id:, file_path:, type:, access_token: nil)
124
133
  raise FileNotFoundError.new(file_path: file_path) unless File.file?(file_path)
125
134
 
@@ -135,13 +144,23 @@ module WhatsappSdk
135
144
  # Upload the complete file to a Graph upload session, starting at offset zero.
136
145
  # Returns the raw response containing the reusable media handle "h".
137
146
  # This does not resume partial uploads or retry failed requests.
147
+ #
148
+ # @param session_id [String] Upload session ID returned by create_upload_session, including any signature.
149
+ # @param file_path [String] Path to the local file to upload in full.
150
+ # @param access_token [String, nil] Token override; nil uses the client's token.
151
+ # @return [Hash] Raw Graph response containing the reusable media handle "h".
152
+ # @raise [FileNotFoundError] If file_path does not identify a regular file.
153
+ # @raise [Api::Responses::HttpResponseError] If Graph returns an API error or a server error.
154
+ # @raise [SystemCallError] If the file cannot be read.
138
155
  def upload_file_to_session(session_id:, file_path:, access_token: nil)
139
156
  raise FileNotFoundError.new(file_path: file_path) unless File.file?(file_path)
140
157
 
141
158
  headers = { 'Content-Type' => 'application/octet-stream', 'file_offset' => '0' }
142
159
  headers['Authorization'] = "Bearer #{access_token}" if access_token
143
- # ponytail: buffers the whole file; stream bytes if large uploads become a requirement.
144
- send_request(endpoint: "./#{session_id}", params: File.binread(file_path), headers: headers)
160
+ File.open(file_path, 'rb') do |file|
161
+ headers['Content-Length'] = file.size.to_s
162
+ send_request(endpoint: "./#{session_id}", params: file, headers: headers)
163
+ end
145
164
  end
146
165
 
147
166
  private
@@ -373,31 +373,13 @@ module WhatsappSdk
373
373
  # @param recipient [String] Recipient' Business-Scoped User ID (BSUID). Optional alternative to recipient_number.
374
374
  # Not allowed for authentication templates.
375
375
  # @return [MessageDataResponse] Response object.
376
+ # @raise [Resource::Errors::MissingArgumentError] If language, components or a destination are missing.
377
+ # @raise [ArgumentError] If both components and components_json are given.
376
378
  def send_template(
377
379
  sender_id:, name:, language:, recipient_number: nil, components: nil, components_json: nil, recipient: nil
378
380
  )
379
- if !components && !components_json
380
- raise Resource::Errors::MissingArgumentError,
381
- "components or components_json is required"
382
- end
383
-
384
- params = {
385
- messaging_product: "whatsapp",
386
- recipient_type: "individual",
387
- to: recipient_number,
388
- type: "template",
389
- template: {
390
- name: name
391
- }
392
- }
393
-
394
- params[:template][:language] = { code: language } if language
395
- params[:template][:components] = if components.nil?
396
- components_json
397
- else
398
- components.map(&:to_json)
399
- end
400
- apply_recipient!(params, recipient_number, recipient)
381
+ params = template_params(name: name, language: language, recipient_number: recipient_number,
382
+ components: components, components_json: components_json, recipient: recipient)
401
383
 
402
384
  response = send_request(
403
385
  endpoint: endpoint(sender_id),
@@ -408,6 +390,35 @@ module WhatsappSdk
408
390
  Api::Responses::MessageDataResponse.build_from_response(response: response)
409
391
  end
410
392
 
393
+ # Send an approved marketing template via Marketing Messages API.
394
+ # @param sender_id [String, Integer] Business phone number ID.
395
+ # @param name [String] Approved marketing template name.
396
+ # @param language [String] Template language code.
397
+ # @param recipient_number [String, Integer, nil] Phone number; takes precedence over recipient.
398
+ # @param components [Array<Resource::Component>, nil] Template component objects.
399
+ # @param components_json [Array<Hash>, nil] Raw components; use [] for a template without parameters.
400
+ # @param recipient [String, nil] BSUID or parent BSUID, used when the phone number is omitted.
401
+ # @param product_policy [String, Symbol, nil] STRICT or CLOUD_API_FALLBACK (any case); nil leaves it to Meta.
402
+ # @param message_activity_sharing [Boolean, nil] Turns message activity sharing on or off; nil leaves it to Meta.
403
+ # @return [Api::Responses::MessageDataResponse] IDs, contacts, and any message_status returned by Meta.
404
+ # @raise [Resource::Errors::MissingArgumentError] If language, components or a destination are missing.
405
+ # @raise [ArgumentError] If both components and components_json are given.
406
+ # @raise [Api::Responses::HttpResponseError] If Meta rejects the message.
407
+ def send_marketing_template(
408
+ sender_id:, name:, language:, recipient_number: nil, components: nil, components_json: nil, recipient: nil,
409
+ product_policy: nil, message_activity_sharing: nil, raw_response: false
410
+ )
411
+ params = template_params(name: name, language: language, recipient_number: recipient_number,
412
+ components: components, components_json: components_json, recipient: recipient)
413
+ params[:product_policy] = product_policy.to_s.upcase unless product_policy.nil?
414
+ params[:message_activity_sharing] = message_activity_sharing unless message_activity_sharing.nil?
415
+ response = send_request(endpoint: marketing_endpoint(sender_id), params: params, headers: DEFAULT_HEADERS,
416
+ **(raw_response ? { raw_response: true } : {}))
417
+ return response if raw_response
418
+
419
+ Api::Responses::MessageDataResponse.build_from_response(response: response)
420
+ end
421
+
411
422
  # Send reaction
412
423
  #
413
424
  # @param sender_id [Integer] Sender' phone number.
@@ -465,10 +476,45 @@ module WhatsappSdk
465
476
 
466
477
  private
467
478
 
479
+ def template_params(name:, language:, recipient_number:, components:, components_json:, recipient:)
480
+ validate_template_args!(language, components, components_json)
481
+
482
+ params = {
483
+ messaging_product: "whatsapp",
484
+ recipient_type: "individual",
485
+ to: recipient_number,
486
+ type: "template",
487
+ template: {
488
+ name: name
489
+ }
490
+ }
491
+
492
+ params[:template][:language] = { code: language }
493
+ params[:template][:components] = if components.nil?
494
+ components_json
495
+ else
496
+ components.map(&:to_json)
497
+ end
498
+ apply_recipient!(params, recipient_number, recipient)
499
+ end
500
+
501
+ def validate_template_args!(language, components, components_json)
502
+ if !components && !components_json
503
+ raise Resource::Errors::MissingArgumentError,
504
+ "components or components_json is required"
505
+ end
506
+ raise ArgumentError, "pass components or components_json, not both" if components && components_json
507
+ raise Resource::Errors::MissingArgumentError, "language is required" if language.to_s.strip.empty?
508
+ end
509
+
468
510
  def endpoint(sender_id)
469
511
  "#{sender_id}/messages"
470
512
  end
471
513
 
514
+ def marketing_endpoint(sender_id)
515
+ "#{sender_id}/marketing_messages"
516
+ end
517
+
472
518
  # Applies the destination to the payload.
473
519
  # - Phone send (recipient_number present): keeps `to`, never adds `recipient` — payload is
474
520
  # identical to the pre-BSUID behavior.
@@ -41,17 +41,74 @@ module WhatsappSdk
41
41
  Resource::PhoneNumber.from_hash(response)
42
42
  end
43
43
 
44
+ # Add a phone number to a WABA. Verification and registration are separate calls.
45
+ # @param business_id [String, Integer] WhatsApp Business Account ID.
46
+ # @param country_code [String] Country calling code, without the plus sign.
47
+ # @param phone_number [String] Phone number forwarded unchanged to Graph.
48
+ # @param verified_name [String] Business display name submitted for review.
49
+ # @return [Responses::IdResponse] Created phone number ID.
50
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
51
+ def add(business_id:, country_code:, phone_number:, verified_name:, raw_response: false)
52
+ response = send_request(
53
+ endpoint: "#{business_id}/phone_numbers",
54
+ params: { cc: country_code, phone_number: phone_number, verified_name: verified_name },
55
+ headers: { 'Content-Type' => 'application/json' },
56
+ **(raw_response ? { raw_response: true } : {})
57
+ )
58
+ return response if raw_response
59
+
60
+ Responses::IdResponse.new(response['id'])
61
+ end
62
+
63
+ # Request a verification code without automatically verifying or registering the number.
64
+ # @param phone_number_id [String, Integer] Phone number ID.
65
+ # @param code_method [String] SMS or VOICE.
66
+ # @param language [String] Locale for code delivery, such as en_US.
67
+ # @return [Boolean] Whether Graph accepted the request.
68
+ # @raise [ArgumentError] If code_method is unsupported.
69
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
70
+ def request_code(phone_number_id:, code_method:, language:, raw_response: false)
71
+ raise ArgumentError, 'code_method must be SMS or VOICE' unless %w[SMS VOICE].include?(code_method)
72
+
73
+ response = send_request(
74
+ endpoint: "#{phone_number_id}/request_code", params: { code_method: code_method, language: language },
75
+ headers: { 'Content-Type' => 'application/json' },
76
+ **(raw_response ? { raw_response: true } : {})
77
+ )
78
+ return response if raw_response
79
+
80
+ Responses::SuccessResponse.success_response?(response: response)
81
+ end
82
+
83
+ # Verify ownership of a phone number. Register it separately with register_number.
84
+ # @param phone_number_id [String, Integer] Phone number ID.
85
+ # @param code [String] Verification code; pass a string to preserve leading zeroes.
86
+ # @return [Boolean] Whether verification succeeded.
87
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
88
+ def verify_code(phone_number_id:, code:, raw_response: false)
89
+ response = send_request(
90
+ endpoint: "#{phone_number_id}/verify_code", params: { code: code },
91
+ headers: { 'Content-Type' => 'application/json' },
92
+ **(raw_response ? { raw_response: true } : {})
93
+ )
94
+ return response if raw_response
95
+
96
+ Responses::SuccessResponse.success_response?(response: response)
97
+ end
98
+
44
99
  # Register a phone number.
45
100
  #
46
101
  # @param phone_number_id [Integer] The registered number we want to retrieve.
47
102
  # @param pin [Integer] Pin of 6 digits.
48
103
  # @return [Boolean] Whether the registration was successful.
49
- def register_number(phone_number_id, pin)
104
+ def register_number(phone_number_id, pin, raw_response: false)
50
105
  response = send_request(
51
106
  http_method: "post",
52
107
  endpoint: "#{phone_number_id}/register",
53
- params: { messaging_product: 'whatsapp', pin: pin }
108
+ params: { messaging_product: 'whatsapp', pin: pin },
109
+ **(raw_response ? { raw_response: true } : {})
54
110
  )
111
+ return response if raw_response
55
112
 
56
113
  Api::Responses::SuccessResponse.success_response?(response: response)
57
114
  end
@@ -70,6 +127,30 @@ module WhatsappSdk
70
127
  Api::Responses::SuccessResponse.success_response?(response: response)
71
128
  end
72
129
 
130
+ # Configure the public key used for Flow data exchange on this phone number.
131
+ # @param phone_number_id [String, Integer] Business phone number ID.
132
+ # @param business_public_key [String] PEM-encoded 2048-bit RSA public key, including newlines.
133
+ # @return [Boolean] Whether the key was accepted.
134
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
135
+ def set_public_key(phone_number_id:, business_public_key:, raw_response: false)
136
+ response = send_request(
137
+ endpoint: "#{phone_number_id}/whatsapp_business_encryption",
138
+ params: { business_public_key: business_public_key },
139
+ headers: { 'Content-Type' => 'application/x-www-form-urlencoded' },
140
+ **(raw_response ? { raw_response: true } : {})
141
+ )
142
+ return response if raw_response
143
+
144
+ Responses::SuccessResponse.success_response?(response: response)
145
+ end
146
+
147
+ # @param phone_number_id [String, Integer] Business phone number ID.
148
+ # @return [Hash] Raw Graph response; public key and signature status are nested in the data array.
149
+ # @raise [Responses::HttpResponseError] If Graph rejects the request.
150
+ def get_public_key(phone_number_id:)
151
+ send_request(endpoint: "#{phone_number_id}/whatsapp_business_encryption", http_method: 'get')
152
+ end
153
+
73
154
  # deprecated methods
74
155
  def registered_numbers(business_id)
75
156
  warn "[DEPRECATION] `registered_numbers` is deprecated. Please use `list` instead."
@@ -14,14 +14,16 @@ module WhatsappSdk
14
14
  @client.download_file(url: url, content_type_header: content_type_header, file_path: file_path)
15
15
  end
16
16
 
17
- def send_request(endpoint: nil, full_url: nil, http_method: "post", params: {}, headers: {}, multipart: false)
17
+ def send_request(endpoint: nil, full_url: nil, http_method: "post", params: {}, headers: {}, multipart: false,
18
+ raw_response: false)
18
19
  @client.send_request(
19
20
  http_method: http_method,
20
21
  full_url: full_url,
21
22
  endpoint: endpoint,
22
23
  params: params,
23
24
  headers: headers,
24
- multipart: multipart
25
+ multipart: multipart,
26
+ **(raw_response ? { raw_response: true } : {})
25
27
  )
26
28
  end
27
29
  end
@@ -23,7 +23,7 @@ module WhatsappSdk
23
23
  private
24
24
 
25
25
  def parse_message(message_json)
26
- Resource::Message.new(id: message_json["id"])
26
+ Resource::Message.new(id: message_json["id"], message_status: message_json["message_status"])
27
27
  end
28
28
 
29
29
  def parse_contact(contact_json)
@@ -83,10 +83,12 @@ module WhatsappSdk
83
83
  #
84
84
  # @param business_id [Integer] The business ID.
85
85
  # @param limit [Integer] Optional. Number of templates to return in a single page.
86
+ # @param after [String, nil] Optional. Cursor from the previous page; nil requests the first page.
86
87
  # @return [Template] Pagination Record containing an array of Template objects.
87
- def list(business_id:, limit: 100)
88
+ def list(business_id:, limit: 100, after: nil)
88
89
  params = {}
89
90
  params["limit"] = limit if limit
91
+ params["after"] = after if after
90
92
 
91
93
  response = send_request(
92
94
  endpoint: "#{business_id}/message_templates",
@@ -182,7 +184,12 @@ module WhatsappSdk
182
184
  # @param start_timestamp [Integer] The start of the time range to retrieve analytics data, in Unix timestamp.
183
185
  # @param end_timestamp [Integer] The end of the time range to retrieve analytics data, in Unix timestamp.
184
186
  # @param template_ids [Array<String>] An array of template IDs for which to retrieve analytics data.
185
- # @param metric_types [Array<String>] An array of metric types to retrieve.
187
+ # @param metric_types [Array<String>] Metric types to retrieve; defaults to an empty array.
188
+ # @param granularity [String] Aggregation interval; defaults to DAILY, the only supported value.
189
+ # @param after [String, nil] Cursor for the next page; nil requests the first page.
190
+ # @return [Api::Responses::PaginationRecords] Page of Resource::TemplateAnalytic records with pagination cursors.
191
+ # @raise [ArgumentError] If a metric type or granularity is unsupported.
192
+ # @raise [Api::Responses::HttpResponseError] If Graph returns an API error or a server error.
186
193
  def template_analytics(
187
194
  business_id:, start_timestamp:, end_timestamp:, template_ids:, metric_types: [],
188
195
  granularity: WhatsappSdk::Resource::TemplateAnalytic::Granularity::DAILY,
@@ -9,10 +9,27 @@ module WhatsappSdk
9
9
  #
10
10
  # The gem have access to the client through WhatsappSdk.configuration.client
11
11
  class Configuration
12
- attr_accessor :access_token, :api_version
12
+ SETTINGS = %i[access_token api_version logger logger_options adapter request_options
13
+ multipart_request_options middleware].freeze
14
+ # Stored frozen, so editing them in place raises instead of being ignored by the cached client.
15
+ HASH_SETTINGS = %i[logger_options request_options multipart_request_options].freeze
16
+ REQUEST_OPTION_SETTINGS = %i[request_options multipart_request_options].freeze
13
17
 
14
18
  # loggers like ActiveSupport::Logger (Rails.logger) is a subclass of Logger
15
- attr_accessor :logger, :logger_options
19
+ attr_reader(*SETTINGS)
20
+
21
+ # Changing a setting makes #client build a new client on its next call. The old client is not closed, because
22
+ # other threads may still be using it.
23
+ SETTINGS.each do |name|
24
+ define_method(:"#{name}=") do |value|
25
+ value = value.dup.freeze if HASH_SETTINGS.include?(name)
26
+ Api::Client.validate_request_options(value) if REQUEST_OPTION_SETTINGS.include?(name)
27
+ @mutex.synchronize do
28
+ @client = nil
29
+ instance_variable_set(:"@#{name}", value)
30
+ end
31
+ end
32
+ end
16
33
 
17
34
  def initialize(
18
35
  access_token = "",
@@ -23,11 +40,24 @@ module WhatsappSdk
23
40
  @access_token = access_token
24
41
  @api_version = api_version
25
42
  @logger = logger
26
- @logger_options = logger_options
43
+ @logger_options = logger_options.dup.freeze
44
+ @adapter = nil
45
+ @request_options = {}.freeze
46
+ @multipart_request_options = {}.freeze
47
+ @middleware = nil
48
+ @mutex = Mutex.new
27
49
  end
28
50
 
51
+ # One client is shared by every API object built from this configuration, so its connections are reused.
52
+ # @return [Api::Client]
29
53
  def client
30
- Api::Client.new(access_token, api_version, logger, logger_options)
54
+ @mutex.synchronize do
55
+ @client ||= Api::Client.new(
56
+ access_token, api_version, logger, logger_options,
57
+ adapter: adapter, request_options: request_options, multipart_request_options: multipart_request_options,
58
+ middleware: middleware
59
+ )
60
+ end
31
61
  end
32
62
  end
33
63
  end
@@ -2,11 +2,43 @@
2
2
 
3
3
  module WhatsappSdk
4
4
  module Resource
5
+ # WhatsApp Business Account fields returned by Graph.
6
+ # Values are retained without conversion; fields omitted from the response are nil.
5
7
  class BusinessAccount
8
+ # @!attribute [rw] id
9
+ # @return [String, nil] Business account ID.
10
+ # @!attribute [rw] name
11
+ # @return [String, nil] Business account name.
12
+ # @!attribute [rw] timezone_id
13
+ # @return [String, nil] Graph time zone identifier.
14
+ # @!attribute [rw] message_template_namespace
15
+ # @return [String, nil] Namespace used by the account's message templates.
16
+ # @!attribute [rw] account_review_status
17
+ # @return [String, nil] Account review status.
18
+ # @!attribute [rw] business_verification_status
19
+ # @return [String, nil] Business verification status.
20
+ # @!attribute [rw] country
21
+ # @return [String, nil] Account country code.
22
+ # @!attribute [rw] ownership_type
23
+ # @return [String, nil] Account ownership type.
24
+ # @!attribute [rw] primary_business_location
25
+ # @return [String, nil] Primary business location returned by Graph.
26
+ # @!attribute [rw] analytics
27
+ # @return [Hash, nil] Messaging analytics, when requested and returned.
28
+ # @!attribute [rw] conversation_analytics
29
+ # @return [Hash, nil] Conversation analytics, when requested and returned.
30
+ # @!attribute [rw] pricing_analytics
31
+ # @return [Hash, nil] Pricing analytics, when requested and returned.
32
+ # @!attribute [rw] call_analytics
33
+ # @return [Hash, nil] Call analytics, when requested and returned.
6
34
  attr_accessor :id, :name, :timezone_id, :message_template_namespace, :account_review_status,
7
35
  :business_verification_status, :country, :ownership_type, :primary_business_location,
8
36
  :analytics, :conversation_analytics, :pricing_analytics, :call_analytics
9
37
 
38
+ # Build an account from a Graph response without converting field values.
39
+ #
40
+ # @param hash [Hash{String => Object}] Account fields keyed by their Graph names.
41
+ # @return [BusinessAccount] Account with nil for any missing fields.
10
42
  def self.from_hash(hash)
11
43
  business_account = BusinessAccount.new
12
44
  business_account.id = hash["id"]
@@ -26,6 +58,10 @@ module WhatsappSdk
26
58
  business_account
27
59
  end
28
60
 
61
+ # Compare account details, excluding analytics fields.
62
+ #
63
+ # @param other [Object] Object to compare with this account.
64
+ # @return [Boolean] Whether the other account has the same core fields.
29
65
  def ==(other)
30
66
  return false unless other.is_a?(WhatsappSdk::Resource::BusinessAccount)
31
67
 
@@ -3,6 +3,10 @@
3
3
  module WhatsappSdk
4
4
  module Resource
5
5
  class ContactResponse
6
+ # @!attribute [rw] user_id
7
+ # Business-scoped user ID, populated only when Graph includes contacts[].user_id.
8
+ # May be present alongside wa_id; nil when omitted from the response.
9
+ # @return [String, nil] Business-scoped user ID returned by Graph.
6
10
  attr_accessor :wa_id, :input, :user_id
7
11
 
8
12
  def initialize(input:, wa_id: nil, user_id: nil)
@@ -50,9 +50,12 @@ module WhatsappSdk
50
50
 
51
51
  class InvalidInteractiveFooter < Error; end
52
52
 
53
+ # Raised when a template parameter format is neither "named" nor "positional".
53
54
  class InvalidParameterFormatError < StandardError
55
+ # @return [Object] Rejected parameter format, retained without conversion.
54
56
  attr_reader :format
55
57
 
58
+ # @param format [Object] Rejected value supplied as the template's parameter_format.
56
59
  def initialize(format:)
57
60
  @format = format
58
61
 
@@ -5,8 +5,12 @@ module WhatsappSdk
5
5
  class Message
6
6
  attr_reader :id
7
7
 
8
- def initialize(id:)
8
+ # @return [String, nil] Message acceptance/pacing status, only when returned by Meta.
9
+ attr_reader :message_status
10
+
11
+ def initialize(id:, message_status: nil)
9
12
  @id = id
13
+ @message_status = message_status
10
14
  end
11
15
  end
12
16
  end
@@ -51,6 +51,10 @@ module WhatsappSdk
51
51
  POSITIONAL
52
52
  ].freeze
53
53
 
54
+ # Check whether a template parameter format is supported.
55
+ #
56
+ # @param format [Object] Value to check against the supported string formats.
57
+ # @return [Boolean] Whether format is exactly "named" or "positional".
54
58
  def self.valid?(format)
55
59
  FORMATS.include?(format)
56
60
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  module WhatsappSdk
4
4
  module Resource
5
+ # Template analytics for one aggregation interval and product type.
6
+ # Metric data points are retained as raw Graph hashes without conversion.
5
7
  class TemplateAnalytic
6
8
  module Granularity
7
9
  DAILY = "DAILY"
@@ -34,14 +36,30 @@ module WhatsappSdk
34
36
  end
35
37
  end
36
38
 
39
+ # @!attribute [rw] granularity
40
+ # @return [String, nil] Aggregation interval, such as DAILY.
41
+ # @!attribute [rw] product_type
42
+ # @return [String, nil] Messaging product, such as cloud_api.
43
+ # @!attribute [rw] data_points
44
+ # @return [Array<Hash>, nil] Raw per-template metrics and time ranges.
37
45
  attr_accessor :granularity, :product_type, :data_points
38
46
 
47
+ # Construct an analytics record without validating or converting its fields.
48
+ #
49
+ # @param granularity [String, nil] Aggregation interval returned by Graph.
50
+ # @param product_type [String, nil] Messaging product returned by Graph.
51
+ # @param data_points [Array<Hash>, nil] Raw per-template metrics and time ranges.
52
+ # @return [TemplateAnalytic] Analytics record containing the supplied values.
39
53
  def initialize(granularity:, product_type:, data_points:)
40
54
  @granularity = granularity
41
55
  @product_type = product_type
42
56
  @data_points = data_points
43
57
  end
44
58
 
59
+ # Build an analytics record from a Graph response.
60
+ #
61
+ # @param hash [Hash{String => Object}] Analytics fields keyed by their Graph names.
62
+ # @return [TemplateAnalytic] Analytics record with nil for any missing fields.
45
63
  def self.from_hash(hash)
46
64
  new(
47
65
  granularity: hash["granularity"],
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WhatsappSdk
4
- VERSION = "1.2.0"
4
+ VERSION = "2.0.0"
5
5
  end
data/whatsapp_sdk.gemspec CHANGED
@@ -42,7 +42,7 @@ Gem::Specification.new do |spec|
42
42
 
43
43
  spec.add_development_dependency("bundler", "~> 2.3")
44
44
  spec.add_development_dependency("minitest", "~> 5.0")
45
- spec.add_development_dependency("rake", "~> 12.3")
45
+ spec.add_development_dependency("rake", "~> 13.0")
46
46
 
47
47
  spec.add_dependency("faraday", "~> 2.0", "> 2.0.1")
48
48
  spec.add_dependency("faraday-multipart", "~> 1")
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: whatsapp_sdk
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.2.0
4
+ version: 2.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - ignacio-chiazzo
@@ -43,14 +43,14 @@ dependencies:
43
43
  requirements:
44
44
  - - "~>"
45
45
  - !ruby/object:Gem::Version
46
- version: '12.3'
46
+ version: '13.0'
47
47
  type: :development
48
48
  prerelease: false
49
49
  version_requirements: !ruby/object:Gem::Requirement
50
50
  requirements:
51
51
  - - "~>"
52
52
  - !ruby/object:Gem::Version
53
- version: '12.3'
53
+ version: '13.0'
54
54
  - !ruby/object:Gem::Dependency
55
55
  name: faraday
56
56
  requirement: !ruby/object:Gem::Requirement
@@ -136,6 +136,7 @@ files:
136
136
  - lib/whatsapp_sdk/api/business_account.rb
137
137
  - lib/whatsapp_sdk/api/business_profile.rb
138
138
  - lib/whatsapp_sdk/api/client.rb
139
+ - lib/whatsapp_sdk/api/flows.rb
139
140
  - lib/whatsapp_sdk/api/medias.rb
140
141
  - lib/whatsapp_sdk/api/messages.rb
141
142
  - lib/whatsapp_sdk/api/phone_numbers.rb