accreditednow 1.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 AccreditedNow LLC
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.
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: accreditednow
3
+ Version: 1.1.0
4
+ Summary: Official AccreditedNow API client: CPA-signed accredited investor verification for Rule 506(c), investor screening and signed webhooks.
5
+ Author: AccreditedNow LLC
6
+ License: MIT
7
+ Project-URL: Homepage, https://accreditednow.org/developers
8
+ Project-URL: Documentation, https://accreditednow.org/verification-api
9
+ Keywords: accredited investor,506(c),verification,kyc,aml
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # AccreditedNow for Python
16
+
17
+ The official client for the [AccreditedNow API](https://accreditednow.org/verification-api): CPA-signed accredited investor verification for Rule 506(c), investor sanctions screening, and signed webhooks. Python 3.8 or newer; standard library only.
18
+
19
+ ```
20
+ pip install https://accreditednow.org/sdk/accreditednow-1.1.0-py3-none-any.whl
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ ```python
26
+ import os
27
+ from accreditednow import AccreditedNow, AccreditedNowError
28
+
29
+ an = AccreditedNow(os.environ["ACCREDITEDNOW_API_KEY"]) # sk_test_... for the sandbox
30
+
31
+ v = an.verifications.create({
32
+ "investor": {"first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com"},
33
+ "external_id": "crm-123",
34
+ })
35
+ print(v["hosted_url"]) # send the investor here
36
+
37
+ latest = an.verifications.retrieve(v["id"])
38
+ if latest["needs_info"]:
39
+ print("The CPA asked for more documents on", latest["documents_requested_at"])
40
+
41
+ for x in an.verifications.list_all(status="verified"):
42
+ print(x["id"], x["expiration_date"])
43
+
44
+ an.verifications.request_reconfirmation(v["id"]) # emails the investor a re-confirmation link
45
+ print(an.verifications.letter_url(v["id"])["letter_url"])
46
+ ```
47
+
48
+ Creates and other de-duplicated POSTs get an `Idempotency-Key` automatically, so the client can retry them safely after a timeout. Pass `idempotency_key="..."` to use your own.
49
+
50
+ Errors raise `AccreditedNowError` with `status`, `type` (the API's error type, e.g. `not_found`), `param` and `retry_at`.
51
+
52
+ ## Webhooks
53
+
54
+ ```python
55
+ from accreditednow import webhooks
56
+
57
+ # Flask: use the RAW body (request.get_data()), not parsed JSON.
58
+ @app.post("/accreditednow")
59
+ def hook():
60
+ try:
61
+ event = webhooks.construct_event(request.get_data(), request.headers.get("X-AccreditedNow-Signature"), os.environ["ACCREDITEDNOW_WEBHOOK_SECRET"])
62
+ except AccreditedNowError:
63
+ return "", 400
64
+ if event["event"] == "verification.needs_info":
65
+ pass # nudge the investor
66
+ return "", 200
67
+ ```
68
+
69
+ ## Sandbox
70
+
71
+ With an `sk_test_` key, `an.verifications.complete(id)` and `an.verifications.request_documents(id)` simulate the CPA's decision and send `livemode: false` webhooks to your endpoint.
72
+
73
+ ## All methods
74
+
75
+ - `verifications`: `create`, `list`, `list_all`, `retrieve`, `letter_url`, `request_reconfirmation`, `add_photo_id`, `add_owner`, `remove_owner`, `complete` (sandbox), `request_documents` (sandbox)
76
+ - `funds`: `list`, `create`
77
+ - `screenings`: `create`, `list`, `list_all`, `retrieve`, `remove`, `dismiss`, `contact.get`, `contact.set`, `contact.clear`
78
+ - `webhooks`: `verify`, `construct_event`, `sign`
79
+
80
+ Full reference: https://accreditednow.org/verification-api · OpenAPI: https://accreditednow.org/openapi-v1.json
@@ -0,0 +1,66 @@
1
+ # AccreditedNow for Python
2
+
3
+ The official client for the [AccreditedNow API](https://accreditednow.org/verification-api): CPA-signed accredited investor verification for Rule 506(c), investor sanctions screening, and signed webhooks. Python 3.8 or newer; standard library only.
4
+
5
+ ```
6
+ pip install https://accreditednow.org/sdk/accreditednow-1.1.0-py3-none-any.whl
7
+ ```
8
+
9
+ ## Quick start
10
+
11
+ ```python
12
+ import os
13
+ from accreditednow import AccreditedNow, AccreditedNowError
14
+
15
+ an = AccreditedNow(os.environ["ACCREDITEDNOW_API_KEY"]) # sk_test_... for the sandbox
16
+
17
+ v = an.verifications.create({
18
+ "investor": {"first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com"},
19
+ "external_id": "crm-123",
20
+ })
21
+ print(v["hosted_url"]) # send the investor here
22
+
23
+ latest = an.verifications.retrieve(v["id"])
24
+ if latest["needs_info"]:
25
+ print("The CPA asked for more documents on", latest["documents_requested_at"])
26
+
27
+ for x in an.verifications.list_all(status="verified"):
28
+ print(x["id"], x["expiration_date"])
29
+
30
+ an.verifications.request_reconfirmation(v["id"]) # emails the investor a re-confirmation link
31
+ print(an.verifications.letter_url(v["id"])["letter_url"])
32
+ ```
33
+
34
+ Creates and other de-duplicated POSTs get an `Idempotency-Key` automatically, so the client can retry them safely after a timeout. Pass `idempotency_key="..."` to use your own.
35
+
36
+ Errors raise `AccreditedNowError` with `status`, `type` (the API's error type, e.g. `not_found`), `param` and `retry_at`.
37
+
38
+ ## Webhooks
39
+
40
+ ```python
41
+ from accreditednow import webhooks
42
+
43
+ # Flask: use the RAW body (request.get_data()), not parsed JSON.
44
+ @app.post("/accreditednow")
45
+ def hook():
46
+ try:
47
+ event = webhooks.construct_event(request.get_data(), request.headers.get("X-AccreditedNow-Signature"), os.environ["ACCREDITEDNOW_WEBHOOK_SECRET"])
48
+ except AccreditedNowError:
49
+ return "", 400
50
+ if event["event"] == "verification.needs_info":
51
+ pass # nudge the investor
52
+ return "", 200
53
+ ```
54
+
55
+ ## Sandbox
56
+
57
+ With an `sk_test_` key, `an.verifications.complete(id)` and `an.verifications.request_documents(id)` simulate the CPA's decision and send `livemode: false` webhooks to your endpoint.
58
+
59
+ ## All methods
60
+
61
+ - `verifications`: `create`, `list`, `list_all`, `retrieve`, `letter_url`, `request_reconfirmation`, `add_photo_id`, `add_owner`, `remove_owner`, `complete` (sandbox), `request_documents` (sandbox)
62
+ - `funds`: `list`, `create`
63
+ - `screenings`: `create`, `list`, `list_all`, `retrieve`, `remove`, `dismiss`, `contact.get`, `contact.set`, `contact.clear`
64
+ - `webhooks`: `verify`, `construct_event`, `sign`
65
+
66
+ Full reference: https://accreditednow.org/verification-api · OpenAPI: https://accreditednow.org/openapi-v1.json
@@ -0,0 +1,16 @@
1
+ """Official AccreditedNow API client (Python 3.8+, standard library only).
2
+
3
+ Docs: https://accreditednow.org/verification-api
4
+ Spec: https://accreditednow.org/openapi-v1.json
5
+
6
+ from accreditednow import AccreditedNow
7
+ an = AccreditedNow("sk_test_...")
8
+ v = an.verifications.create({"investor": {"first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com"}})
9
+ print(v["hosted_url"])
10
+ """
11
+
12
+ from .client import AccreditedNow, AccreditedNowError, VERSION
13
+ from . import webhooks
14
+
15
+ __all__ = ["AccreditedNow", "AccreditedNowError", "webhooks", "VERSION"]
16
+ __version__ = VERSION
@@ -0,0 +1,233 @@
1
+ import json
2
+ import random
3
+ import secrets
4
+ import time
5
+ import urllib.error
6
+ import urllib.parse
7
+ import urllib.request
8
+
9
+ VERSION = "1.1.0"
10
+ DEFAULT_BASE = "https://accreditednow.org/v1"
11
+
12
+
13
+ class AccreditedNowError(Exception):
14
+ """An error from the API (or the network). `type` is the API's error.type, e.g. "not_found"."""
15
+
16
+ def __init__(self, message, status=0, type="api_error", param=None, retry_at=None, body=None):
17
+ super().__init__(message)
18
+ self.message = message
19
+ self.status = status
20
+ self.type = type
21
+ self.param = param
22
+ self.retry_at = retry_at
23
+ self.body = body
24
+
25
+
26
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
27
+ def redirect_request(self, *args, **kwargs): # never follow redirects with our key attached
28
+ return None
29
+
30
+
31
+ def _enc(value):
32
+ s = "" if value is None else str(value)
33
+ if not s:
34
+ raise AccreditedNowError("An id is required.", type="invalid_request")
35
+ return urllib.parse.quote(s, safe="")
36
+
37
+
38
+ def _qs(params):
39
+ items = [(k, str(v).lower() if isinstance(v, bool) else str(v)) for k, v in (params or {}).items() if v not in (None, "")]
40
+ return ("?" + urllib.parse.urlencode(items)) if items else ""
41
+
42
+
43
+ def _new_key():
44
+ return "idem_" + secrets.token_hex(16)
45
+
46
+
47
+ def _backoff(n):
48
+ return min(8.0, 0.5 * (2 ** (n - 1))) + random.random() * 0.25
49
+
50
+
51
+ class AccreditedNow:
52
+ """AccreditedNow(api_key, base_url=..., timeout=30, max_retries=2)"""
53
+
54
+ def __init__(self, api_key, base_url=DEFAULT_BASE, timeout=30, max_retries=2):
55
+ if not api_key or not (str(api_key).startswith("sk_live_") or str(api_key).startswith("sk_test_")):
56
+ raise AccreditedNowError("Pass your API key (sk_live_... or sk_test_...). Create one on your AccreditedNow dashboard.", type="invalid_api_key")
57
+ self._key = str(api_key)
58
+ self.base_url = str(base_url).rstrip("/")
59
+ self.timeout = timeout
60
+ self.max_retries = max(0, int(max_retries))
61
+ self.testmode = self._key.startswith("sk_test_")
62
+ self._opener = urllib.request.build_opener(_NoRedirect)
63
+ self.verifications = _Verifications(self)
64
+ self.events = _Events(self)
65
+ self.funds = _Funds(self)
66
+ self.screenings = _Screenings(self)
67
+
68
+ def _iterate(self, path, params):
69
+ p = dict({"limit": 100}, **(params or {}))
70
+ offset = int(p.get("offset") or 0)
71
+ while True:
72
+ p["offset"] = offset
73
+ page = self._request("GET", path + _qs(p))
74
+ data = (page or {}).get("data") or []
75
+ for item in data:
76
+ yield item
77
+ if not page or not page.get("has_more") or not data:
78
+ return
79
+ offset += len(data)
80
+
81
+ def _request(self, method, path, body=None, idempotency_key=None, retry_safe=False):
82
+ headers = {
83
+ "Authorization": "Bearer " + self._key,
84
+ "Accept": "application/json",
85
+ "User-Agent": "accreditednow-python/" + VERSION,
86
+ }
87
+ data = None
88
+ if body is not None:
89
+ headers["Content-Type"] = "application/json"
90
+ data = json.dumps(body).encode("utf-8")
91
+ if idempotency_key:
92
+ headers["Idempotency-Key"] = str(idempotency_key)
93
+ # GET and DELETE are safe to retry; a POST only when it carries an Idempotency-Key.
94
+ can_retry = method in ("GET", "DELETE") or (retry_safe and bool(idempotency_key))
95
+ attempt = 0
96
+ while True:
97
+ req = urllib.request.Request(self.base_url + path, data=data, headers=headers, method=method)
98
+ status, text, retry_after = 0, "", None
99
+ try:
100
+ with self._opener.open(req, timeout=self.timeout) as r:
101
+ status, text = r.status, r.read().decode("utf-8")
102
+ except urllib.error.HTTPError as e:
103
+ status = e.code
104
+ text = e.read().decode("utf-8", "replace") if e.fp else ""
105
+ retry_after = e.headers.get("Retry-After") if e.headers else None
106
+ except (urllib.error.URLError, OSError) as e:
107
+ if can_retry and attempt < self.max_retries:
108
+ attempt += 1
109
+ time.sleep(_backoff(attempt))
110
+ continue
111
+ raise AccreditedNowError("Could not reach AccreditedNow: %s" % e, status=0, type="network_error")
112
+ try:
113
+ parsed = json.loads(text) if text else None
114
+ except ValueError:
115
+ parsed = None
116
+ if 200 <= status < 300:
117
+ return parsed
118
+ in_progress = status == 409 and isinstance(parsed, dict) and (parsed.get("error") or {}).get("type") == "idempotency_in_progress"
119
+ if can_retry and attempt < self.max_retries and (status == 429 or status >= 500 or in_progress):
120
+ attempt += 1
121
+ try:
122
+ wait = min(60, int(retry_after)) if retry_after else _backoff(attempt)
123
+ except ValueError:
124
+ wait = _backoff(attempt)
125
+ time.sleep(wait)
126
+ continue
127
+ err = (parsed or {}).get("error") or {} if isinstance(parsed, dict) else {}
128
+ raise AccreditedNowError(err.get("message") or ("HTTP %d" % status), status=status, type=err.get("type") or "api_error",
129
+ param=err.get("param"), retry_at=err.get("retry_at"), body=parsed)
130
+
131
+ # A POST the API de-duplicates gets an Idempotency-Key, so a retry after a timeout can
132
+ # never create two records. Pass your own key to dedupe across process restarts.
133
+ def _post_safe(self, path, body, idempotency_key):
134
+ return self._request("POST", path, body if body is not None else {}, idempotency_key or _new_key(), retry_safe=True)
135
+
136
+
137
+ class _Verifications:
138
+ def __init__(self, c):
139
+ self._c = c
140
+
141
+ def create(self, body, idempotency_key=None):
142
+ return self._c._post_safe("/verifications", body or {}, idempotency_key)
143
+
144
+ def list(self, **params):
145
+ return self._c._request("GET", "/verifications" + _qs(params))
146
+
147
+ def list_all(self, **params):
148
+ return self._c._iterate("/verifications", params)
149
+
150
+ def retrieve(self, id):
151
+ return self._c._request("GET", "/verifications/" + _enc(id))
152
+
153
+ def letter_url(self, id):
154
+ """{"id", "letter_url"}: the signed letter (short-lived URL; download it promptly)."""
155
+ return self._c._request("GET", "/verifications/" + _enc(id) + "/letter?format=json")
156
+
157
+ def request_reconfirmation(self, id, idempotency_key=None):
158
+ return self._c._post_safe("/verifications/" + _enc(id) + "/reconfirmation-request", {}, idempotency_key)
159
+
160
+ def add_photo_id(self, id, body, idempotency_key=None):
161
+ return self._c._post_safe("/verifications/" + _enc(id) + "/photo-id", body or {}, idempotency_key)
162
+
163
+ def add_owner(self, id, owner, idempotency_key=None):
164
+ return self._c._post_safe("/verifications/" + _enc(id) + "/owners", owner or {}, idempotency_key)
165
+
166
+ def remove_owner(self, id, owner_id):
167
+ return self._c._request("DELETE", "/verifications/" + _enc(id) + "/owners/" + _enc(owner_id))
168
+
169
+ # Sandbox (sk_test_) only:
170
+ def complete(self, id):
171
+ return self._c._request("POST", "/verifications/" + _enc(id) + "/complete", {})
172
+
173
+ def request_documents(self, id):
174
+ return self._c._request("POST", "/verifications/" + _enc(id) + "/request-documents", {})
175
+
176
+
177
+ class _Events:
178
+ """Recent events (the same envelopes as the webhook, kept 30 days). params: type, limit, since."""
179
+
180
+ def __init__(self, c):
181
+ self._c = c
182
+
183
+ def list(self, params=None):
184
+ return self._c._request("GET", "/events" + _qs(params))
185
+
186
+
187
+ class _Funds:
188
+ def __init__(self, c):
189
+ self._c = c
190
+
191
+ def list(self):
192
+ return self._c._request("GET", "/funds")
193
+
194
+ def create(self, body):
195
+ return self._c._request("POST", "/funds", body or {})
196
+
197
+
198
+ class _Contact:
199
+ def __init__(self, c):
200
+ self._c = c
201
+
202
+ def get(self):
203
+ return self._c._request("GET", "/screenings/contact")
204
+
205
+ def set(self, body):
206
+ return self._c._request("PUT", "/screenings/contact", body or {})
207
+
208
+ def clear(self):
209
+ return self._c._request("DELETE", "/screenings/contact")
210
+
211
+
212
+ class _Screenings:
213
+ def __init__(self, c):
214
+ self._c = c
215
+ self.contact = _Contact(c)
216
+
217
+ def create(self, body, idempotency_key=None):
218
+ return self._c._post_safe("/screenings", body or {}, idempotency_key)
219
+
220
+ def list(self, **params):
221
+ return self._c._request("GET", "/screenings" + _qs(params))
222
+
223
+ def list_all(self, **params):
224
+ return self._c._iterate("/screenings", params)
225
+
226
+ def retrieve(self, id):
227
+ return self._c._request("GET", "/screenings/" + _enc(id))
228
+
229
+ def remove(self, id):
230
+ return self._c._request("DELETE", "/screenings/" + _enc(id))
231
+
232
+ def dismiss(self, id, note=None):
233
+ return self._c._request("POST", "/screenings/" + _enc(id) + "/dismiss", {"note": note} if note else {})
@@ -0,0 +1,53 @@
1
+ """Verify AccreditedNow webhook signatures.
2
+
3
+ Header: X-AccreditedNow-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">
4
+ Pass the raw request body exactly as received (bytes or str), not re-serialized JSON.
5
+ """
6
+ import hashlib
7
+ import hmac
8
+ import json
9
+ import time
10
+
11
+ from .client import AccreditedNowError
12
+
13
+
14
+ def _parse(header):
15
+ out = {}
16
+ for part in str(header or "").split(","):
17
+ if "=" in part:
18
+ k, v = part.split("=", 1)
19
+ out[k.strip()] = v.strip()
20
+ return out
21
+
22
+
23
+ def _raw(body):
24
+ return body.decode("utf-8") if isinstance(body, (bytes, bytearray)) else str(body)
25
+
26
+
27
+ def sign(raw_body, secret, ts=None):
28
+ """A signature header for a body you build (for your own tests)."""
29
+ t = int(ts or time.time())
30
+ mac = hmac.new(str(secret).encode("utf-8"), ("%d.%s" % (t, _raw(raw_body))).encode("utf-8"), hashlib.sha256).hexdigest()
31
+ return "t=%d,v1=%s" % (t, mac)
32
+
33
+
34
+ def verify(raw_body, signature_header, secret, tolerance=300):
35
+ """True when the signature is valid and no older than `tolerance` seconds."""
36
+ try:
37
+ p = _parse(signature_header)
38
+ t = int(p.get("t") or 0)
39
+ if not t or not p.get("v1") or not secret:
40
+ return False
41
+ if abs(int(time.time()) - t) > tolerance:
42
+ return False
43
+ expected = hmac.new(str(secret).encode("utf-8"), ("%d.%s" % (t, _raw(raw_body))).encode("utf-8"), hashlib.sha256).hexdigest()
44
+ return hmac.compare_digest(expected, p["v1"])
45
+ except Exception:
46
+ return False
47
+
48
+
49
+ def construct_event(raw_body, signature_header, secret, tolerance=300):
50
+ """The parsed event dict, or raises AccreditedNowError(type="invalid_signature")."""
51
+ if not verify(raw_body, signature_header, secret, tolerance):
52
+ raise AccreditedNowError("Webhook signature is not valid (or is older than the tolerance).", type="invalid_signature")
53
+ return json.loads(_raw(raw_body))
@@ -0,0 +1,80 @@
1
+ Metadata-Version: 2.4
2
+ Name: accreditednow
3
+ Version: 1.1.0
4
+ Summary: Official AccreditedNow API client: CPA-signed accredited investor verification for Rule 506(c), investor screening and signed webhooks.
5
+ Author: AccreditedNow LLC
6
+ License: MIT
7
+ Project-URL: Homepage, https://accreditednow.org/developers
8
+ Project-URL: Documentation, https://accreditednow.org/verification-api
9
+ Keywords: accredited investor,506(c),verification,kyc,aml
10
+ Requires-Python: >=3.8
11
+ Description-Content-Type: text/markdown
12
+ License-File: LICENSE
13
+ Dynamic: license-file
14
+
15
+ # AccreditedNow for Python
16
+
17
+ The official client for the [AccreditedNow API](https://accreditednow.org/verification-api): CPA-signed accredited investor verification for Rule 506(c), investor sanctions screening, and signed webhooks. Python 3.8 or newer; standard library only.
18
+
19
+ ```
20
+ pip install https://accreditednow.org/sdk/accreditednow-1.1.0-py3-none-any.whl
21
+ ```
22
+
23
+ ## Quick start
24
+
25
+ ```python
26
+ import os
27
+ from accreditednow import AccreditedNow, AccreditedNowError
28
+
29
+ an = AccreditedNow(os.environ["ACCREDITEDNOW_API_KEY"]) # sk_test_... for the sandbox
30
+
31
+ v = an.verifications.create({
32
+ "investor": {"first_name": "Ada", "last_name": "Lovelace", "email": "ada@example.com"},
33
+ "external_id": "crm-123",
34
+ })
35
+ print(v["hosted_url"]) # send the investor here
36
+
37
+ latest = an.verifications.retrieve(v["id"])
38
+ if latest["needs_info"]:
39
+ print("The CPA asked for more documents on", latest["documents_requested_at"])
40
+
41
+ for x in an.verifications.list_all(status="verified"):
42
+ print(x["id"], x["expiration_date"])
43
+
44
+ an.verifications.request_reconfirmation(v["id"]) # emails the investor a re-confirmation link
45
+ print(an.verifications.letter_url(v["id"])["letter_url"])
46
+ ```
47
+
48
+ Creates and other de-duplicated POSTs get an `Idempotency-Key` automatically, so the client can retry them safely after a timeout. Pass `idempotency_key="..."` to use your own.
49
+
50
+ Errors raise `AccreditedNowError` with `status`, `type` (the API's error type, e.g. `not_found`), `param` and `retry_at`.
51
+
52
+ ## Webhooks
53
+
54
+ ```python
55
+ from accreditednow import webhooks
56
+
57
+ # Flask: use the RAW body (request.get_data()), not parsed JSON.
58
+ @app.post("/accreditednow")
59
+ def hook():
60
+ try:
61
+ event = webhooks.construct_event(request.get_data(), request.headers.get("X-AccreditedNow-Signature"), os.environ["ACCREDITEDNOW_WEBHOOK_SECRET"])
62
+ except AccreditedNowError:
63
+ return "", 400
64
+ if event["event"] == "verification.needs_info":
65
+ pass # nudge the investor
66
+ return "", 200
67
+ ```
68
+
69
+ ## Sandbox
70
+
71
+ With an `sk_test_` key, `an.verifications.complete(id)` and `an.verifications.request_documents(id)` simulate the CPA's decision and send `livemode: false` webhooks to your endpoint.
72
+
73
+ ## All methods
74
+
75
+ - `verifications`: `create`, `list`, `list_all`, `retrieve`, `letter_url`, `request_reconfirmation`, `add_photo_id`, `add_owner`, `remove_owner`, `complete` (sandbox), `request_documents` (sandbox)
76
+ - `funds`: `list`, `create`
77
+ - `screenings`: `create`, `list`, `list_all`, `retrieve`, `remove`, `dismiss`, `contact.get`, `contact.set`, `contact.clear`
78
+ - `webhooks`: `verify`, `construct_event`, `sign`
79
+
80
+ Full reference: https://accreditednow.org/verification-api · OpenAPI: https://accreditednow.org/openapi-v1.json
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ accreditednow/__init__.py
5
+ accreditednow/client.py
6
+ accreditednow/webhooks.py
7
+ accreditednow.egg-info/PKG-INFO
8
+ accreditednow.egg-info/SOURCES.txt
9
+ accreditednow.egg-info/dependency_links.txt
10
+ accreditednow.egg-info/top_level.txt
11
+ tests/test_client.py
@@ -0,0 +1 @@
1
+ accreditednow
@@ -0,0 +1,20 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "accreditednow"
7
+ version = "1.1.0"
8
+ description = "Official AccreditedNow API client: CPA-signed accredited investor verification for Rule 506(c), investor screening and signed webhooks."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "AccreditedNow LLC" }]
13
+ keywords = ["accredited investor", "506(c)", "verification", "kyc", "aml"]
14
+
15
+ [project.urls]
16
+ Homepage = "https://accreditednow.org/developers"
17
+ Documentation = "https://accreditednow.org/verification-api"
18
+
19
+ [tool.setuptools]
20
+ packages = ["accreditednow"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,113 @@
1
+ """Offline tests: a local HTTP server stands in for the API. Run: python3 tests/test_client.py"""
2
+ import json
3
+ import os
4
+ import sys
5
+ import threading
6
+ import time
7
+ from http.server import BaseHTTPRequestHandler, HTTPServer
8
+ from urllib.parse import urlparse, parse_qs
9
+
10
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
11
+ from accreditednow import AccreditedNow, AccreditedNowError, webhooks # noqa: E402
12
+
13
+ SEEN = []
14
+ STATE = {"fail": 0}
15
+
16
+
17
+ class H(BaseHTTPRequestHandler):
18
+ def log_message(self, *a):
19
+ pass
20
+
21
+ def _j(self, code, obj):
22
+ b = json.dumps(obj).encode()
23
+ self.send_response(code)
24
+ self.send_header("Content-Type", "application/json")
25
+ self.send_header("Content-Length", str(len(b)))
26
+ self.end_headers()
27
+ self.wfile.write(b)
28
+
29
+ def _any(self):
30
+ n = int(self.headers.get("Content-Length") or 0)
31
+ body = self.rfile.read(n).decode() if n else ""
32
+ SEEN.append({"method": self.command, "path": self.path, "headers": dict(self.headers), "body": body})
33
+ if self.headers.get("Authorization") != "Bearer sk_test_abc":
34
+ return self._j(401, {"error": {"type": "unauthorized", "message": "bad key"}})
35
+ if self.path == "/v1/verifications" and self.command == "POST":
36
+ if STATE["fail"]:
37
+ STATE["fail"] -= 1
38
+ return self._j(503, {"error": {"type": "server_error", "message": "again"}})
39
+ return self._j(201, {"id": "ver_test_1", "object": "verification", "status": "created"})
40
+ if self.path.startswith("/v1/verifications?"):
41
+ off = int(parse_qs(urlparse(self.path).query).get("offset", ["0"])[0])
42
+ data = [{"id": x} for x in ["a", "b", "c"]][off:off + 2]
43
+ return self._j(200, {"object": "list", "data": data, "total": 3, "limit": 2, "offset": off, "has_more": off + 2 < 3})
44
+ if self.path == "/v1/verifications/ver_test_1/reconfirmation-request":
45
+ return self._j(409, {"error": {"type": "reconfirmation_too_soon", "message": "wait", "retry_at": "2026-11-20T00:00:00Z"}})
46
+ if self.path == "/v1/verifications/ver_test_1/letter?format=json":
47
+ return self._j(200, {"id": "ver_test_1", "letter_url": "https://cdn/x.pdf"})
48
+ return self._j(404, {"error": {"type": "not_found", "message": "Unknown endpoint."}})
49
+
50
+ do_GET = do_POST = do_PUT = do_DELETE = _any
51
+
52
+
53
+ def main():
54
+ srv = HTTPServer(("127.0.0.1", 0), H)
55
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
56
+ base = "http://127.0.0.1:%d/v1" % srv.server_address[1]
57
+ an = AccreditedNow("sk_test_abc", base_url=base)
58
+ assert an.testmode
59
+
60
+ try:
61
+ AccreditedNow("nope")
62
+ raise AssertionError("expected an error")
63
+ except AccreditedNowError as e:
64
+ assert e.type == "invalid_api_key"
65
+
66
+ STATE["fail"] = 1
67
+ v = an.verifications.create({"investor": {"email": "a@b.co"}})
68
+ assert v["id"] == "ver_test_1"
69
+ posts = [s for s in SEEN if s["method"] == "POST" and s["path"] == "/v1/verifications"]
70
+ assert len(posts) == 2
71
+ keys = [p["headers"].get("Idempotency-Key") for p in posts]
72
+ assert keys[0].startswith("idem_") and keys[0] == keys[1]
73
+ assert json.loads(posts[0]["body"]) == {"investor": {"email": "a@b.co"}}
74
+
75
+ assert [x["id"] for x in an.verifications.list_all(status="verified")] == ["a", "b", "c"]
76
+
77
+ try:
78
+ an.verifications.request_reconfirmation("ver_test_1")
79
+ raise AssertionError("expected 409")
80
+ except AccreditedNowError as e:
81
+ assert e.status == 409 and e.type == "reconfirmation_too_soon" and e.retry_at == "2026-11-20T00:00:00Z"
82
+ try:
83
+ an.verifications.retrieve("ver/1")
84
+ raise AssertionError("expected 404")
85
+ except AccreditedNowError as e:
86
+ assert e.status == 404 and e.type == "not_found"
87
+ assert an.verifications.letter_url("ver_test_1")["letter_url"] == "https://cdn/x.pdf"
88
+
89
+ secret = "whsec_test"
90
+ raw = json.dumps({"id": "evt_1", "event": "verification.needs_info", "data": {}})
91
+ hdr = webhooks.sign(raw, secret)
92
+ assert webhooks.verify(raw, hdr, secret)
93
+ assert webhooks.verify(raw.encode(), hdr, secret)
94
+ assert not webhooks.verify(raw + " ", hdr, secret)
95
+ assert not webhooks.verify(raw, hdr, "other")
96
+ assert not webhooks.verify(raw, webhooks.sign(raw, secret, int(time.time()) - 1000), secret)
97
+ assert webhooks.construct_event(raw, hdr, secret)["event"] == "verification.needs_info"
98
+ try:
99
+ webhooks.construct_event(raw, "t=1,v1=00", secret)
100
+ raise AssertionError("expected invalid_signature")
101
+ except AccreditedNowError as e:
102
+ assert e.type == "invalid_signature"
103
+
104
+ # Same signature as the Node SDK / server for a fixed timestamp.
105
+ fixed = os.environ.get("AN_SIG_CHECK")
106
+ if fixed:
107
+ assert webhooks.sign(raw, secret, 1700000000) == fixed, "signature mismatch with server"
108
+ srv.shutdown()
109
+ print("python sdk: all tests passed")
110
+
111
+
112
+ if __name__ == "__main__":
113
+ main()