clikgate 2.0.0__py3-none-any.whl

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.
clikgate/__init__.py ADDED
@@ -0,0 +1,176 @@
1
+ """The official Clikgate server SDK for Python.
2
+
3
+ Example::
4
+
5
+ from decimal import Decimal
6
+ from clikgate import Clikgate
7
+
8
+ clikgate = Clikgate() # reads CLIKGATE_API_KEY
9
+ clikgate.goal("account_opened", click_id=click_id, reference="APP-55231", value=Decimal("2000000"))
10
+ """
11
+
12
+ from . import webhooks
13
+ from ._ads_hashing import HashedIdentifiers, hash_for_ads
14
+ from ._click_ids import (
15
+ BROWSER_ENGINES,
16
+ CLICK_ID_HEADER,
17
+ CLICK_ID_PATTERN,
18
+ KEPT_BY,
19
+ KEPT_COOKIE,
20
+ PLATFORMS,
21
+ ClickContext,
22
+ ClickIds,
23
+ KeepResponse,
24
+ KeepRoute,
25
+ click_ids,
26
+ is_valid,
27
+ )
28
+ from ._client import AsyncClikgate, Clikgate, PersonIdentified
29
+ from ._core import ErrorContext, OnError
30
+ from ._enums import GoalKind, GoalStatus, Provider
31
+ from ._errors import (
32
+ AuthenticationError,
33
+ ClikgateError,
34
+ ClikgateServerOnlyError,
35
+ ConfigurationError,
36
+ ConflictError,
37
+ IdempotencyError,
38
+ InvalidRequestError,
39
+ LinkLockedError,
40
+ NetworkError,
41
+ NotFoundError,
42
+ PermissionError,
43
+ PrivateModeFieldRejectedError,
44
+ RateLimitError,
45
+ ServerError,
46
+ SignatureVerificationError,
47
+ TimeoutError,
48
+ )
49
+ from ._goals import AsyncGoals, GoalBatchEvent, Goals
50
+ from ._http import Clock, RequestOptions
51
+ from ._identity import IDENTITY_SECRET_ENV, IDENTITY_SECRETS_ENV, create_identity_token
52
+ from ._money import MoneyInput, format_value
53
+ from ._payments import AsyncPayments, Payments, build_from_flutterwave, build_from_monnify, build_from_paystack, build_from_stripe
54
+ from ._resources import AsyncClicks, AsyncConversions, AsyncLinks, Clicks, Conversions, Links
55
+ from ._types import (
56
+ Click,
57
+ ConfigGoal,
58
+ Conversion,
59
+ GoalAttribution,
60
+ GoalBatchItem,
61
+ GoalBatchResult,
62
+ GoalEvent,
63
+ GoalPaymentInfo,
64
+ Link,
65
+ LinkChangeRequest,
66
+ LinkPage,
67
+ LinkUpdateResult,
68
+ LinkWarning,
69
+ PaymentConfirmation,
70
+ PaymentConfirmationBody,
71
+ QrCode,
72
+ ServerSdkConfig,
73
+ WebhookEvent,
74
+ )
75
+ from ._version import VERSION
76
+ from .webhooks import RawBody
77
+
78
+ __version__ = VERSION
79
+
80
+ #: Stable warning codes (SPEC section 15), passed as ``extra={"clikgate_code": code}``.
81
+ WARNING_CODES = (
82
+ "inexact_number",
83
+ "unknown_goal",
84
+ "value_not_allowed",
85
+ "value_required",
86
+ "config_unavailable",
87
+ "sdk_below_minimum_version",
88
+ "queue_full_dropped",
89
+ "unrecognised_payment_response",
90
+ )
91
+
92
+ __all__ = [
93
+ "PersonIdentified",
94
+ "CLICK_ID_HEADER",
95
+ "CLICK_ID_PATTERN",
96
+ "VERSION",
97
+ "WARNING_CODES",
98
+ "AsyncClicks",
99
+ "AsyncClikgate",
100
+ "AsyncConversions",
101
+ "AsyncGoals",
102
+ "AsyncLinks",
103
+ "AsyncPayments",
104
+ "AuthenticationError",
105
+ "BROWSER_ENGINES",
106
+ "Click",
107
+ "ClickContext",
108
+ "ClickIds",
109
+ "Clicks",
110
+ "Clikgate",
111
+ "ClikgateError",
112
+ "Clock",
113
+ "ConfigGoal",
114
+ "ConfigurationError",
115
+ "ConflictError",
116
+ "Conversion",
117
+ "Conversions",
118
+ "ErrorContext",
119
+ "GoalAttribution",
120
+ "GoalBatchEvent",
121
+ "GoalBatchItem",
122
+ "GoalBatchResult",
123
+ "GoalEvent",
124
+ "GoalKind",
125
+ "GoalPaymentInfo",
126
+ "GoalStatus",
127
+ "HashedIdentifiers",
128
+ "Goals",
129
+ "IdempotencyError",
130
+ "InvalidRequestError",
131
+ "KEPT_BY",
132
+ "KEPT_COOKIE",
133
+ "KeepResponse",
134
+ "KeepRoute",
135
+ "Link",
136
+ "LinkChangeRequest",
137
+ "LinkLockedError",
138
+ "LinkPage",
139
+ "LinkUpdateResult",
140
+ "LinkWarning",
141
+ "Links",
142
+ "MoneyInput",
143
+ "NetworkError",
144
+ "NotFoundError",
145
+ "OnError",
146
+ "PLATFORMS",
147
+ "PaymentConfirmation",
148
+ "PaymentConfirmationBody",
149
+ "Payments",
150
+ "PermissionError",
151
+ "PrivateModeFieldRejectedError",
152
+ "Provider",
153
+ "QrCode",
154
+ "RateLimitError",
155
+ "RawBody",
156
+ "RequestOptions",
157
+ "ServerError",
158
+ "ServerSdkConfig",
159
+ "SignatureVerificationError",
160
+ "ClikgateServerOnlyError",
161
+ "create_identity_token",
162
+ "IDENTITY_SECRET_ENV",
163
+ "IDENTITY_SECRETS_ENV",
164
+ "TimeoutError",
165
+ "WebhookEvent",
166
+ "__version__",
167
+ "build_from_flutterwave",
168
+ "build_from_monnify",
169
+ "build_from_paystack",
170
+ "build_from_stripe",
171
+ "click_ids",
172
+ "format_value",
173
+ "hash_for_ads",
174
+ "is_valid",
175
+ "webhooks",
176
+ ]
clikgate/_addon.py ADDED
@@ -0,0 +1,52 @@
1
+ """Shared by the framework add-ons (SPEC section 17)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import contextlib
6
+ import threading
7
+ from typing import Any, Optional, Union
8
+
9
+ from ._click_ids import ClickIds, click_ids
10
+
11
+ Client = Any # Clikgate | AsyncClikgate (kept loose: the add-ons import no framework at module level)
12
+
13
+
14
+ def helpers_for(client: Optional[Client]) -> ClickIds:
15
+ return client.click_ids if client is not None else click_ids
16
+
17
+
18
+ def warm_config(client: Optional[Client]) -> None:
19
+ """Learn the organisation's ``click_id_param`` in the background; never blocks a request (SPEC 17)."""
20
+ if client is None or getattr(client, "_clikgate_warmed", False):
21
+ return
22
+ try:
23
+ client._clikgate_warmed = True
24
+ config = getattr(client, "config", None)
25
+ if config is None:
26
+ return
27
+ import inspect
28
+
29
+ if inspect.iscoroutinefunction(config):
30
+ import asyncio
31
+
32
+ with contextlib.suppress(RuntimeError):
33
+ asyncio.get_running_loop().create_task(config())
34
+ return
35
+ threading.Thread(target=_quiet, args=(config,), name="clikgate-config", daemon=True).start()
36
+ except Exception:
37
+ pass
38
+
39
+
40
+ def _quiet(fn: Any) -> None:
41
+ with contextlib.suppress(Exception):
42
+ fn()
43
+
44
+
45
+ def capture(helpers: ClickIds, request: Any) -> tuple[Optional[str], bool]:
46
+ """The click ID from the request, and whether it came from the query string (then it is persisted)."""
47
+ click_id = helpers.from_request(request)
48
+ from_query = click_id is not None and helpers.from_query(request) == click_id
49
+ return click_id, from_query
50
+
51
+
52
+ CookieDays = Union[int, float]
@@ -0,0 +1,98 @@
1
+ """Hashed email and phone for ad network matching.
2
+
3
+ The values Clikgate accepts as ``hashed_email``, ``hashed_phone_e164`` and ``hashed_phone_digits``: SHA-256 as 64
4
+ lowercase hex characters.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import hashlib
10
+ import re
11
+ from typing import Any, Mapping, Optional, TypedDict
12
+
13
+ from ._errors import local_error
14
+
15
+ __all__ = ["HASHED_FIELDS", "HashedIdentifiers", "check_hashed_fields", "hash_for_ads"]
16
+
17
+ #: The wire fields (also the Python option names).
18
+ HASHED_FIELDS = ("hashed_email", "hashed_phone_e164", "hashed_phone_digits")
19
+
20
+ _SHA256_HEX = re.compile(r"[0-9a-f]{64}")
21
+ _E164_DIGITS = re.compile(r"[1-9][0-9]{6,14}")
22
+ _NON_DIGIT = re.compile(r"[^0-9]")
23
+
24
+
25
+ class HashedIdentifiers(TypedDict, total=False):
26
+ """What :func:`hash_for_ads` returns: only the fields for the values given, ready for ``**`` into ``goal()``."""
27
+
28
+ #: SHA-256 of the email, trimmed and lowercased.
29
+ hashed_email: str
30
+ #: SHA-256 of the phone in E.164 with the ``+`` (``+2348031234567``).
31
+ hashed_phone_e164: str
32
+ #: SHA-256 of the phone digits with the country code, no ``+`` (``2348031234567``).
33
+ hashed_phone_digits: str
34
+
35
+
36
+ def _sha256(value: str) -> str:
37
+ return hashlib.sha256(value.encode("utf-8")).hexdigest()
38
+
39
+
40
+ def hash_for_ads(email: Optional[str] = None, phone: Optional[str] = None) -> HashedIdentifiers:
41
+ """Normalise and hash an email and / or phone on your own server, for a goal's ad network matching.
42
+
43
+ Pure and offline: no client needed. In private mode Clikgate never hashes for you: hash on your own server with
44
+ this helper and send only the hashes. ``None`` (or a missing argument) gives no field.
45
+
46
+ - ``email``: trimmed and lowercased; it must contain ``@``.
47
+ - ``phone``: must include its country code (start with ``+`` or ``00``); spaces and punctuation are removed, and
48
+ the result must be 7-15 digits starting with 1-9. A national number such as ``0803 123 4567`` is refused.
49
+
50
+ Raises:
51
+ InvalidRequestError: code ``invalid_argument``, ``param`` ``email`` or ``phone``; the input is never in the
52
+ message.
53
+
54
+ Example::
55
+
56
+ clikgate.goal(
57
+ "account_opened",
58
+ reference="APP-55231",
59
+ click_id=click_id,
60
+ **hash_for_ads(email=customer.email, phone=customer.phone), # e.g. "+234 803 123 4567"
61
+ )
62
+ """
63
+ out: HashedIdentifiers = {}
64
+ if email is not None:
65
+ value = email.strip().lower() if isinstance(email, str) else ""
66
+ if "@" not in value:
67
+ raise local_error("invalid_argument", "email must be an email address (it contains @).", "email")
68
+ out["hashed_email"] = _sha256(value)
69
+ if phone is not None:
70
+ trimmed = phone.strip() if isinstance(phone, str) else ""
71
+ digits = _NON_DIGIT.sub("", trimmed)
72
+ if trimmed.startswith("00"):
73
+ digits = digits[2:]
74
+ elif not trimmed.startswith("+"):
75
+ digits = ""
76
+ if not _E164_DIGITS.fullmatch(digits):
77
+ raise local_error(
78
+ "invalid_argument",
79
+ 'phone must include its country code, e.g. "+234 803 123 4567" (7-15 digits after the +).',
80
+ "phone",
81
+ )
82
+ out["hashed_phone_e164"] = _sha256("+" + digits)
83
+ out["hashed_phone_digits"] = _sha256(digits)
84
+ return out
85
+
86
+
87
+ def check_hashed_fields(wire: Mapping[str, Any]) -> None:
88
+ """Refuse a hashed wire field that isn't 64 lowercase hex characters (the value is never echoed)."""
89
+ for field in HASHED_FIELDS:
90
+ value = wire.get(field)
91
+ if value is None:
92
+ continue
93
+ if not isinstance(value, str) or not _SHA256_HEX.fullmatch(value):
94
+ raise local_error(
95
+ "invalid_hashed_identifier",
96
+ f"{field} must be a SHA-256 hash as 64 lowercase hex characters (use hash_for_ads).",
97
+ field,
98
+ )