customerio 6.2.0 → 6.3.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: d7a5b0095c02a4c1b1a5cf0f9edf47a131d20d8f779620c4ddfe82298750ab7c
4
- data.tar.gz: 9260b0c869b268a4c511c34fbb291ab82e2bb14a13a341a8b2482be31f50f869
3
+ metadata.gz: 8a43f4be850dd294263d0f317d7a0a0a85d940dded1b925c7da7b75ec54ac2af
4
+ data.tar.gz: d48249e3a1f3451ab4ab78375313fe621ffeb2b4b399f914a078c1717a937f4d
5
5
  SHA512:
6
- metadata.gz: 7aed6bdc54c5f284ccbef64a7992c49cade462dca1513e7d31ee6496c7c884b1db0c8831ef8ff20a9223a3a8364dbcd703726424ce06d3ca4c2d82610d9da82c
7
- data.tar.gz: 227a6869e02e98d8d3cdcfdcd3a8c928c7c114f7b7a92d72cd97612f2c3ed877e5d7ad4c160686e2c9e8c659b87b038b549d6e0aa844c9d28721ff8257f4767e
6
+ metadata.gz: 648a43bd107228d57c12a63f3efb99ecacbfe0fdcbf60c9da0abebb4e545da2d41337604e3a317905c1f334caf596c562ed12007517c24b1c7b561ea823d7489
7
+ data.tar.gz: e22f60e2c27cf5acdd24cb7f1c45836e3ee31f8f9e1d45da08bb772419f890604c2a885e4e11ae34a8506cbf13c7845d7eb117d4dbdda6e7d23b49a8821974fa
data/README.md CHANGED
@@ -48,6 +48,36 @@ In the end, the decision on whether or not to use the API client or
48
48
  the JavaScript snippet should be based on what works best for you.
49
49
  You'll be able to integrate **fully** with [Customer.io](https://customer.io) with either approach.
50
50
 
