whatsapp_sdk 1.1.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 +4 -4
- data/CHANGELOG.md +19 -0
- data/Gemfile.lock +9 -8
- data/README.md +192 -0
- data/lib/whatsapp_sdk/api/business_account.rb +15 -0
- data/lib/whatsapp_sdk/api/client.rb +118 -17
- data/lib/whatsapp_sdk/api/flows.rb +95 -0
- data/lib/whatsapp_sdk/api/medias.rb +46 -0
- data/lib/whatsapp_sdk/api/messages.rb +123 -34
- data/lib/whatsapp_sdk/api/phone_numbers.rb +83 -2
- data/lib/whatsapp_sdk/api/request.rb +4 -2
- data/lib/whatsapp_sdk/api/responses/generic_error_response.rb +4 -0
- data/lib/whatsapp_sdk/api/responses/message_data_response.rb +4 -2
- data/lib/whatsapp_sdk/api/templates.rb +9 -2
- data/lib/whatsapp_sdk/configuration.rb +34 -4
- data/lib/whatsapp_sdk/resource/business_account.rb +36 -0
- data/lib/whatsapp_sdk/resource/contact_response.rb +7 -2
- data/lib/whatsapp_sdk/resource/errors.rb +3 -0
- data/lib/whatsapp_sdk/resource/message.rb +5 -1
- data/lib/whatsapp_sdk/resource/parameter_object.rb +4 -0
- data/lib/whatsapp_sdk/resource/template_analytic.rb +18 -0
- data/lib/whatsapp_sdk/version.rb +1 -1
- data/whatsapp_sdk.gemspec +1 -1
- metadata +6 -8
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 202653d687745c5eb823ee6695f81b957d61ab71483a1b634fcc220950e8308b
|
|
4
|
+
data.tar.gz: 7c0c90da847bb1d09ce19e2427c6da83e10ff999e7ffcffe63a9faf684cf472f
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: c5f66afee0a839d25a167241d8e9df918330f12a42badbb7d300e774b2400127836358075a769a726a085bfac0a059bdbed450c9c879c2ee0b90df098c2bff90
|
|
7
|
+
data.tar.gz: d34b6ac016775f7a7d9a8fb3431d4cea9b9bff2abecf8a1bc04136b5ed4be4dda4ea60fc943e51ca0ee7848b933588cfa6cfdbeb9f0328cfbae60c3ec4232652
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,24 @@
|
|
|
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
|
+
|
|
15
|
+
# v 1.2.0
|
|
16
|
+
- Expose Graph media upload sessions through the configured client @oitedi [199](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/199)
|
|
17
|
+
- Support BSUID recipients and preserve user IDs in message responses @oitedi [198](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/198)
|
|
18
|
+
- Add voice message support to audio sends @oitedi [197](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/197)
|
|
19
|
+
- Guard `GenericErrorResponse.build_from_response` against non-Hash input @afonso-aguas [195](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/195)
|
|
20
|
+
- Fix false-positive `HttpResponseError` on bodies containing "error" substring @afonso-aguas [194](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/194)
|
|
21
|
+
|
|
3
22
|
# v 1.1.0
|
|
4
23
|
- Add support for pagination in template_analytics with 'after' cursor @osvaldo-santos [190](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/190)
|
|
5
24
|
- Add template_analytics feature @osvaldo-santos [189](https://github.com/ignacio-chiazzo/ruby_whatsapp_sdk/pull/189)
|
data/Gemfile.lock
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
PATH
|
|
2
2
|
remote: .
|
|
3
3
|
specs:
|
|
4
|
-
whatsapp_sdk (
|
|
4
|
+
whatsapp_sdk (2.0.0)
|
|
5
5
|
faraday (~> 2.0, > 2.0.1)
|
|
6
6
|
faraday-multipart (~> 1)
|
|
7
7
|
zeitwerk (~> 2)
|
|
@@ -9,8 +9,8 @@ PATH
|
|
|
9
9
|
GEM
|
|
10
10
|
remote: https://rubygems.org/
|
|
11
11
|
specs:
|
|
12
|
-
addressable (2.
|
|
13
|
-
public_suffix (>= 2.0.2, <
|
|
12
|
+
addressable (2.9.1)
|
|
13
|
+
public_suffix (>= 2.0.2, < 8.0)
|
|
14
14
|
ast (2.4.2)
|
|
15
15
|
base64 (0.2.0)
|
|
16
16
|
coderay (1.1.3)
|
|
@@ -25,10 +25,10 @@ GEM
|
|
|
25
25
|
faraday-net_http (3.4.2)
|
|
26
26
|
net-http (~> 0.5)
|
|
27
27
|
hashdiff (1.0.1)
|
|
28
|
-
json (2.
|
|
28
|
+
json (2.19.9)
|
|
29
29
|
logger (1.7.0)
|
|
30
30
|
method_source (1.0.0)
|
|
31
|
-
minitest (5.
|
|
31
|
+
minitest (5.27.0)
|
|
32
32
|
mocha (1.14.0)
|
|
33
33
|
multipart-post (2.4.1)
|
|
34
34
|
net-http (0.9.1)
|
|
@@ -41,9 +41,9 @@ GEM
|
|
|
41
41
|
method_source (~> 1.0)
|
|
42
42
|
pry-nav (1.0.0)
|
|
43
43
|
pry (>= 0.9.10, < 0.15)
|
|
44
|
-
public_suffix (5.
|
|
44
|
+
public_suffix (5.1.1)
|
|
45
45
|
rainbow (3.1.1)
|
|
46
|
-
rake (
|
|
46
|
+
rake (13.4.2)
|
|
47
47
|
regexp_parser (2.5.0)
|
|
48
48
|
rexml (3.4.2)
|
|
49
49
|
rubocop (1.30.1)
|
|
@@ -78,6 +78,7 @@ PLATFORMS
|
|
|
78
78
|
arm64-darwin-22
|
|
79
79
|
arm64-darwin-23
|
|
80
80
|
arm64-darwin-24
|
|
81
|
+
arm64-darwin-25
|
|
81
82
|
x86_64-darwin-19
|
|
82
83
|
x86_64-darwin-21
|
|
83
84
|
x86_64-linux
|
|
@@ -88,7 +89,7 @@ DEPENDENCIES
|
|
|
88
89
|
mocha
|
|
89
90
|
pry
|
|
90
91
|
pry-nav
|
|
91
|
-
rake (~>
|
|
92
|
+
rake (~> 13.0)
|
|
92
93
|
rubocop
|
|
93
94
|
rubocop-minitest
|
|
94
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>
|
|
@@ -535,6 +617,116 @@ If the API response is still `success`, but the message is not delivered:
|
|
|
535
617
|
|
|
536
618
|
Note: Sometimes the messages are delayed; see [Meta documentation](https://developers.facebook.com/docs/whatsapp/on-premises/guides/send-message-performance#delays).
|
|
537
619
|
|
|
620
|
+
|
|
621
|
+
### Voice messages
|
|
622
|
+
|
|
623
|
+
Pass `voice: true` to `send_audio` with an uploaded `audio_id` or hosted `link`.
|
|
624
|
+
Voice messages require an Ogg file encoded with Opus; the SDK does not transcode media.
|
|
625
|
+
Omitting `voice` (or passing `false`) sends basic audio.
|
|
626
|
+
|
|
627
|
+
```ruby
|
|
628
|
+
client.messages.send_audio(sender_id: sender_id, recipient_number: recipient_number,
|
|
629
|
+
audio_id: media_id, voice: true)
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
See [Meta's audio message documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/messages/audio-messages/).
|
|
633
|
+
|
|
634
|
+
### Upload handles for templates and profile photos
|
|
635
|
+
|
|
636
|
+
Use Graph upload sessions when an endpoint requires a media handle instead of a WhatsApp media ID:
|
|
637
|
+
|
|
638
|
+
```ruby
|
|
639
|
+
session = client.media.create_upload_session(app_id: app_id, file_path: "header.png", type: "image/png")
|
|
640
|
+
upload = client.media.upload_file_to_session(session_id: session.fetch("id"), file_path: "header.png")
|
|
641
|
+
handle = upload.fetch("h")
|
|
642
|
+
```
|
|
643
|
+
|
|
644
|
+
Both methods use the client's configured API version and token. An optional `access_token:`
|
|
645
|
+
overrides the token for that request only. They return the Graph response hashes and raise
|
|
646
|
+
`WhatsappSdk::Api::Responses::HttpResponseError` on Graph errors, like the other APIs.
|
|
647
|
+
Missing files or directories raise `WhatsappSdk::Api::Medias::FileNotFoundError`.
|
|
648
|
+
The upload reads the entire file into memory and starts at offset zero; automatic retries and
|
|
649
|
+
resuming interrupted uploads are not included.
|
|
650
|
+
See [Meta's upload guide](https://developers.facebook.com/docs/graph-api/guides/upload).
|
|
651
|
+
|
|
652
|
+
### Business-scoped user IDs (BSUIDs)
|
|
653
|
+
|
|
654
|
+
All message sends accept `recipient:` as an alternative to `recipient_number:`.
|
|
655
|
+
Use the complete BSUID (or parent BSUID), including its country prefix:
|
|
656
|
+
|
|
657
|
+
```ruby
|
|
658
|
+
response = client.messages.send_text(sender_id: sender_id, recipient: "US.123abc", message: "Hello")
|
|
659
|
+
response.contacts.first.user_id # => "US.123abc"
|
|
660
|
+
response.contacts.first.wa_id # => nil when Meta omits the phone number
|
|
661
|
+
```
|
|
662
|
+
|
|
663
|
+
Phone numbers take precedence when both destinations are supplied. Missing or blank
|
|
664
|
+
selected destinations raise `WhatsappSdk::Resource::Errors::MissingArgumentError` before sending.
|
|
665
|
+
Authentication templates require a phone number; the SDK does not infer template category from its name or buttons.
|
|
666
|
+
See [Meta's BSUID documentation](https://developers.facebook.com/documentation/business-messaging/whatsapp/business-scoped-user-ids/).
|
|
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
|
+
|
|
538
730
|
## Development
|
|
539
731
|
|
|
540
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
|
-
'
|
|
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,28 +82,41 @@ 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
|
-
|
|
55
|
-
|
|
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
|
-
|
|
108
|
+
response = connection_for(url, multipart).public_send(http_method, url.to_s, request_params(params, headers),
|
|
109
|
+
headers)
|
|
58
110
|
|
|
59
|
-
response
|
|
111
|
+
return response if raw_response
|
|
60
112
|
|
|
61
|
-
|
|
62
|
-
raise Api::Responses::HttpResponseError.new(http_status: response.status, body: JSON.parse(response.body))
|
|
63
|
-
end
|
|
113
|
+
parsed_body = parse_response_body(response.body)
|
|
64
114
|
|
|
65
|
-
|
|
115
|
+
if response.status >= 400 || Api::Responses::GenericErrorResponse.response_error?(response: parsed_body)
|
|
116
|
+
raise Api::Responses::HttpResponseError.new(http_status: response.status, body: parsed_body)
|
|
117
|
+
end
|
|
66
118
|
|
|
67
|
-
|
|
119
|
+
parsed_body
|
|
68
120
|
end
|
|
69
121
|
|
|
70
122
|
def download_file(url:, content_type_header:, file_path: nil)
|
|
@@ -83,19 +135,68 @@ 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
|
|
|
157
|
+
def parse_response_body(body)
|
|
158
|
+
return nil if body.nil? || body.empty?
|
|
159
|
+
|
|
160
|
+
JSON.parse(body)
|
|
161
|
+
end
|
|
162
|
+
|
|
88
163
|
def request_params(params, headers)
|
|
89
164
|
return params.to_json if params.is_a?(Hash) && headers['Content-Type'] == 'application/json'
|
|
90
165
|
|
|
91
166
|
params
|
|
92
167
|
end
|
|
93
168
|
|
|
94
|
-
|
|
95
|
-
|
|
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|
|
|
96
196
|
client.request(:multipart) if multipart
|
|
97
197
|
client.request(:url_encoded)
|
|
98
|
-
client
|
|
198
|
+
@middleware&.call(client)
|
|
199
|
+
client.adapter(@adapter || ::Faraday.default_adapter)
|
|
99
200
|
client.headers['Authorization'] = "Bearer #{@access_token}" unless @access_token.nil?
|
|
100
201
|
client.response(:logger, @logger, @logger_options) unless @logger.nil?
|
|
101
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
|