checkbiz 1.0.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.
Files changed (100) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +52 -0
  3. data/LICENSE.md +21 -0
  4. data/README.md +43 -117
  5. data/checkbiz.gemspec +8 -5
  6. data/lib/checkbiz/auth/access_token.rb +60 -0
  7. data/lib/checkbiz/auth/bearer.rb +21 -0
  8. data/lib/checkbiz/company.rb +26 -0
  9. data/lib/checkbiz/error_translation.rb +21 -0
  10. data/lib/checkbiz/person.rb +43 -0
  11. data/lib/checkbiz/resource.rb +15 -13
  12. data/lib/checkbiz/version.rb +1 -1
  13. data/lib/checkbiz.rb +66 -10
  14. metadata +36 -103
  15. data/lib/checkbiz/resources/address_information.rb +0 -17
  16. data/lib/checkbiz/resources/bolagsverket.rb +0 -17
  17. data/lib/checkbiz/resources/company_annual_report.rb +0 -13
  18. data/lib/checkbiz/resources/company_annual_reports.rb +0 -13
  19. data/lib/checkbiz/resources/company_articles_of_association.rb +0 -13
  20. data/lib/checkbiz/resources/company_autocomplete.rb +0 -13
  21. data/lib/checkbiz/resources/company_beneficial_owner.rb +0 -15
  22. data/lib/checkbiz/resources/company_certificates_of_registration.rb +0 -13
  23. data/lib/checkbiz/resources/company_credit_template.rb +0 -23
  24. data/lib/checkbiz/resources/company_event.rb +0 -29
  25. data/lib/checkbiz/resources/company_information.rb +0 -41
  26. data/lib/checkbiz/resources/company_information_list.rb +0 -14
  27. data/lib/checkbiz/resources/company_search.rb +0 -13
  28. data/lib/checkbiz/resources/company_search_advanced.rb +0 -13
  29. data/lib/checkbiz/resources/company_worksite.rb +0 -13
  30. data/lib/checkbiz/resources/custom_list.rb +0 -31
  31. data/lib/checkbiz/resources/data_factory_person_search.rb +0 -14
  32. data/lib/checkbiz/resources/extended_search_no.rb +0 -14
  33. data/lib/checkbiz/resources/geomatics.rb +0 -13
  34. data/lib/checkbiz/resources/heartbeat.rb +0 -9
  35. data/lib/checkbiz/resources/lookup_company_no.rb +0 -14
  36. data/lib/checkbiz/resources/lookup_id_no.rb +0 -14
  37. data/lib/checkbiz/resources/lookup_phone_no.rb +0 -14
  38. data/lib/checkbiz/resources/nix.rb +0 -11
  39. data/lib/checkbiz/resources/package_calls.rb +0 -13
  40. data/lib/checkbiz/resources/package_information.rb +0 -13
  41. data/lib/checkbiz/resources/person_beneficial_owner.rb +0 -24
  42. data/lib/checkbiz/resources/person_credit_template.rb +0 -23
  43. data/lib/checkbiz/resources/person_event.rb +0 -18
  44. data/lib/checkbiz/resources/person_information.rb +0 -47
  45. data/lib/checkbiz/resources/person_information_list.rb +0 -14
  46. data/lib/checkbiz/resources/person_search.rb +0 -15
  47. data/lib/checkbiz/resources/person_search_advanced.rb +0 -15
  48. data/lib/checkbiz/resources/person_verify.rb +0 -15
  49. data/lib/checkbiz/resources/pts_info.rb +0 -13
  50. data/lib/checkbiz/resources/safenode_company_credit_report.rb +0 -14
  51. data/lib/checkbiz/resources/safenode_company_remark_control.rb +0 -14
  52. data/lib/checkbiz/resources/safenode_person_credit_report.rb +0 -14
  53. data/lib/checkbiz/resources/safenode_person_remark_control.rb +0 -14
  54. data/lib/checkbiz/resources/search_no.rb +0 -14
  55. data/lib/checkbiz/resources/signatory.rb +0 -15
  56. data/lib/checkbiz/resources/spar.rb +0 -13
  57. data/lib/checkbiz/resources/statistics.rb +0 -14
  58. data/lib/checkbiz/resources/subscriber.rb +0 -17
  59. data/lib/checkbiz/resources/subscriber_list.rb +0 -16
  60. data/lib/checkbiz/resources/url.rb +0 -16
  61. data/lib/checkbiz/resources/url_search.rb +0 -16
  62. data/lib/checkbiz/types/address_information.rb +0 -136
  63. data/lib/checkbiz/types/bolagsverket.rb +0 -1012
  64. data/lib/checkbiz/types/common.rb +0 -503
  65. data/lib/checkbiz/types/company_advanced_search.rb +0 -38
  66. data/lib/checkbiz/types/company_annual_reports.rb +0 -17
  67. data/lib/checkbiz/types/company_autocomplete.rb +0 -25
  68. data/lib/checkbiz/types/company_credit_template.rb +0 -54
  69. data/lib/checkbiz/types/company_event.rb +0 -37
  70. data/lib/checkbiz/types/company_information.rb +0 -460
  71. data/lib/checkbiz/types/company_information_list.rb +0 -15
  72. data/lib/checkbiz/types/company_search.rb +0 -38
  73. data/lib/checkbiz/types/company_worksite.rb +0 -18
  74. data/lib/checkbiz/types/custom_list_add.rb +0 -16
  75. data/lib/checkbiz/types/custom_list_get.rb +0 -17
  76. data/lib/checkbiz/types/data_factory_person_search.rb +0 -117
  77. data/lib/checkbiz/types/geomatic.rb +0 -140
  78. data/lib/checkbiz/types/lookup_company_no.rb +0 -57
  79. data/lib/checkbiz/types/lookup_id_no.rb +0 -22
  80. data/lib/checkbiz/types/lookup_phone_no.rb +0 -29
  81. data/lib/checkbiz/types/package_calls.rb +0 -27
  82. data/lib/checkbiz/types/package_information.rb +0 -23
  83. data/lib/checkbiz/types/person_advanced_search.rb +0 -117
  84. data/lib/checkbiz/types/person_credit_template.rb +0 -61
  85. data/lib/checkbiz/types/person_event.rb +0 -33
  86. data/lib/checkbiz/types/person_information.rb +0 -598
  87. data/lib/checkbiz/types/person_information_list.rb +0 -19
  88. data/lib/checkbiz/types/person_search.rb +0 -88
  89. data/lib/checkbiz/types/person_verify.rb +0 -61
  90. data/lib/checkbiz/types/pts.rb +0 -15
  91. data/lib/checkbiz/types/safenode_company_credit_report.rb +0 -50
  92. data/lib/checkbiz/types/safenode_company_remark_control.rb +0 -29
  93. data/lib/checkbiz/types/safenode_person_credit_report.rb +0 -49
  94. data/lib/checkbiz/types/safenode_person_remark_control.rb +0 -28
  95. data/lib/checkbiz/types/signatory.rb +0 -40
  96. data/lib/checkbiz/types/spar.rb +0 -107
  97. data/lib/checkbiz/types/statistics.rb +0 -33
  98. data/lib/checkbiz/types/subscriber.rb +0 -68
  99. data/lib/checkbiz/types/subscriber_list.rb +0 -49
  100. data/lib/checkbiz/types/subscriber_nix.rb +0 -16
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b39862dbdbf3fd706db79eac866a201e69d1a238f26bedf7dce37cb4ae9a1a81
4
- data.tar.gz: ec12732ab50604633fe37c36e5e6f21fb62b776e9ef2cc32c0188fabf8f95b22
3
+ metadata.gz: 48c93bd17a8656b619f47853029ac022d50f3819fd57c808e40bb1a2090ca415
4
+ data.tar.gz: d0253b2b221ef92639cffa9a5ccf0e733541ae17723bdf175f48b9eb1002b9e1
5
5
  SHA512:
6
- metadata.gz: '03918bd9aba1fc0a47829b67c5ffbced80785fd989afe21bd8e2472d3e0c5e81fa07b51e73aab57890b863f3403ac3c9e7497ed7732662619bcac4a45482feb5'
7
- data.tar.gz: ed6c8a084b8c2035b91c0a19f554ccadd4252d62bc03a000692629bf664bee9295dd7398f45c2d4c415b8d093aaabea841503a0eebbdbede23ee22cfbbc1046b
6
+ metadata.gz: 434c3119792f56a183ece67eeea4cd268bb9068c1fe263a07c72637fa700c25785c2e7f8ddc1eb25a8f39404f983834f874a6b82811ad2cd464aac82a44e7771
7
+ data.tar.gz: 3e2b7296e231cf0ccb5dd9dc1238458e277f5f06f2962bf531f8829c2c790978393cdc647fccf6be42f097fbeff34989985730a0306186eca1040f7dc1effe43
data/CHANGELOG.md ADDED
@@ -0,0 +1,52 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
6
+ and this project adheres to
7
+ [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
8
+
9
+ ## [Unreleased]
10
+
11
+ ## [2.0.0] - 2026-11-18
12
+
13
+ A rewrite for Checkbiz's v2 API, which replaces the current API at the turn
14
+ of the year 2026/2027. Nothing from 1.0.0 carries over; see the README for
15
+ how to authenticate and look things up.
16
+
17
+ ### Added
18
+
19
+ - **`Checkbiz.authenticate_with(username:, password:)`.** v2 authenticates
20
+ with a Bearer token, which the gem fetches with your credentials, shares
21
+ between threads and renews before it expires, or as soon as Checkbiz
22
+ rejects it.
23
+ - **`Checkbiz::Person.find` and `Checkbiz::Company.find`**, which look up a
24
+ person by personal number and a company by organisation number and return
25
+ every field Checkbiz sends. Fields Checkbiz doesn't know are `nil`, and
26
+ dates are `Date`, except a person's `deregistration_date`, which is a string
27
+ because Checkbiz sends `00` for an unknown month or day.
28
+ - **`Checkbiz.ping`**, which checks the credentials and the connection.
29
+ - **Errors of the gem's own:** `Checkbiz::RequestError` (with the response),
30
+ `Checkbiz::AuthenticationError`, `Checkbiz::ConnectionError` and
31
+ `Checkbiz::AttributeError`, all subclasses of `Checkbiz::Error`. Nothing
32
+ from rest-easy or Faraday reaches the caller.
33
+ - **Retries and timeouts.** 429s are retried after Checkbiz's `Retry-After`,
34
+ and requests give up after 5 seconds connecting or 10 reading.
35
+
36
+ ### Removed
37
+
38
+ - **Every resource for the old API**, and with them `Checkbiz.configure`
39
+ with `RestEasy::Auth::PSK`, the `.call(..., package:)` interface and
40
+ `Checkbiz::ArgumentError`.
41
+
42
+ ### Changed
43
+
44
+ - **Requires Ruby 3.2** (was 3.1) and rest-easy `~> 1.5` (was `~> 1.0.0`).
45
+ - **`Checkbiz::RequestError` and `Checkbiz::AttributeError` are no longer
46
+ `RestEasy::Error` subclasses**, so code rescuing `RestEasy::Error` no longer
47
+ catches them; rescue `Checkbiz::Error` instead.
48
+ - **The gem no longer depends on dry-struct.**
49
+
50
+ ## [1.0.0] - 2026-03-19
51
+
52
+ First release, for Checkbiz's original API.
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Accodeing to you KB
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 CHANGED
@@ -1,144 +1,70 @@
1
1
  # Checkbiz
2
2
 
3
- Ruby wrapper for the [Checkbiz API](https://api.checkbiz.se), built on [rest-easy](https://github.com/accodeing/rest-easy).
3
+ [![Gem Version](https://badge.fury.io/rb/checkbiz.svg?icon=si%3Arubygems)](https://badge.fury.io/rb/checkbiz)
4
4
 
5
- Provides typed access to Swedish person, company, and credit information services.
5
+ Ruby wrapper for the [Checkbiz API](https://api-docs.checkbiz.se/docs/v2/apidocs.html), built on [rest-easy](https://github.com/accodeing/rest-easy).
6
+
7
+ Provides typed access to Swedish person and company information.
8
+
9
+ Checkbiz replaces its current API with a new one (v2) at the turn of the year 2026/2027. The gem now supports v2 only, with person and company lookup.
6
10
 
7
11
  ## Installation
8
12
 
9
13
  ```ruby
10
- gem "checkbiz", path: "../checkbiz" # local
11
- gem "checkbiz", git: "https://github.com/accodeing/checkbiz" # git
14
+ gem "checkbiz", "~> 2.0"
12
15
  ```
13
16
 
14
- ## Configuration
17
+ ## Usage
15
18
 
16
19
  ```ruby
17
- Checkbiz.configure do
18
- authentication RestEasy::Auth::PSK.new(
19
- api_key: ENV["CHECKBIZ_API_KEY"],
20
- header_prefix: "Basic"
21
- )
22
- end
23
- ```
20
+ Checkbiz.authenticate_with(username: ENV["CHECKBIZ_USERNAME"], password: ENV["CHECKBIZ_PASSWORD"])
24
21
 
25
- ## Usage
22
+ Checkbiz.ping # => true
26
23
 
27
- Every endpoint is a resource class with a `.call` method. Pass query parameters as keyword arguments and the package name via `package:`.
24
+ person = Checkbiz::Person.find("198510102398")
25
+ person.first_names # => "Adam August"
26
+ person.fbf_address # => "Testgatan 123"
27
+ person.birth_date # => #<Date: 1985-10-10>
28
28
 
29
- ```ruby
30
- # Company information
31
- company = Checkbiz::CompanyInformation.call(
32
- organization_number: "5564866286",
33
- package: "foretagadress"
34
- )
35
- company.name # => PersonNameBlock struct
36
- company.basic # => CompanyBasicBlock struct
37
- company.meta.response_code # => "Ok"
38
-
39
- # Person information
40
- person = Checkbiz::PersonInformation.call(
41
- ssn: "194907299289",
42
- package: "personadress"
43
- )
44
- person.basic # => PersonBasicBlock struct
45
- person.ssn_status # => "Active"
46
-
47
- # Search
48
- results = Checkbiz::CompanySearch.call(
49
- who: "Accodeing",
50
- max_nr_records: 10,
51
- package: "sokforetag"
52
- )
53
- results.basic_result # => CompanySearchBasicBlock struct
54
-
55
- # Account info (no package required)
56
- info = Checkbiz::PackageInformation.call
57
- info.products # => Array of PackageInformationProductBlock
29
+ company = Checkbiz::Company.find("5555555555")
30
+ company.name # => "Exempelbolaget AB"
31
+ company.form # => "aktiebolag"
32
+ company.address # => "Testgatan 123"
58
33
  ```
59
34
 
60
- ### Response metadata
35
+ Attributes are named after Checkbiz's fields in snake_case. For a person, `fbf_*` is the population register ("folkbokföring") address and `sp_*` the special postal address. A company's `form` and `status` are Checkbiz's slugs, such as `aktiebolag` and `konkurs-inledd`. Fields Checkbiz sends as empty strings, meaning unknown, are `nil`.
61
36
 
62
- `responseCode` and `responseMessage` are extracted into `meta` on every response:
37
+ Errors are `Checkbiz::Error` or one of its subclasses. `Checkbiz::Error` itself means Checkbiz answered with something unexpected, such as an HTML page instead of JSON.
63
38
 
64
- ```ruby
65
- result = Checkbiz::CompanyInformation.call(organization_number: "5564866286", package: "foretagadress")
66
- result.meta.response_code # => "Ok"
67
- result.meta.response_message # => nil
68
- ```
39
+ - `Checkbiz::RequestError`: Checkbiz answered with an error, e.g. a 404 for a personal number it doesn't know. `#response` holds the response, and the message includes Checkbiz's error messages.
40
+ - `Checkbiz::AuthenticationError`: a subclass of `RequestError`, raised when the credentials are rejected.
41
+ - `Checkbiz::ConnectionError`: Checkbiz couldn't be reached, or didn't connect within 5 seconds or answer within 10.
42
+ - `Checkbiz::AttributeError`: a response didn't fit a resource's attributes.
69
43
 
70
- ### V2 endpoints
44
+ ## Authentication
71
45
 
72
- Some endpoints have a v2 variant with additional fields:
46
+ The gem handles authentication. Given a Checkbiz username and password, `Checkbiz::Auth::AccessToken` fetches a token from `/v2/authentication/token` and reuses it until shortly before it expires (tokens last an hour). `Checkbiz::Auth::Bearer` sends it with every request, and after a 401 it drops the token so the retry fetches a new one.
73
47
 
74
- ```ruby
75
- Checkbiz::CompanyCreditTemplate.call_v2(
76
- organization_number: "5564866286",
77
- package: "bas"
78
- )
79
- ```
48
+ ## Retries
49
+
50
+ Failed requests are retried up to three times, using rest-easy's `retry_transient_errors`:
80
51
 
81
- ### Custom lists (POST/PUT)
52
+ - A 429 is retried after waiting as long as Checkbiz's `Retry-After` header asks (1 second without one). If it asks for more than 10 seconds, the request raises instead.
53
+ - A 5xx, a timeout or a failed connection is retried for `Checkbiz.ping` only. Lookups are POST requests, and rest-easy only repeats those on a 429, so a lookup that gets a 5xx raises right away.
54
+ - A 401 is retried with a new token.
55
+ - Anything else raises right away.
56
+
57
+ The token request itself isn't retried: a 429, 5xx or timeout while fetching a token raises at once. A process fetches a token about once an hour.
58
+
59
+ To raise on a 429, 5xx, timeout or failed connection too, without retrying:
82
60
 
83
61
  ```ruby
84
- Checkbiz::CustomList.call(package: "bas") # GET
85
- Checkbiz::CustomList.add(items, package: "bas") # POST
86
- Checkbiz::CustomList.remove(items, package: "bas") # PUT
62
+ Checkbiz.configure { retry_transient_errors false }
87
63
  ```
88
64
 
89
- ## Available resources
90
-
91
- ### Account
92
- - `PackageInformation` - list authorized products and packages
93
- - `PackageCalls` - usage statistics
94
-
95
- ### Company
96
- - `CompanyInformation` - company details by org number
97
- - `CompanyInformationList` - batch lookup
98
- - `CompanyCreditTemplate` / `call_v2` - credit reports
99
- - `CompanyBeneficialOwner` - beneficial ownership
100
- - `CompanyAnnualReports` - list annual reports
101
- - `CompanyAnnualReport` - fetch single report by ref number
102
- - `CompanyArticlesOfAssociation` - articles of association (PDF)
103
- - `CompanyCertificatesOfRegistration` - registration certificate (PDF)
104
- - `CompanyWorksite` - worksite info by CFAR number
105
- - `CompanySearch` - basic company search
106
- - `CompanySearchAdvanced` - advanced company search
107
- - `CompanyAutocomplete` - autocomplete suggestions
108
- - `CompanyEvent` - company events by date range
109
-
110
- ### Person
111
- - `PersonInformation` - person details by SSN
112
- - `PersonInformationList` - batch lookup
113
- - `PersonCreditTemplate` / `call_v2` - credit reports
114
- - `PersonBeneficialOwner` - beneficial ownership
115
- - `PersonSearch` - basic person search
116
- - `PersonSearchAdvanced` - advanced person search
117
- - `PersonEvent` - person events by date range
118
- - `PersonVerify` - identity verification
119
-
120
- ### Lookups
121
- - `LookupIdNo` - lookup by ID number
122
- - `LookupCompanyNo` - lookup by company number
123
- - `LookupPhoneNo` - lookup by phone number
124
- - `AddressInformation` - address lookup
125
- - `Nix` - NIX registry check
126
-
127
- ### Specialized
128
- - `Bolagsverket` - Swedish Companies Registration Office data
129
- - `Signatory` - signatory information
130
- - `Spar` - SPAR registry
131
- - `PtsInfo` - PTS phone data
132
- - `Geomatics` - geographic data
133
- - `Statistics` - income and economic statistics
134
- - `DataFactoryPersonSearch` - extended person search
135
- - `Subscriber` / `SubscriberList` - subscriber info
136
- - `SearchNo` / `ExtendedSearchNo` - Norwegian registry search
137
- - `SafenodePersonCreditReport` / `SafenodePersonRemarkControl` - Safenode person reports
138
- - `SafenodeCompanyCreditReport` / `SafenodeCompanyRemarkControl` - Safenode company reports
139
- - `Url` / `UrlSearch` - report URL generation
140
- - `CustomList` - custom list management (GET/POST/PUT)
141
- - `Heartbeat` - API health check
65
+ ## Tokens and processes
66
+
67
+ Each process fetches and keeps its own token. That is safe because Checkbiz does not invalidate older tokens when it issues a new one, so several app processes or servers can use the same credentials at once.
142
68
 
143
69
  ## Development
144
70
 
@@ -147,8 +73,8 @@ bundle install
147
73
  bundle exec rspec
148
74
  ```
149
75
 
150
- Tests use VCR cassettes recorded against the staging API. To re-record, delete `spec/vcr_cassettes/` and run the suite with a valid API key configured in `spec/spec_helper.rb`.
76
+ Tests use VCR cassettes recorded against the Checkbiz API. Credentials are read from the environment, loaded from `.env.test.local` (gitignored) or `.env.test`. To re-record a cassette, delete it and run its spec with valid credentials in `.env.test.local`.
151
77
 
152
78
  ## License
153
79
 
154
- MIT
80
+ [MIT](LICENSE.md). Copyright (c) 2026 Accodeing to you KB.
data/checkbiz.gemspec CHANGED
@@ -11,22 +11,25 @@ Gem::Specification.new do |spec|
11
11
  spec.license = "MIT"
12
12
  spec.version = Checkbiz::VERSION.dup
13
13
 
14
- spec.summary = "Checkbiz V1 API library, based on rest-easy."
14
+ spec.summary = "Checkbiz v2 API library, based on rest-easy."
15
15
  spec.description = spec.summary
16
16
  spec.homepage = "https://github.com/accodeing/checkbiz"
17
- spec.files = Dir["CHANGELOG.md", "LICENSE", "README.md", "checkbiz.gemspec", "lib/**/*", "config/*.yml"]
17
+ spec.files = Dir["CHANGELOG.md", "LICENSE.md", "README.md", "checkbiz.gemspec", "lib/**/*"]
18
18
  spec.bindir = "bin"
19
19
  spec.executables = []
20
20
  spec.require_paths = ["lib"]
21
21
 
22
- spec.required_ruby_version = ">= 3.1.0"
22
+ spec.required_ruby_version = ">= 3.2.0"
23
23
 
24
- spec.add_runtime_dependency "rest-easy", "~> 1.0.0"
25
- spec.add_runtime_dependency "dry-struct"
24
+ spec.add_runtime_dependency "rest-easy", "~> 1.5"
25
+ spec.add_runtime_dependency "faraday", "~> 2.0"
26
+ spec.add_runtime_dependency "zeitwerk", "~> 2.6"
26
27
 
27
28
  spec.add_development_dependency "bundler"
28
29
  spec.add_development_dependency "rake"
29
30
  spec.add_development_dependency "rspec"
30
31
  spec.add_development_dependency "vcr"
31
32
  spec.add_development_dependency "webmock"
33
+
34
+ spec.metadata["rubygems_mfa_required"] = "true"
32
35
  end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "faraday"
4
+ require "json"
5
+
6
+ module Checkbiz
7
+ module Auth
8
+ class AccessToken
9
+ TOKEN_PATH = "authentication/token"
10
+ EXPIRY_MARGIN_IN_SECONDS = 30
11
+ MONOTONIC_CLOCK = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
12
+
13
+ def initialize(username:, password:, base_url: Checkbiz.config.base_url, clock: MONOTONIC_CLOCK)
14
+ @clock = clock
15
+ @connection = Faraday.new(
16
+ url: base_url,
17
+ request: {open_timeout: Checkbiz::OPEN_TIMEOUT_IN_SECONDS, timeout: Checkbiz::TIMEOUT_IN_SECONDS}
18
+ ) do |f|
19
+ f.request :authorization, :basic, username, password
20
+ end
21
+ @mutex = Mutex.new
22
+ end
23
+
24
+ def value
25
+ @mutex.synchronize do
26
+ fetch if @value.nil? || @clock.call >= @expires_at
27
+ @value
28
+ end
29
+ end
30
+
31
+ # Another thread may already have replaced the rejected token, so only drop it if it is still current.
32
+ def invalidate(rejected_value)
33
+ @mutex.synchronize { @value = nil if rejected_value == @value }
34
+ end
35
+
36
+ private
37
+
38
+ def fetch
39
+ response = @connection.post(TOKEN_PATH)
40
+ raise Checkbiz::RequestError.for(response) unless response.success?
41
+
42
+ case parse(response.body)
43
+ in {access_token: String => value, expires_in: Integer => expires_in}
44
+ @value = value
45
+ @expires_at = @clock.call + expires_in - EXPIRY_MARGIN_IN_SECONDS
46
+ else
47
+ raise Checkbiz::Error, "Unexpected response from Checkbiz: #{response.body.to_s[0, 200]}"
48
+ end
49
+ rescue Faraday::Error => e
50
+ raise Checkbiz::ConnectionError, "Could not reach Checkbiz: #{e.message}"
51
+ end
52
+
53
+ def parse(body)
54
+ JSON.parse(body.to_s, symbolize_names: true)
55
+ rescue JSON::ParserError
56
+ nil
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Checkbiz
4
+ module Auth
5
+ class Bearer
6
+ def initialize(access_token)
7
+ @access_token = access_token
8
+ end
9
+
10
+ def apply(request)
11
+ request.headers["Authorization"] = "Bearer #{@access_token.value}"
12
+ end
13
+
14
+ def on_rejected(response)
15
+ raise Checkbiz::RequestError, response unless response.status == 401
16
+
17
+ @access_token.invalidate(response.env.request_headers["Authorization"]&.delete_prefix("Bearer "))
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Checkbiz
4
+ class Company < Checkbiz::Resource
5
+ configure do
6
+ path "company/base"
7
+ end
8
+
9
+ key :organization_number, String
10
+
11
+ attr :name, String
12
+ attr :form, String
13
+ attr :status, String
14
+ attr :status_change_date, Date
15
+ attr :registration_date, Date
16
+ attr :deregistration_date, Date
17
+ attr :seat_municipality_code, String
18
+ attr :care_of, String
19
+ attr :address, String
20
+ attr :zip, String
21
+ attr :city, String
22
+ attr :country_code, String
23
+ attr :phone_number, String
24
+ attr :email, String
25
+ end
26
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Checkbiz
4
+ module ErrorTranslation
5
+ private
6
+
7
+ def with_translated_errors
8
+ yield
9
+ rescue RestEasy::RequestError => e
10
+ raise Error, e.message unless e.response
11
+
12
+ raise RequestError.for(e.response)
13
+ rescue RestEasy::AttributeError => e
14
+ raise AttributeError, e.message
15
+ rescue Faraday::ParsingError => e
16
+ raise Error, "Unexpected response from Checkbiz: #{e.message}"
17
+ rescue Faraday::Error => e
18
+ raise ConnectionError, "Could not reach Checkbiz: #{e.message}"
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,43 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Checkbiz
4
+ class Person < Checkbiz::Resource
5
+ configure do
6
+ path "person/base"
7
+ end
8
+
9
+ key :personal_number, String
10
+
11
+ attr :status, String
12
+ attr :secret_identity, Boolean
13
+ attr :birth_date, Date
14
+ attr :gender, String
15
+ attr :given_name, String
16
+ attr :first_names, String
17
+ attr :last_names, String
18
+ attr :registration_date, Date
19
+ # Not always a valid date: the month or day is 00 when it isn't known, e.g. "2026-03-00".
20
+ attr :deregistration_date, String
21
+ attr :county_code, String
22
+ attr :municipality_code, String
23
+
24
+ # Population register ("folkbokföring") address
25
+ attr :fbf_care_of, String
26
+ attr :fbf_address_prefix, String
27
+ attr :fbf_address, String
28
+ attr :fbf_zip, String
29
+ attr :fbf_city, String
30
+
31
+ # Special postal address
32
+ attr :sp_care_of, String
33
+ attr :sp_address_prefix, String
34
+ attr :sp_address, String
35
+ attr :sp_zip, String
36
+ attr :sp_city, String
37
+
38
+ attr :foreign_address1, String
39
+ attr :foreign_address2, String
40
+ attr :foreign_address3, String
41
+ attr :foreign_country, String
42
+ end
43
+ end
@@ -2,22 +2,24 @@
2
2
 
3
3
  module Checkbiz
4
4
  class Resource < RestEasy::Resource
5
- PARAM_CONVENTION = RestEasy::Conventions::PascalCase.new
5
+ extend ErrorTranslation
6
6
 
7
- before_parse do |data, meta|
8
- meta.response_code = data.delete("responseCode")
9
- meta.response_message = data.delete("responseMessage")
10
- next data
7
+ # Checkbiz sends an empty string for anything it doesn't know.
8
+ before_parse do |data|
9
+ data.is_a?(::Hash) ? data.transform_values { |value| (value == "") ? nil : value } : data
11
10
  end
12
11
 
13
- class << self
14
- def call(**params)
15
- package = params.delete(:package)
16
- headers = package ? { "Package" => package } : {}
17
- api_params = params.transform_keys { |k| PARAM_CONVENTION.serialise(k) }
18
- response = get(path: config.path, params: api_params, headers:)
19
- parse(response)
20
- end
12
+ def self.parse(api_data)
13
+ with_translated_errors { super }
14
+ end
15
+
16
+ # Checkbiz looks entities up with a POST carrying the key in the body, not a GET to path/id.
17
+ def self.find(id)
18
+ key = all_attribute_definitions.fetch(key_attribute_name)
19
+ response = post(path: config.path, body: {key.api_name => id.to_s})
20
+ raise Checkbiz::Error, "Unexpected response from Checkbiz: #{response.to_s[0, 200]}" unless response.is_a?(::Hash)
21
+
22
+ parse(response)
21
23
  end
22
24
  end
23
25
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Checkbiz
4
- VERSION = "1.0.0"
4
+ VERSION = "2.0.0"
5
5
  end
data/lib/checkbiz.rb CHANGED
@@ -4,23 +4,79 @@ require "rest_easy"
4
4
  require "zeitwerk"
5
5
 
6
6
  loader = Zeitwerk::Loader.for_gem
7
- loader.collapse("#{__dir__}/checkbiz/resources")
8
7
  loader.setup
9
8
 
10
9
  module Checkbiz
11
10
  extend RestEasy
11
+ extend ErrorTranslation
12
12
 
13
- class RequestError < RestEasy::Error; end
14
- class AttributeError < RestEasy::Error; end
15
- class ArgumentError < RestEasy::Error; end
13
+ OPEN_TIMEOUT_IN_SECONDS = 5
14
+ TIMEOUT_IN_SECONDS = 10
16
15
 
17
16
  configure do
18
- base_url "https://api.checkbiz.se/api"
17
+ base_url "https://data.checkbiz.se/v2"
19
18
  max_retries 3
20
- authentication RestEasy::Auth::PSK.new(
21
- api_key: "",
22
- header_prefix: "Basic"
23
- )
24
- attribute_convention :CamelCase
19
+ retry_transient_errors true
20
+ conversions.json_attributes = :camelCase
25
21
  end
22
+
23
+ connection do |f|
24
+ f.options.open_timeout = OPEN_TIMEOUT_IN_SECONDS
25
+ f.options.timeout = TIMEOUT_IN_SECONDS
26
+ end
27
+
28
+ class << self
29
+ def authenticate_with(username:, password:)
30
+ config.authentication = Auth::Bearer.new(Auth::AccessToken.new(username:, password:))
31
+ end
32
+
33
+ def ping
34
+ get(path: "ping").to_s.strip == "OK"
35
+ end
36
+
37
+ %i[get post].each do |verb|
38
+ define_method(verb) { |**options| with_translated_errors { super(**options) } }
39
+ end
40
+ end
41
+
42
+ class Error < StandardError; end
43
+
44
+ class ConnectionError < Error; end
45
+
46
+ class AttributeError < Error; end
47
+
48
+ class RequestError < Error
49
+ attr_reader :response
50
+
51
+ def self.for(response)
52
+ (response.status == 401) ? AuthenticationError.new(response) : new(response)
53
+ end
54
+
55
+ def initialize(response)
56
+ @response = response
57
+ super("Request failed: #{response.status}#{details(response.body)}")
58
+ end
59
+
60
+ private
61
+
62
+ # JSON errors carry {"errorMessages": [...]}, parsed or not; some, like 401 and 403, are plain text.
63
+ def details(body)
64
+ body = parse(body) if body.is_a?(String)
65
+ messages =
66
+ if body.is_a?(Hash) && body["errorMessages"].is_a?(Array) then body["errorMessages"]
67
+ elsif body.is_a?(String) || body.nil? then [body]
68
+ else [JSON.generate(body)]
69
+ end
70
+ text = messages.map { |message| message.to_s.strip }.reject(&:empty?).join(", ")
71
+ text.empty? ? "" : " - #{text}"
72
+ end
73
+
74
+ def parse(body)
75
+ JSON.parse(body)
76
+ rescue JSON::ParserError
77
+ body
78
+ end
79
+ end
80
+
81
+ class AuthenticationError < RequestError; end
26
82
  end