51
+ ### Quick start
52
+
53
+ Create a client with your secret key (`sk_…`). It sends tracking calls to the Track API and transactional messages to the App API, and picks the US or EU region from the key.
54
+
55
+ ```ruby
56
+ cio = Customerio::UnifiedClient.new(ENV["CIO_API_KEY"])
57
+
58
+ cio.identify(id: "user_123", email: "a@example.com")
59
+ cio.track("user_123", "order_completed")
60
+ cio.send_email(Customerio::SendEmailRequest.new(
61
+ to: "a@example.com",
62
+ identifiers: { id: "user_123" },
63
+ transactional_message_id: 5
64
+ ))
65
+ ```
66
+
67
+ A `pk_` or `sk_` key belongs to one region, so passing `Customerio::Regions::US` or `Customerio::Regions::EU` when it disagrees with the key raises `ArgumentError`. A custom `Customerio::Regions::Region` is used as given. Every URL (`track_url`, `api_url` and a custom region's) must start with `https://`. Legacy App API keys also work here for transactional calls; they default to `Customerio::Regions::US` unless you pass `region:`. Tracking calls on Pipelines workspaces need a source-bound `pk_` or `sk_` key.
68
+
69
+ `identify`, `track`, `track_anonymous`, `pageview`, the `send_*` methods and `trigger_broadcast` are on the client directly. The rest of the Track and App API are on `cio.track_client` and `cio.api_client`.
70
+
71
+ If the key can't do what you asked, the call raises `Customerio::KeyCapabilityError`. A public key (`pk_…`) raises it before any request when you send a transactional message or trigger a broadcast. A 401 or 403 from the server is re-raised as a `KeyCapabilityError` too, with the original error as `cause`.
72
+
73
+ ```ruby
74
+ begin
75
+ cio.send_email(request)
76
+ rescue Customerio::KeyCapabilityError => e
77
+ puts e.capability, e.message # :transactional, "The server refused this request to send transactional messages ..."
78
+ end
79
+ ```
80
+
51
81
  ### Setup
52
82
 
53
83
  Create an instance of the client with your [Customer.io credentials](https://fly.customer.io/settings/api_credentials).
@@ -514,6 +544,54 @@ You can target the broadcast audience in several ways. Only one audience option
514
544
 
515
545
  If you omit the audience option, the broadcast uses its default audience configured in the UI.
516
546
 
547
+ ### Import data from a CSV
548
+
549
+ You can start a CSV import and read its result using the `APIClient`. Create a `CreateImportRequest` containing:
550
+
551
+ * `name`: a name for the import.
552
+ * `data_file_url`: the public URL of your CSV file.
553
+ * `type`: what the file holds: `people`, `event`, `object`, `relationship` or `device`.
554
+ * `identifier`: the column that identifies each person, `id` or `email`. Every type except `object` needs it.
555
+ * `description`: optional notes about the import.
556
+
557
+ Use `create_import` to start the import, then `get_import` with the returned `id` to check on it. This example adds push tokens to people who already exist:
558
+
559
+ ```ruby
560
+ require "customerio"
561
+
562
+ client = Customerio::APIClient.new("your API key", region: Customerio::Regions::US)
563
+
564
+ request = Customerio::CreateImportRequest.new(
565
+ name: "Push tokens",
566
+ data_file_url: "https://example.com/devices.csv",
567
+ type: "device",
568
+ identifier: "id",
569
+ )
570
+
571
+ begin
572
+ import = client.create_import(request)["import"]
573
+ puts import["id"], import["state"]
574
+
575
+ import = client.get_import(import["id"])["import"]
576
+ puts import["state"], import["rows_imported"], import["error_download_url"]
577
+ rescue Customerio::InvalidResponse => e
578
+ puts e.code, e.message
579
+ end
580
+ ```
581
+
582
+ A `device` file needs these columns:
583
+
584
+ * `id` or `email`, matching the `identifier` you set
585
+ * `token`: the device's push token
586
+ * `platform`: `ios` or `android`
587
+ * `last_used` (optional): when the device was last used, in unix seconds
588
+
589
+ Any other column is saved as a device attribute.
590
+
591
+ A device import only adds devices to people who already exist. It skips rows for people it can't find and tokens that repeat for another person. The skipped rows and the reason for each are in the file at `error_download_url`, which can be set even when the import succeeds. To get the file, send a GET request to `error_download_url` with your app key as a Bearer token. The answer is JSON like `{"url": "..."}`, where `url` is a temporary link to the CSV.
592
+
593
+ With the one-key client, these calls are on `cio.api_client`, like `cio.api_client.create_import(request)`.
594
+
517
595
  ## Contributing
518
596
 
519
597
  1. Fork it
@@ -58,22 +58,45 @@ module Customerio
58
58
  deliver(trigger_broadcast_path(req.broadcast_id), req.message)
59
59
  end
60
60
 
61
+ def create_import(req)
62
+ validate_request!(req, CreateImportRequest)
63
+
64
+ deliver(imports_path, { import: req.message })
65
+ end
66
+
67
+ def get_import(import_id)
68
+ whole_number = (import_id.is_a?(Integer) || import_id.is_a?(String)) && import_id.to_s.match?(/\A\d+\z/)
69
+ raise ArgumentError, "import_id must be a whole number" unless whole_number
70
+
71
+ deliver(import_path(import_id), nil, :get)
72
+ end
73
+
61
74
  private
62
75
 
63
- def deliver(path, message)
64
- response = @client.request(:post, path, message)
76
+ def deliver(path, message, method = :post)
77
+ response = @client.request(method, path, message)
65
78
 
66
79
  case response
67
80
  when Net::HTTPSuccess
68
81
  JSON.parse(response.body)
69
82
  when Net::HTTPBadRequest
70
- error = JSON.parse(response.body).dig("meta", "error")
71
- raise InvalidResponse.new(response.code, error, response)
83
+ raise InvalidResponse.new(response.code, bad_request_reason(response.body), response)
72
84
  else
73
85
  raise InvalidResponse.new(response.code, response.body, response)
74
86
  end
75
87
  end
76
88
 
89
+ # The send calls answer a 400 with `{"meta":{"error":…}}` and the imports
90
+ # calls with `{"errors":[{"detail":…}]}`; anything else is shown as it came.
91
+ def bad_request_reason(body)
92
+ parsed = JSON.parse(body.to_s)
93
+ return body unless parsed.is_a?(Hash)
94
+
95
+ parsed.dig("meta", "error") || parsed.dig("errors", 0, "detail") || body
96
+ rescue JSON::ParserError, TypeError
97
+ body
98
+ end
99
+
77
100
  def validate_request!(request, request_class)
78
101
  return if request.is_a?(request_class)
79
102
 
@@ -107,5 +130,13 @@ module Customerio
107
130
  def trigger_broadcast_path(broadcast_id)
108
131
  "/v1/campaigns/#{broadcast_id}/triggers"
109
132
  end
133
+
134
+ def imports_path
135
+ "/v1/imports"
136
+ end
137
+
138
+ def import_path(import_id)
139
+ "/v1/imports/#{import_id}"
140
+ end
110
141
  end
111
142
  end
@@ -41,7 +41,8 @@ module Customerio
41
41
  uri = URI.join(@base_uri, path)
42
42
  request_headers = headers.dup
43
43
 
44
- session = Net::HTTP.new(uri.host, uri.port)
44
+ # hostname drops the brackets around an IPv6 address, which host keeps.
45
+ session = Net::HTTP.new(uri.hostname, uri.port)
45
46
  session.use_ssl = uri.scheme == "https"
46
47
  session.open_timeout = @timeout
47
48
  session.read_timeout = @timeout
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Customerio
4
+ class CreateImportRequest
5
+ REQUIRED_FIELDS = %i[data_file_url type].freeze
6
+
7
+ OPTIONAL_FIELDS = %i[name identifier description people_to_process data_to_process object_type_id].freeze
8
+
9
+ attr_reader :message
10
+
11
+ def initialize(opts)
12
+ REQUIRED_FIELDS.each do |field|
13
+ raise ArgumentError, "#{field} is required" if blank?(opts[field])
14
+ end
15
+
16
+ @message = opts.select { |field, _value| valid_field?(field) }
17
+ end
18
+
19
+ private
20
+
21
+ def blank?(value)
22
+ value.nil? || value.to_s.strip.empty?
23
+ end
24
+
25
+ def valid_field?(field)
26
+ REQUIRED_FIELDS.include?(field) || OPTIONAL_FIELDS.include?(field)
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,213 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Customerio
4
+ # Raised by UnifiedClient when its key can't do what a method asks.
5
+ #
6
+ # Raised before the request when the key's type rules it out (a public `pk_`
7
+ # key can't send transactional messages or trigger broadcasts). Otherwise
8
+ # the server's 401 or 403 is re-raised as this error, with the original
9
+ # InvalidResponse as `cause`.
10
+ class KeyCapabilityError < StandardError
11
+ # What the key can't do: :track, :transactional or :broadcast.
12
+ attr_reader :capability
13
+ # The HTTP status code as an Integer, when the server refused the key.
14
+ attr_reader :code
15
+
16
+ def initialize(capability, message, code = nil)
17
+ @capability = capability
18
+ @code = code
19
+
20
+ super(message)
21
+ end
22
+ end
23
+
24
+ # One client for tracking and transactional messages, authenticated with a
25
+ # single key sent as a Bearer token.
26
+ #
27
+ # Tracking methods go to the Track API; send methods go to the App API. For
28
+ # `pk_` / `sk_` keys the region comes from the key, and Regions::US or
29
+ # Regions::EU disagreeing with it raises ArgumentError; a custom Region is
30
+ # used as given. Legacy keys take any `region` and default to Regions::US.
31
+ #
32
+ # Every URL must be https, since the key is sent as a Bearer token.
33
+ #
34
+ # Other Track and App API methods are on #track_client and #api_client.
35
+ class UnifiedClient
36
+ # Keys in the shared format look like `{type}_{us|eu}_{random}_{checksum}`,
37
+ # where type is `pk` (public) or `sk` (secret). The server checks the
38
+ # checksum; the client only reads the prefix.
39
+ KEY_PREFIX = /\A(pk|sk)_(us|eu)_/
40
+
41
+ CAPABILITY_ACTIONS = {
42
+ track: "send tracking data",
43
+ transactional: "send transactional messages",
44
+ broadcast: "trigger broadcasts"
45
+ }.freeze
46
+
47
+ KEY_REGIONS = { "us" => Regions::US, "eu" => Regions::EU }.freeze
48
+ private_constant :KEY_REGIONS
49
+
50
+ attr_reader :track_client, :region
51
+
52
+ def initialize(api_key, options = {})
53
+ api_key = api_key.to_s.strip
54
+ raise ArgumentError, "api_key is required" if api_key.empty?
55
+
56
+ match = KEY_PREFIX.match(api_key)
57
+ @key_kind = match ? match[1].to_sym : :legacy
58
+ @region = resolve_region(match && match[2], options[:region])
59
+ check_urls(options)
60
+
61
+ @track_client = BearerTrackClient.new(api_key, track_options(options))
62
+ @api_client = APIClient.new(api_key, api_options(options))
63
+ end
64
+
65
+ # The App API client. Raises KeyCapabilityError for a public `pk_` key.
66
+ def api_client
67
+ refuse_public_key(:transactional)
68
+ @api_client
69
+ end
70
+
71
+ def identify(attributes)
72
+ guard(:track) { track_client.identify(attributes) }
73
+ end
74
+
75
+ def track(customer_id, event_name, attributes = {}, id: nil, timestamp: nil)
76
+ guard(:track) { track_client.track(customer_id, event_name, attributes, id: id, timestamp: timestamp) }
77
+ end
78
+
79
+ def track_anonymous(anonymous_id, event_name, attributes = {}, id: nil, timestamp: nil)
80
+ guard(:track) { track_client.track_anonymous(anonymous_id, event_name, attributes, id: id, timestamp: timestamp) }
81
+ end
82
+
83
+ def pageview(customer_id, page, attributes = {})
84
+ guard(:track) { track_client.pageview(customer_id, page, attributes) }
85
+ end
86
+
87
+ def send_email(req)
88
+ guard(:transactional) { api_client.send_email(req) }
89
+ end
90
+
91
+ def send_push(req)
92
+ guard(:transactional) { api_client.send_push(req) }
93
+ end
94
+
95
+ def send_sms(req)
96
+ guard(:transactional) { api_client.send_sms(req) }
97
+ end
98
+
99
+ def send_whatsapp(req)
100
+ guard(:transactional) { api_client.send_whatsapp(req) }
101
+ end
102
+
103
+ def send_inbox_message(req)
104
+ guard(:transactional) { api_client.send_inbox_message(req) }
105
+ end
106
+
107
+ def send_in_app(req)
108
+ guard(:transactional) { api_client.send_in_app(req) }
109
+ end
110
+
111
+ def trigger_broadcast(req)
112
+ guard(:broadcast) do
113
+ refuse_public_key(:broadcast)
114
+ @api_client.trigger_broadcast(req)
115
+ end
116
+ end
117
+
118
+ private
119
+
120
+ # A prefixed key belongs to one region, so the other built-in region would
121
+ # only get a redirect or a 401 from the server. A custom Region may be a
122
+ # proxy, so it's trusted.
123
+ def resolve_region(key_region, region)
124
+ return region || Regions::US if key_region.nil?
125
+ return KEY_REGIONS[key_region] if region.nil?
126
+
127
+ name = KEY_REGIONS.key(region)
128
+ if name && name != key_region
129
+ raise ArgumentError, "region #{name} does not match the #{key_region} region of this key"
130
+ end
131
+
132
+ region
133
+ end
134
+
135
+ # The key goes out as a Bearer token, so never send it over plain http.
136
+ def check_urls(options)
137
+ check_https("track_url", options[:track_url])
138
+ check_https("api_url", options[:api_url])
139
+ return unless @region.is_a?(Regions::Region)
140
+
141
+ check_https("region track_url", @region.track_url)
142
+ check_https("region api_url", @region.api_url)
143
+ end
144
+
145
+ def check_https(name, url)
146
+ return if url.nil? || url.to_s.empty?
147
+
148
+ uri = begin
149
+ URI.parse(url.to_s)
150
+ rescue URI::InvalidURIError
151
+ raise ArgumentError, "#{name} is not a valid URL: #{url}"
152
+ end
153
+ raise ArgumentError, "#{name} must start with https://" unless uri.scheme == "https"
154
+ raise ArgumentError, "#{name} is not a valid URL: #{url}" if uri.host.to_s.empty?
155
+ end
156
+
157
+ def refuse_public_key(capability)
158
+ return unless @key_kind == :pk
159
+
160
+ raise KeyCapabilityError.new(
161
+ capability,
162
+ "This key can't use the App API: public keys (pk_) are for tracking only. Use a secret key (sk_)."
163
+ )
164
+ end
165
+
166
+ def track_options(options)
167
+ options.except(:api_url).merge(region: @region, url: options[:track_url])
168
+ end
169
+
170
+ def api_options(options)
171
+ options.except(:track_url).merge(region: @region, url: options[:api_url])
172
+ end
173
+
174
+ # Turns a 401/403 into a KeyCapabilityError so a key mismatch is never a
175
+ # bare auth failure. The original error is kept as `cause`.
176
+ def guard(capability)
177
+ yield
178
+ rescue InvalidResponse => e
179
+ raise unless %w[401 403].include?(e.code.to_s)
180
+
181
+ reason = refusal_reason(e.message)
182
+ raise KeyCapabilityError.new(
183
+ capability,
184
+ "The server refused this request to #{CAPABILITY_ACTIONS[capability]} (#{e.code}): #{reason}. " \
185
+ "Check the key type, its IP restrictions and the workspace status.",
186
+ e.code.to_i
187
+ )
188
+ end
189
+
190
+ # The App API sends `{"errors":[{"detail":…}]}` and the Track API sends
191
+ # `{"meta":{"error":…}}`; anything else is shown as it came.
192
+ def refusal_reason(body)
193
+ parsed = JSON.parse(body.to_s)
194
+ return body unless parsed.is_a?(Hash)
195
+
196
+ reason = parsed.dig("errors", 0, "detail") || parsed.dig("meta", "error")
197
+ reason.is_a?(String) && !reason.empty? ? reason : body
198
+ rescue JSON::ParserError, TypeError
199
+ body
200
+ end
201
+
202
+ # Client only speaks Basic auth, so swap in a Bearer transport.
203
+ class BearerTrackClient < Client
204
+ def initialize(api_key, options)
205
+ super(nil, nil, options)
206
+
207
+ options = options.merge(url: options[:region].track_url) if options[:url].nil? || options[:url].empty?
208
+ @client = BaseClient.new({ app_key: api_key }, options)
209
+ end
210
+ end
211
+ private_constant :BearerTrackClient
212
+ end
213
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Customerio
4
- VERSION = "6.2.0"
4
+ VERSION = "6.3.0"
5
5
  end
data/lib/customerio.rb CHANGED
@@ -13,5 +13,7 @@ module Customerio
13
13
  require "customerio/requests/send_inbox_message_request"
14
14
  require "customerio/requests/send_in_app_request"
15
15
  require "customerio/requests/trigger_broadcast_request"
16
+ require "customerio/requests/create_import_request"
16
17
  require "customerio/api"
18
+ require "customerio/unified_client"
17
19
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: customerio
3
3
  version: !ruby/object:Gem::Version
4
- version: 6.2.0
4
+ version: 6.3.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - John Allison
@@ -52,6 +52,7 @@ files:
52
52
  - lib/customerio/base_client.rb
53
53
  - lib/customerio/client.rb
54
54
  - lib/customerio/regions.rb
55
+ - lib/customerio/requests/create_import_request.rb
55
56
  - lib/customerio/requests/send_email_request.rb
56
57
  - lib/customerio/requests/send_in_app_request.rb
57
58
  - lib/customerio/requests/send_inbox_message_request.rb
@@ -59,6 +60,7 @@ files:
59
60
  - lib/customerio/requests/send_sms_request.rb
60
61
  - lib/customerio/requests/send_whatsapp_request.rb
61
62
  - lib/customerio/requests/trigger_broadcast_request.rb
63
+ - lib/customerio/unified_client.rb
62
64
  - lib/customerio/version.rb
63
65
  homepage: https://customer.io
64
66
  licenses: