leadwebia 0.2.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 846877d12e45676878a548f7503a546083e3cd5ac6218279880741d340436023
4
+ data.tar.gz: 1e87660a885f250b9917939ece48dd8c0e9865a3a0ba77a633dc8b42938b5f22
5
+ SHA512:
6
+ metadata.gz: 0f3b414a81467228e354b606c85ef6c4ad69c3703a356aa39f299ac6e1a816bd81e7f95374d93512241cc445d4321ba1036dfcb2b1f904832c213b168160fbf5
7
+ data.tar.gz: 05555a69ab4ccad1d9257ce37834b0916c5baabe59e3cdf33e2b66d7bd6d5f8b6c5a66ba2742f9b0e923cbd51433fe53355ec2a8888c6aef0b9c25740a41b9fd
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 LeadWebia
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,166 @@
1
+ # LeadWebia for Ruby
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/leadwebia.svg)](https://rubygems.org/gems/leadwebia)
4
+
5
+ Official Ruby client for the [LeadWebia API](https://leadwebia.com/docs/api). Find local businesses on Google Maps by niche and city, get their emails, phones and website audit, manage them as leads, and push them to your tools or receive them by webhook.
6
+
7
+ [LeadWebia](https://leadwebia.com) is a lead generation tool for web designers, agencies and anyone who sells to local businesses: it finds businesses with or without a website, their contact details and what their current website is missing. The API does with an API key what you do in the app.
8
+
9
+ - Zero dependencies (standard library `net/http`), Ruby 3.0+.
10
+ - All 35 operations of the API; answers are plain Hashes, as in the [OpenAPI document](https://api.leadwebia.com/api/v1/docs).
11
+ - Automatic `Idempotency-Key` on searches, so a retry never charges twice.
12
+ - Retries on `429` (honouring `Retry-After`), `502`, `503` and network errors.
13
+ - Typed errors per `error.code`, cursor iteration over new leads, webhook signature check.
14
+
15
+ ## Install
16
+
17
+ ```bash
18
+ gem install leadwebia
19
+ ```
20
+
21
+ or in your Gemfile: `gem "leadwebia"`.
22
+
23
+ ## Authentication
24
+
25
+ Create an API key in the app: [leadwebia.com/api](https://leadwebia.com/api) (Integrations → API). Pass it to the client or set `LEADWEBIA_API_KEY`.
26
+
27
+ ```ruby
28
+ require "leadwebia"
29
+
30
+ client = LeadWebia::Client.new("lw_live_...") # or LeadWebia::Client.new with LEADWEBIA_API_KEY set
31
+ puts client.me["credits"]
32
+ ```
33
+
34
+ Keep the key on your server: it spends your account's credits.
35
+
36
+ ## Find leads
37
+
38
+ ```ruby
39
+ client = LeadWebia::Client.new
40
+
41
+ # 1. Pick the area
42
+ area = client.locations("Austin", state: "TX")["data"][0]
43
+
44
+ # 2. Start a search: plumbers and roofers without a website, up to 50 businesses
45
+ search = client.searches.create(["plumber", "roofing contractor"], [area["area_id"]], 50,
46
+ only_without_website: true)
47
+
48
+ # 3. Wait for it and read the leads
49
+ client.searches.wait(search["search_id"])
50
+ client.leads.list(search_id: search["search_id"], limit: 100)["data"].each do |lead|
51
+ puts [lead["name"], lead["phone"], lead["emails"]].inspect
52
+ end
53
+ ```
54
+
55
+ A search reserves `max_leads` credits and charges 1 per business delivered (with `only_with_email: true`, 1 per business delivered with an email); unused credits return. `client.searches.more(search_id, 50)` loads more in the same area.
56
+
57
+ ## New leads as they arrive
58
+
59
+ `each_lead` follows the polling cursor. Store the last cursor and pass it next time to get only new leads:
60
+
61
+ ```ruby
62
+ cursor = load_cursor || "0" # "0" = everything, "now" = from now on
63
+ client.each_lead(cursor, on_cursor: ->(c) { save_cursor(c) }) do |lead|
64
+ add_to_crm(lead)
65
+ end
66
+ ```
67
+
68
+ Without a block it returns an `Enumerator` (`client.each_lead("0").first(10)`).
69
+
70
+ ## Resources
71
+
72
+ | Group | Methods |
73
+ | --- | --- |
74
+ | Account | `me`, `lead_statuses` |
75
+ | Locations | `locations(city, country: "US", state: nil)` |
76
+ | Searches | `searches.create`, `.list`, `.updates(updated_since)`, `.get`, `.runs`, `.more`, `.remaining`, `.wait` |
77
+ | Leads | `leads.list(**filters)`, `.feed(since)`, `.each(since)`, `.get`, `.set_status`, `.bulk_status`, `.delete`, `.bulk_delete`, `.outreach_message` |
78
+ | Exports | `exports.create(search_id: … or place_ids: …, website: "any")` → CSV URL (paid plans) |
79
+ | Integrations | `integrations.list`, `.targets(kind)`, `.send_leads(kind, …)`, `.send_status(task_id)` |
80
+ | Reports | `reports.lookup(name, city)`, `.create(place_id)`, `.get`, `.share`, `.pdf` |
81
+ | Tools | `tools.website_check(url, include_pagespeed: false)`, `tools.emails(url)` |
82
+ | Webhooks | `webhooks.create(url, events)`, `.list`, `.get`, `.update`, `.delete`, `.test`, `.deliveries` |
83
+
84
+ Lead filters: `search_id`, `website` (`any`, `without`, `with`, `social_or_directory`), `status`, `q`, `cms`, `cms_outdated`, `uses_ads`, `has_email`, `sort`, `limit`, `offset`. Every field is described in the [API reference](https://leadwebia.com/docs/api) and the [OpenAPI document](https://api.leadwebia.com/api/v1/docs).
85
+
86
+ ## Website tools
87
+
88
+ ```ruby
89
+ site = client.tools.website_check("joesplumbing.com", include_pagespeed: true)
90
+ contacts = client.tools.emails("joesplumbing.com")
91
+ puts site["technologies"]["cms"], site["ssl"]["days_remaining"], contacts["emails"].inspect
92
+ ```
93
+
94
+ The same checks power LeadWebia's free [website tools](https://leadwebia.com/tools).
95
+
96
+ ## Webhooks
97
+
98
+ ```ruby
99
+ hook = client.webhooks.create("https://example.com/leadwebia", ["lead.created", "search.completed"])
100
+ secret = hook["signing_secret"] # shown only once: store it
101
+ ```
102
+
103
+ Verify each delivery with the raw body (before parsing JSON). Rails example:
104
+
105
+ ```ruby
106
+ class LeadwebiaWebhooksController < ActionController::API
107
+ def create
108
+ body = request.raw_post
109
+ signature = request.headers[LeadWebia::SIGNATURE_HEADER]
110
+ return head :unauthorized unless LeadWebia.verify_signature(body, signature, ENV["LEADWEBIA_WEBHOOK_SECRET"])
111
+
112
+ event = JSON.parse(body)
113
+ AddToCrm.call(event["data"]) if event["type"] == "lead.created"
114
+ head :no_content
115
+ end
116
+ end
117
+ ```
118
+
119
+ Webhooks need a paid plan.
120
+
121
+ ## Errors
122
+
123
+ Every API error is a `LeadWebia::Error` with `code`, `message`, `status`, `request_id`, `docs_url` and `retry_after`, raised as a subclass you can rescue:
124
+
125
+ ```ruby
126
+ begin
127
+ client.searches.more(search_id, 100)
128
+ rescue LeadWebia::InsufficientCreditsError => e
129
+ puts "Top up: #{e.message}"
130
+ rescue LeadWebia::ConflictError => e
131
+ puts "This area is used up, search a new one" if e.code == "search_exhausted"
132
+ rescue LeadWebia::RateLimitError => e
133
+ puts "Retry in #{e.retry_after} s"
134
+ rescue LeadWebia::Error => e
135
+ puts [e.code, e.message, e.request_id].inspect
136
+ end
137
+ ```
138
+
139
+ | Exception | Status | Codes |
140
+ | --- | --- | --- |
141
+ | `AuthenticationError` | 401 | `invalid_api_key` |
142
+ | `InsufficientCreditsError` | 402 | `insufficient_credits` |
143
+ | `PermissionDeniedError` | 403 | `paid_plan_required`, `professional_plan_required` |
144
+ | `NotFoundError` | 404 | `not_found`, `search_not_found`, `lead_not_found`, `report_not_found` |
145
+ | `ConflictError` | 409 | `search_exhausted`, `idempotency_conflict`, `report_not_ready`, `integration_not_connected`, … |
146
+ | `ValidationError` | 422 | `validation_error` (`details` lists the fields) |
147
+ | `RateLimitError` | 429 | `rate_limited`, `email_lookup_limit`, `lookup_limit`, `message_limit`, `queue_full` |
148
+ | `ServerError` | 5xx | `upstream_error`, `website_unreadable`, `internal_error` |
149
+ | `APIConnectionError` | — | network error or timeout |
150
+
151
+ Limits: 60 requests/min per key, 120 per account, 10 credit-spending calls/min.
152
+
153
+ ## Development
154
+
155
+ ```bash
156
+ rake test # or: ruby -Ilib test/test_client.rb
157
+ gem build leadwebia.gemspec
158
+ ```
159
+
160
+ The integration tests in `test/test_live.rb` run only with `LEADWEBIA_API_KEY` set (or a git-ignored `sdk/.env.test`); `LEADWEBIA_LIVE_SPEND=1..5` also runs one real search.
161
+
162
+ Other languages: [Python, Node.js, Rust and Go](https://github.com/leadwebia/leadwebia-sdk). AI assistants can use the same features through the [LeadWebia MCP server](https://leadwebia.com/integrations/mcp).
163
+
164
+ ## License
165
+
166
+ MIT
data/leadwebia.gemspec ADDED
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/leadwebia/version"
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = "leadwebia"
7
+ spec.version = LeadWebia::VERSION
8
+ spec.authors = ["LeadWebia"]
9
+ spec.summary = "Official LeadWebia API client: Google Maps lead search, emails, website audits, webhooks."
10
+ spec.description = "Find local businesses on Google Maps by niche and city, with their emails, phones and " \
11
+ "website audit; manage them as leads (CRM status, exports, prospect reports) and receive " \
12
+ "them by signed webhook. Client for the LeadWebia API v1, standard library only."
13
+ spec.homepage = "https://leadwebia.com"
14
+ spec.license = "MIT"
15
+ spec.required_ruby_version = ">= 3.0"
16
+
17
+ spec.metadata = {
18
+ "homepage_uri" => "https://leadwebia.com",
19
+ "documentation_uri" => "https://leadwebia.com/docs/api",
20
+ "source_code_uri" => "https://github.com/leadwebia/leadwebia-sdk/tree/main/ruby",
21
+ "bug_tracker_uri" => "https://github.com/leadwebia/leadwebia-sdk/issues",
22
+ "changelog_uri" => "https://github.com/leadwebia/leadwebia-sdk/releases",
23
+ "rubygems_mfa_required" => "true"
24
+ }
25
+
26
+ spec.files = Dir["lib/**/*.rb"] + %w[README.md LICENSE leadwebia.gemspec]
27
+ spec.require_paths = ["lib"]
28
+ end
@@ -0,0 +1,204 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "openssl"
6
+ require "securerandom"
7
+ require "uri"
8
+
9
+ module LeadWebia
10
+ # Client for the LeadWebia API v1. Answers are Hashes with String keys, as in
11
+ # the {https://api.leadwebia.com/api/v1/openapi.json OpenAPI document}.
12
+ #
13
+ # @example
14
+ # client = LeadWebia::Client.new("lw_live_...") # or set LEADWEBIA_API_KEY
15
+ # client.me["credits"]
16
+ #
17
+ # Create a key in the app: https://leadwebia.com/api
18
+ class Client
19
+ # Production API root.
20
+ DEFAULT_BASE_URL = "https://api.leadwebia.com/api/v1"
21
+ # Seconds per request: website checks with PageSpeed can take ~60 s.
22
+ DEFAULT_TIMEOUT = 90
23
+ # Retries of 429, 502, 503 and network errors.
24
+ DEFAULT_MAX_RETRIES = 3
25
+ # Cap of the wait taken from a Retry-After header, in seconds.
26
+ MAX_RETRY_AFTER = 60.0
27
+ RETRY_STATUSES = [429, 502, 503].freeze
28
+ NETWORK_ERRORS = [SocketError, SystemCallError, IOError, Timeout::Error, OpenSSL::SSL::SSLError].freeze
29
+ private_constant :RETRY_STATUSES, :NETWORK_ERRORS
30
+
31
+ # @return [String]
32
+ attr_reader :base_url
33
+ # @return [Searches] Google Maps lead searches (they spend credits)
34
+ attr_reader :searches
35
+ # @return [Leads] saved leads and their CRM status
36
+ attr_reader :leads
37
+ # @return [Exports] CSV exports (paid plans)
38
+ attr_reader :exports
39
+ # @return [Integrations] push leads to the tools connected in the app
40
+ attr_reader :integrations
41
+ # @return [Reports] prospect reports
42
+ attr_reader :reports
43
+ # @return [Tools] website check and email finder (no credits)
44
+ attr_reader :tools
45
+ # @return [Webhooks] event subscriptions (paid plans)
46
+ attr_reader :webhooks
47
+
48
+ # @param api_key [String, nil] defaults to ENV["LEADWEBIA_API_KEY"]
49
+ # @param base_url [String]
50
+ # @param timeout [Numeric] seconds per request
51
+ # @param max_retries [Integer] retries of 429/502/503 and network errors (0 disables)
52
+ # @param user_agent [String, nil]
53
+ # @param sleeper [#call, nil] waits between retries and polls (for tests)
54
+ # @raise [ArgumentError] when there is no API key
55
+ def initialize(api_key = nil, base_url: DEFAULT_BASE_URL, timeout: DEFAULT_TIMEOUT,
56
+ max_retries: DEFAULT_MAX_RETRIES, user_agent: nil, sleeper: nil)
57
+ @api_key = api_key || ENV.fetch("LEADWEBIA_API_KEY", nil)
58
+ if @api_key.nil? || @api_key.empty?
59
+ raise ArgumentError, "Pass api_key or set LEADWEBIA_API_KEY (create a key at https://leadwebia.com/api)"
60
+ end
61
+
62
+ @base_url = base_url.sub(%r{/+\z}, "")
63
+ @timeout = timeout
64
+ @max_retries = max_retries
65
+ @user_agent = user_agent || "leadwebia-ruby/#{VERSION}"
66
+ @sleeper = sleeper || ->(seconds) { sleep(seconds) }
67
+ @searches = Searches.new(self)
68
+ @leads = Leads.new(self)
69
+ @exports = Exports.new(self)
70
+ @integrations = Integrations.new(self)
71
+ @reports = Reports.new(self)
72
+ @tools = Tools.new(self)
73
+ @webhooks = Webhooks.new(self)
74
+ end
75
+
76
+ def inspect
77
+ "#<#{self.class.name} base_url=#{@base_url.inspect}>"
78
+ end
79
+
80
+ # Plan, credits and +paid_features+ of the key's account (also a credential test).
81
+ # @return [Hash]
82
+ def me
83
+ request(:get, "/me")
84
+ end
85
+
86
+ # The account's CRM statuses, in order.
87
+ # @return [Array<Hash>]
88
+ def lead_statuses
89
+ request(:get, "/lead-statuses")
90
+ end
91
+
92
+ # Areas matching a city: +{"data" => [{"area_id", "name", "state", "country", "population", "points"}]}+.
93
+ # Pass an +area_id+ to {Searches#create}.
94
+ # @param city [String]
95
+ # @param country [String] ISO 3166-1 alpha-2
96
+ # @param state [String, nil]
97
+ # @return [Hash]
98
+ def locations(city, country: "US", state: nil)
99
+ request(:get, "/locations", params: { city: city, country: country, state: state })
100
+ end
101
+
102
+ # Shortcut for {Leads#each}.
103
+ # @return [Enumerator, nil]
104
+ def each_lead(since = "0", **options, &block)
105
+ leads.each(since, **options, &block)
106
+ end
107
+ alias iter_leads each_lead
108
+
109
+ # Sends a request, retrying 429/502/503 and network errors.
110
+ # @api private
111
+ def request(method, path, params: nil, body: nil, headers: nil)
112
+ uri = URI(@base_url + path)
113
+ query = encode_query(params)
114
+ uri.query = query unless query.empty?
115
+ payload = body.nil? ? nil : JSON.generate(body)
116
+ attempt = 0
117
+ begin
118
+ send_once(method, uri, payload, headers)
119
+ rescue Error => e
120
+ retryable = e.is_a?(APIConnectionError) || RETRY_STATUSES.include?(e.status)
121
+ raise if !retryable || attempt >= @max_retries
122
+
123
+ @sleeper.call(retry_delay(attempt, e.retry_after))
124
+ attempt += 1
125
+ retry
126
+ end
127
+ end
128
+
129
+ # @api private
130
+ def pause(seconds)
131
+ @sleeper.call(seconds)
132
+ end
133
+
134
+ private
135
+
136
+ def send_once(method, uri, payload, headers)
137
+ request = Net::HTTPGenericRequest.new(method.to_s.upcase, !payload.nil?, true, uri.request_uri)
138
+ request["Authorization"] = "Bearer #{@api_key}"
139
+ request["Accept"] = "application/json"
140
+ request["User-Agent"] = @user_agent
141
+ if payload
142
+ request["Content-Type"] = "application/json"
143
+ request.body = payload
144
+ end
145
+ (headers || {}).each { |k, v| request[k] = v }
146
+ response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
147
+ open_timeout: @timeout, read_timeout: @timeout,
148
+ write_timeout: @timeout) do |http|
149
+ http.request(request)
150
+ end
151
+ status = response.code.to_i
152
+ raise api_error(response, status) if status >= 300
153
+
154
+ text = response.body.to_s
155
+ text.strip.empty? ? nil : JSON.parse(text)
156
+ rescue *NETWORK_ERRORS => e
157
+ raise APIConnectionError, "Could not reach LeadWebia: #{e.message}"
158
+ rescue JSON::ParserError => e
159
+ raise Error.new("Unexpected answer from #{uri.path}: #{e.message}", status: status)
160
+ end
161
+
162
+ def api_error(response, status)
163
+ body = {}
164
+ begin
165
+ payload = JSON.parse(response.body.to_s)
166
+ body = payload["error"] if payload.is_a?(Hash) && payload["error"].is_a?(Hash)
167
+ rescue JSON::ParserError
168
+ body = {}
169
+ end
170
+ message = body["message"].to_s.empty? ? "HTTP #{status}" : body["message"]
171
+ LeadWebia.error_class(status).new(
172
+ message,
173
+ code: body["code"],
174
+ status: status,
175
+ request_id: body["request_id"] || response["X-Request-Id"],
176
+ docs_url: body["docs_url"],
177
+ details: body["details"],
178
+ retry_after: parse_retry_after(response["Retry-After"])
179
+ )
180
+ end
181
+
182
+ def parse_retry_after(value)
183
+ return nil if value.nil? || value.strip.empty?
184
+
185
+ seconds = Float(value.strip)
186
+ seconds.negative? ? nil : seconds
187
+ rescue ArgumentError
188
+ nil
189
+ end
190
+
191
+ def retry_delay(attempt, retry_after)
192
+ return [retry_after, MAX_RETRY_AFTER].min unless retry_after.nil?
193
+
194
+ [0.5 * (2**attempt), 8.0].min + (rand * 0.25)
195
+ end
196
+
197
+ def encode_query(params)
198
+ return "" if params.nil?
199
+
200
+ pairs = params.reject { |_, v| v.nil? }.map { |k, v| [k.to_s, v.to_s] }
201
+ URI.encode_www_form(pairs)
202
+ end
203
+ end
204
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LeadWebia
4
+ # Base class of every error raised by the client.
5
+ #
6
+ # API errors carry the fields of the v1 error envelope
7
+ # (+{"error": {"code", "message", "status", "request_id", "docs_url"}}+).
8
+ # Rescue a subclass, or branch on {#code} (e.g. +"insufficient_credits"+).
9
+ class Error < StandardError
10
+ # @return [String, nil] machine-readable code, e.g. +"search_exhausted"+
11
+ attr_reader :code
12
+ # @return [Integer, nil] HTTP status; nil when the API could not be reached
13
+ attr_reader :status
14
+ # @return [String, nil] request id to quote to support
15
+ attr_reader :request_id
16
+ # @return [String, nil] documentation of this error
17
+ attr_reader :docs_url
18
+ # @return [Object, nil] invalid fields on validation errors
19
+ attr_reader :details
20
+ # @return [Float, nil] seconds from the Retry-After header
21
+ attr_reader :retry_after
22
+
23
+ # @param message [String]
24
+ def initialize(message, code: nil, status: nil, request_id: nil, docs_url: nil, details: nil, retry_after: nil)
25
+ super(message)
26
+ @code = code
27
+ @status = status
28
+ @request_id = request_id
29
+ @docs_url = docs_url
30
+ @details = details
31
+ @retry_after = retry_after
32
+ end
33
+ end
34
+
35
+ # Network error or timeout: the request never got an answer.
36
+ class APIConnectionError < Error; end
37
+
38
+ # 401 +invalid_api_key+: missing, unknown or revoked key.
39
+ class AuthenticationError < Error; end
40
+
41
+ # 402 +insufficient_credits+: not enough credits for this search or report.
42
+ class InsufficientCreditsError < Error; end
43
+
44
+ # 403 +paid_plan_required+ / +professional_plan_required+.
45
+ class PermissionDeniedError < Error; end
46
+
47
+ # 404 +not_found+, +search_not_found+, +lead_not_found+, +report_not_found+.
48
+ class NotFoundError < Error; end
49
+
50
+ # 409 +search_exhausted+, +idempotency_conflict+, +report_not_ready+, +integration_not_connected+…
51
+ class ConflictError < Error; end
52
+
53
+ # 422 +validation_error+; {Error#details} lists the invalid fields.
54
+ class ValidationError < Error; end
55
+
56
+ # 429 +rate_limited+ or another limit; {Error#retry_after} is in seconds.
57
+ class RateLimitError < Error; end
58
+
59
+ # 5xx: +upstream_error+, +website_unreadable+, +internal_error+…
60
+ class ServerError < Error; end
61
+
62
+ # Raised by {Searches#wait} when the search is still running at the deadline.
63
+ class TimeoutError < Error; end
64
+
65
+ ERRORS_BY_STATUS = {
66
+ 401 => AuthenticationError,
67
+ 402 => InsufficientCreditsError,
68
+ 403 => PermissionDeniedError,
69
+ 404 => NotFoundError,
70
+ 409 => ConflictError,
71
+ 422 => ValidationError,
72
+ 429 => RateLimitError
73
+ }.freeze
74
+ private_constant :ERRORS_BY_STATUS
75
+
76
+ # @param status [Integer]
77
+ # @return [Class] the error class for an HTTP status
78
+ def self.error_class(status)
79
+ ERRORS_BY_STATUS.fetch(status) { status >= 500 ? ServerError : Error }
80
+ end
81
+ end
@@ -0,0 +1,318 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "uri"
5
+
6
+ module LeadWebia
7
+ # Base of the resource groups (one per OpenAPI tag).
8
+ class Resource
9
+ # @param client [Client]
10
+ def initialize(client)
11
+ @client = client
12
+ end
13
+
14
+ private
15
+
16
+ def req(method, path, **kwargs)
17
+ @client.request(method, path, **kwargs)
18
+ end
19
+
20
+ def seg(value)
21
+ URI.encode_www_form_component(value.to_s).gsub("+", "%20")
22
+ end
23
+
24
+ def compact(hash)
25
+ hash.reject { |_, v| v.nil? }
26
+ end
27
+ end
28
+
29
+ # Google Maps lead searches. Starting one spends credits (1 per business delivered).
30
+ class Searches < Resource
31
+ # Statuses after which a search no longer changes.
32
+ FINISHED_STATUSES = %w[delivered completed failed cancelled].freeze
33
+
34
+ # Starts a search: 1–5 niches in 1–20 areas (+area_id+ from {Client#locations}).
35
+ #
36
+ # Reserves +max_leads+ credits; unused credits return when it ends. An
37
+ # +Idempotency-Key+ is generated when you don't pass one and reused on
38
+ # automatic retries, so a retry never starts (or charges) twice.
39
+ #
40
+ # @example
41
+ # area = client.locations("Austin", state: "TX")["data"][0]
42
+ # client.searches.create(["plumber"], [area["area_id"]], 50, only_without_website: true)
43
+ # @return [Hash] the search
44
+ def create(niches, area_ids, max_leads, only_without_website: false, only_with_email: false,
45
+ include_pagespeed: false, language: "en", idempotency_key: nil)
46
+ body = {
47
+ niches: Array(niches), area_ids: Array(area_ids), max_leads: max_leads,
48
+ only_without_website: only_without_website, only_with_email: only_with_email,
49
+ include_pagespeed: include_pagespeed, language: language
50
+ }
51
+ req(:post, "/searches", body: body, headers: { "Idempotency-Key" => idempotency_key || SecureRandom.uuid })
52
+ end
53
+
54
+ # Searches, newest first: +{"data", "total", "offset", "next_offset", "has_more"}+.
55
+ # @param status [String, nil] queued, running, delivered, completed or failed
56
+ # @return [Hash]
57
+ def list(limit: 25, offset: 0, status: nil)
58
+ req(:get, "/searches", params: { limit: limit, offset: offset, status: status })
59
+ end
60
+
61
+ # Cursor feed of changed searches: +{"data", "next_cursor", "has_more"}+.
62
+ # @return [Hash]
63
+ def updates(updated_since = "0")
64
+ req(:get, "/searches", params: { updated_since: updated_since })
65
+ end
66
+
67
+ # @return [Hash] one search
68
+ def get(search_id)
69
+ req(:get, "/searches/#{seg(search_id)}")
70
+ end
71
+
72
+ # @return [Hash] the runs of a search
73
+ def runs(search_id)
74
+ req(:get, "/searches/#{seg(search_id)}/runs")
75
+ end
76
+
77
+ # Loads more results of a search in the same area (spends credits like {#create}).
78
+ # Raises {ConflictError} with code +search_exhausted+ when the area is used up.
79
+ # @return [Hash] the search
80
+ def more(search_id, max_leads, only_without_website: false, include_pagespeed: false, language: "en",
81
+ idempotency_key: nil)
82
+ body = { max_leads: max_leads, only_without_website: only_without_website,
83
+ include_pagespeed: include_pagespeed, language: language }
84
+ req(:post, "/searches/#{seg(search_id)}/more", body: body,
85
+ headers: { "Idempotency-Key" => idempotency_key || SecureRandom.uuid })
86
+ end
87
+
88
+ # @return [Hash] estimate of how many more businesses the area still has
89
+ def remaining(search_id)
90
+ req(:get, "/searches/#{seg(search_id)}/remaining")
91
+ end
92
+
93
+ # Polls {#get} until the search is +delivered+, +completed+, +failed+ or +cancelled+.
94
+ # @raise [LeadWebia::TimeoutError] when it is still running after +timeout+ seconds
95
+ # @return [Hash] the finished search
96
+ def wait(search_id, poll_interval: 10, timeout: 1800)
97
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
98
+ loop do
99
+ search = get(search_id)
100
+ return search if FINISHED_STATUSES.include?(search["status"])
101
+ if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
102
+ raise LeadWebia::TimeoutError, "search #{search_id} still #{search["status"]} after #{timeout}s"
103
+ end
104
+
105
+ @client.pause(poll_interval)
106
+ end
107
+ end
108
+ end
109
+
110
+ # Saved leads (businesses) and their CRM status.
111
+ class Leads < Resource
112
+ # Filtered page: +{"data", "total", "offset", "next_offset", "has_more"}+.
113
+ # @param website [String, nil] +any+, +without+, +with+ or +social_or_directory+
114
+ # @param sort [String, nil] +newest+, +rating+, +reviews+, +name+ or +status+
115
+ # @return [Hash]
116
+ def list(search_id: nil, website: nil, status: nil, q: nil, cms: nil, cms_outdated: nil, uses_ads: nil,
117
+ has_email: nil, sort: nil, limit: 25, offset: 0)
118
+ req(:get, "/leads", params: {
119
+ search_id: search_id, website: website, status: status, q: q, cms: cms, cms_outdated: cms_outdated,
120
+ uses_ads: uses_ads, has_email: has_email, sort: sort, limit: limit, offset: offset
121
+ })
122
+ end
123
+
124
+ # One page of the polling feed: +{"data", "next_cursor", "has_more"}+.
125
+ # @param since [String] +"0"+ = everything, +"now"+ = from now on, or a stored +next_cursor+
126
+ # @return [Hash]
127
+ def feed(since = "0", search_id: nil, q: nil, limit: nil)
128
+ req(:get, "/leads", params: { since: since, search_id: search_id, q: q, limit: limit })
129
+ end
130
+
131
+ # Every lead after +since+, oldest first, following +next_cursor+ until
132
+ # +has_more+ is false. +on_cursor+ receives each new cursor: store the last
133
+ # one and pass it as +since+ next time to get only new leads.
134
+ #
135
+ # @example
136
+ # client.leads.each(cursor, on_cursor: ->(c) { save_cursor(c) }) { |lead| add_to_crm(lead) }
137
+ # @yieldparam lead [Hash]
138
+ # @return [Enumerator, nil] an Enumerator when no block is given
139
+ def each(since = "0", search_id: nil, q: nil, on_cursor: nil)
140
+ return enum_for(:each, since, search_id: search_id, q: q, on_cursor: on_cursor) unless block_given?
141
+
142
+ cursor = since
143
+ loop do
144
+ page = feed(cursor, search_id: search_id, q: q)
145
+ (page["data"] || []).each { |lead| yield lead }
146
+ cursor = page["next_cursor"] || cursor
147
+ on_cursor&.call(cursor)
148
+ break unless page["has_more"]
149
+ end
150
+ nil
151
+ end
152
+ alias iter each
153
+
154
+ # @return [Hash] the full lead
155
+ def get(place_id)
156
+ req(:get, "/leads/#{seg(place_id)}")
157
+ end
158
+
159
+ # Sets the CRM status (title or id, see {Client#lead_statuses}); nil clears it.
160
+ # @return [Hash] the lead
161
+ def set_status(place_id, status)
162
+ req(:patch, "/leads/#{seg(place_id)}", body: { status: status })
163
+ end
164
+
165
+ # Up to 500 +place_ids+, or every lead of +search_id+. Returns +{"updated"}+.
166
+ # @return [Hash]
167
+ def bulk_status(status, place_ids: nil, search_id: nil)
168
+ body = compact(place_ids: place_ids, search_id: search_id).merge(status: status)
169
+ req(:post, "/leads/status", body: body)
170
+ end
171
+
172
+ # @return [Hash] +{"deleted"}+
173
+ def delete(place_id)
174
+ req(:delete, "/leads/#{seg(place_id)}")
175
+ end
176
+
177
+ # @return [Hash] +{"deleted"}+
178
+ def bulk_delete(place_ids)
179
+ req(:post, "/leads/delete", body: { place_ids: Array(place_ids) })
180
+ end
181
+
182
+ # AI-written cold email for this lead (no credits; daily cap).
183
+ # @return [Hash] +{"subject", "message", "language", "issues_mentioned"}+
184
+ def outreach_message(place_id, language: nil, sender_name: nil, agency_name: nil)
185
+ req(:post, "/leads/#{seg(place_id)}/outreach-message",
186
+ body: compact(language: language, sender_name: sender_name, agency_name: agency_name))
187
+ end
188
+ end
189
+
190
+ # CSV exports (paid plans).
191
+ class Exports < Resource
192
+ # CSV of up to 5,000 leads: +{"count", "url", "filename", "expires_at"}+.
193
+ # @return [Hash]
194
+ def create(place_ids: nil, search_id: nil, website: "any")
195
+ req(:post, "/exports", body: compact(place_ids: place_ids, search_id: search_id).merge(website: website))
196
+ end
197
+ end
198
+
199
+ # Push leads to tools already connected in the app (Instantly, Google Sheets, webhook).
200
+ class Integrations < Resource
201
+ # @return [Hash] +{"data" => [kinds]}+
202
+ def list
203
+ req(:get, "/integrations")
204
+ end
205
+
206
+ # @return [Hash] campaigns or spreadsheets of an integration
207
+ def targets(kind)
208
+ req(:get, "/integrations/#{seg(kind)}/targets")
209
+ end
210
+
211
+ # Sends leads; poll {#send_status} with the +task_id+.
212
+ # @return [Hash]
213
+ def send_leads(kind, place_ids: nil, search_id: nil, campaign_id: nil, spreadsheet_id: nil,
214
+ new_spreadsheet_name: nil)
215
+ req(:post, "/integrations/#{seg(kind)}/send", body: compact(
216
+ place_ids: place_ids, search_id: search_id, campaign_id: campaign_id,
217
+ spreadsheet_id: spreadsheet_id, new_spreadsheet_name: new_spreadsheet_name
218
+ ))
219
+ end
220
+
221
+ # @return [Hash] state of a send
222
+ def send_status(task_id)
223
+ req(:get, "/integrations/sends/#{seg(task_id)}")
224
+ end
225
+ end
226
+
227
+ # Prospect reports (online presence audit of one business).
228
+ class Reports < Resource
229
+ # Finds a business on Google Maps by name + city (no credits; daily cap).
230
+ # @return [Hash] +{"lookup_id", "candidates"}+
231
+ def lookup(name, city, country: "US", keyword: nil)
232
+ req(:post, "/reports/lookup", body: compact(name: name, city: city, country: country, keyword: keyword))
233
+ end
234
+
235
+ # Starts a report (20 credits when a new run is needed; an existing report is free).
236
+ # @return [Hash] the report
237
+ def create(place_id, lookup_id: nil, refresh: false)
238
+ req(:post, "/reports", body: compact(place_id: place_id, lookup_id: lookup_id, refresh: refresh))
239
+ end
240
+
241
+ # @param full [Boolean] include the complete data
242
+ # @return [Hash] the report
243
+ def get(place_id, full: false)
244
+ req(:get, "/reports/#{seg(place_id)}", params: full ? { full: true } : nil)
245
+ end
246
+
247
+ # White-label link (+format: "link"+) or PDF (+"pdf"+).
248
+ # @return [Hash] +{"format", "status", "url"}+
249
+ def share(place_id, format: "link", language: "en")
250
+ req(:post, "/reports/#{seg(place_id)}/share", body: { format: format, language: language })
251
+ end
252
+
253
+ # @return [Hash] state and URL of the report's PDF
254
+ def pdf(place_id)
255
+ req(:get, "/reports/#{seg(place_id)}/pdf")
256
+ end
257
+ end
258
+
259
+ # Website tools for any URL (no credits).
260
+ class Tools < Resource
261
+ # CMS and version, tech stack, ad pixels, SSL certificate and (optionally,
262
+ # slower) Google PageSpeed scores and Core Web Vitals.
263
+ # @return [Hash] +{"url", "technologies", "ssl", "pagespeed"}+
264
+ def website_check(url, include_pagespeed: false)
265
+ req(:post, "/tools/website-check", body: { url: url, include_pagespeed: include_pagespeed })
266
+ end
267
+
268
+ # Emails, phones and social profiles published on the website (20 websites/hour).
269
+ # @return [Hash] +{"domain", "emails", "phones", "socials", "contact_page", "pages_checked"}+
270
+ def emails(url)
271
+ req(:post, "/tools/emails", body: { url: url })
272
+ end
273
+ end
274
+
275
+ # Event subscriptions (paid plans). Verify deliveries with {LeadWebia.verify_signature}.
276
+ class Webhooks < Resource
277
+ # @return [Hash] +{"data" => [webhooks]}+
278
+ def list
279
+ req(:get, "/webhooks")
280
+ end
281
+
282
+ # Events: +lead.created+, +search.completed+, +search.failed+, +report.ready+,
283
+ # +report.failed+. The answer's +signing_secret+ is shown only once: store it.
284
+ # @return [Hash] the webhook with its +signing_secret+
285
+ def create(url, events, description: nil)
286
+ req(:post, "/webhooks", body: compact(url: url, events: Array(events), description: description))
287
+ end
288
+
289
+ # @return [Hash] one webhook
290
+ def get(webhook_id)
291
+ req(:get, "/webhooks/#{seg(webhook_id)}")
292
+ end
293
+
294
+ # Changes a webhook; nil arguments are left as they are.
295
+ # @return [Hash] the webhook
296
+ def update(webhook_id, url: nil, events: nil, description: nil, enabled: nil)
297
+ req(:patch, "/webhooks/#{seg(webhook_id)}",
298
+ body: compact(url: url, events: events, description: description, enabled: enabled))
299
+ end
300
+
301
+ # @return [nil]
302
+ def delete(webhook_id)
303
+ req(:delete, "/webhooks/#{seg(webhook_id)}")
304
+ nil
305
+ end
306
+
307
+ # Sends a signed +ping+ event now; returns the receiver's answer.
308
+ # @return [Hash] +{"ok", "status_code", "error"}+
309
+ def test(webhook_id)
310
+ req(:post, "/webhooks/#{seg(webhook_id)}/test")
311
+ end
312
+
313
+ # @return [Hash] +{"data" => [deliveries]}+
314
+ def deliveries(webhook_id)
315
+ req(:get, "/webhooks/#{seg(webhook_id)}/deliveries")
316
+ end
317
+ end
318
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module LeadWebia
4
+ # Version of this gem.
5
+ VERSION = "0.2.0"
6
+ end
@@ -0,0 +1,35 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module LeadWebia
6
+ # Header LeadWebia signs webhook deliveries with.
7
+ SIGNATURE_HEADER = "X-LeadWebia-Signature"
8
+
9
+ # +sha256=<hex HMAC-SHA256 of the raw body>+, as LeadWebia sends it.
10
+ #
11
+ # @param raw_body [String] the request body exactly as received
12
+ # @param secret [String] the webhook's +signing_secret+
13
+ # @return [String]
14
+ def self.compute_signature(raw_body, secret)
15
+ "sha256=#{OpenSSL::HMAC.hexdigest("SHA256", secret.to_s, raw_body.to_s)}"
16
+ end
17
+
18
+ # True when +header+ (the +X-LeadWebia-Signature+ value) matches the raw
19
+ # request body signed with the webhook's +signing_secret+. Pass the body
20
+ # exactly as received, before any JSON parsing. The comparison is constant-time.
21
+ #
22
+ # @example Rails
23
+ # body = request.raw_post
24
+ # head :unauthorized unless LeadWebia.verify_signature(body, request.headers["X-LeadWebia-Signature"], secret)
25
+ #
26
+ # @param raw_body [String]
27
+ # @param header [String, nil]
28
+ # @param secret [String]
29
+ # @return [Boolean]
30
+ def self.verify_signature(raw_body, header, secret)
31
+ return false if header.nil? || header.empty? || secret.nil? || secret.empty?
32
+
33
+ OpenSSL.secure_compare(compute_signature(raw_body, secret), header.strip)
34
+ end
35
+ end
data/lib/leadwebia.rb ADDED
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Official Ruby client for the LeadWebia API v1 (https://leadwebia.com/docs/api).
4
+ #
5
+ # LeadWebia (https://leadwebia.com) finds local businesses on Google Maps by
6
+ # niche and city, with their emails, phones and a website audit.
7
+ #
8
+ # @example Find plumbers without a website in Austin, TX
9
+ # require "leadwebia"
10
+ #
11
+ # client = LeadWebia::Client.new # reads LEADWEBIA_API_KEY
12
+ # area = client.locations("Austin", state: "TX")["data"][0]
13
+ # search = client.searches.create(["plumber"], [area["area_id"]], 50, only_without_website: true)
14
+ # client.searches.wait(search["search_id"])
15
+ # client.leads.list(search_id: search["search_id"], limit: 100)["data"].each do |lead|
16
+ # puts [lead["name"], lead["phone"], lead["emails"]].inspect
17
+ # end
18
+ module LeadWebia
19
+ # Shortcut for {Client#initialize}.
20
+ # @return [Client]
21
+ def self.new(api_key = nil, **options)
22
+ Client.new(api_key, **options)
23
+ end
24
+ end
25
+
26
+ require_relative "leadwebia/version"
27
+ require_relative "leadwebia/errors"
28
+ require_relative "leadwebia/webhooks"
29
+ require_relative "leadwebia/client"
30
+ require_relative "leadwebia/resources"
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: leadwebia
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.2.0
5
+ platform: ruby
6
+ authors:
7
+ - LeadWebia
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-01 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Find local businesses on Google Maps by niche and city, with their emails,
14
+ phones and website audit; manage them as leads (CRM status, exports, prospect reports)
15
+ and receive them by signed webhook. Client for the LeadWebia API v1, standard library
16
+ only.
17
+ email:
18
+ executables: []
19
+ extensions: []
20
+ extra_rdoc_files: []
21
+ files:
22
+ - LICENSE
23
+ - README.md
24
+ - leadwebia.gemspec
25
+ - lib/leadwebia.rb
26
+ - lib/leadwebia/client.rb
27
+ - lib/leadwebia/errors.rb
28
+ - lib/leadwebia/resources.rb
29
+ - lib/leadwebia/version.rb
30
+ - lib/leadwebia/webhooks.rb
31
+ homepage: https://leadwebia.com
32
+ licenses:
33
+ - MIT
34
+ metadata:
35
+ homepage_uri: https://leadwebia.com
36
+ documentation_uri: https://leadwebia.com/docs/api
37
+ source_code_uri: https://github.com/leadwebia/leadwebia-sdk/tree/main/ruby
38
+ bug_tracker_uri: https://github.com/leadwebia/leadwebia-sdk/issues
39
+ changelog_uri: https://github.com/leadwebia/leadwebia-sdk/releases
40
+ rubygems_mfa_required: 'true'
41
+ post_install_message:
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: '3.0'
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 3.5.22
57
+ signing_key:
58
+ specification_version: 4
59
+ summary: 'Official LeadWebia API client: Google Maps lead search, emails, website
60
+ audits, webhooks.'
61
+ test_files: []