feat: show payment provider webhook urls

This commit is contained in:
3252a8
2026-05-22 15:57:49 +03:00
parent f5023dc46b
commit 648f4ba4bc
10 changed files with 326 additions and 3 deletions
@@ -13,6 +13,7 @@ async def admin_settings_get_route(request: web.Request) -> web.Response:
overrides_by_key = {entry["key"]: entry for entry in overrides}
fields = manifest_payload()
webhook_base_url = str(settings.WEBHOOK_BASE_URL or "").strip().rstrip("/")
sections: Dict[str, Dict[str, Any]] = {}
for field in fields:
key = field["key"]
@@ -34,6 +35,14 @@ async def admin_settings_get_route(request: web.Request) -> web.Response:
}
if is_secret:
response_field["has_value"] = bool(value)
webhook_path = str(response_field.get("webhook_path") or "").strip()
if webhook_path:
if not webhook_path.startswith("/"):
webhook_path = f"/{webhook_path}"
response_field["webhook_path"] = webhook_path
response_field["webhook_base_url_configured"] = bool(webhook_base_url)
if webhook_base_url:
response_field["webhook_url"] = f"{webhook_base_url}{webhook_path}"
sections[section_id]["fields"].append(response_field)
ordered_sections = sorted(sections.values(), key=lambda s: s["order"])
@@ -507,7 +507,11 @@ def manifest_payload() -> List[dict]:
same value so existing UIs that only read ``placeholder`` also show the
hint inside the empty input.
"""
from bot.payment_providers import find_manifest_owner, manifest_field_default
from bot.payment_providers import (
find_manifest_owner,
manifest_field_default,
provider_webhook_metadata,
)
sections_order = {
"general": 1,
@@ -531,10 +535,12 @@ def manifest_payload() -> List[dict]:
)
default_value: Optional[str] = None
webhook_metadata: Optional[dict] = None
owner = find_manifest_owner(field.key)
if owner is not None:
spec, manifest_field = owner
default_value = manifest_field_default(spec, manifest_field)
webhook_metadata = provider_webhook_metadata(spec)
placeholder = field.placeholder
if not placeholder and default_value:
@@ -561,6 +567,8 @@ def manifest_payload() -> List[dict]:
}
if default_value is not None:
item["default"] = default_value
if webhook_metadata:
item.update(webhook_metadata)
if field.choices:
item["choices"] = [
{
@@ -25,6 +25,7 @@ from .registry import (
provider_emoji_map,
provider_label_map,
provider_telegram_button_text,
provider_webhook_metadata,
resolve_provider_presentation,
)
@@ -53,5 +54,6 @@ __all__ = [
"provider_telegram_button_text",
"provider_emoji_map",
"provider_label_map",
"provider_webhook_metadata",
"resolve_provider_presentation",
]
+40
View File
@@ -333,6 +333,46 @@ def find_manifest_owner(key: str) -> Optional[tuple[PaymentProviderSpec, Provide
return None
def _webhook_spec_for(spec: PaymentProviderSpec) -> Optional[PaymentProviderSpec]:
if spec.webhook_path and spec.webhook_route:
return spec
if not spec.service_key:
return None
for candidate in PAYMENT_PROVIDER_SPECS:
if (
candidate.service_key == spec.service_key
and candidate.webhook_path
and candidate.webhook_route
):
return candidate
return None
def provider_webhook_metadata(spec: PaymentProviderSpec) -> Optional[Dict[str, Any]]:
"""Return admin-manifest webhook metadata for a provider SPEC.
Some visible payment buttons share one backing service and webhook route
(for example Platega SBP and Platega Crypto), so presentation-only specs
inherit the route from their service sibling.
"""
webhook_spec = _webhook_spec_for(spec)
if webhook_spec is None or not webhook_spec.webhook_path:
return None
try:
path = str(webhook_spec.webhook_path(None) or "").strip()
except Exception:
return None
if not path:
return None
return {
"provider_id": spec.id,
"provider_label": spec.label,
"webhook_provider_id": webhook_spec.id,
"webhook_path": path,
"webhook_requires_base_url": bool(webhook_spec.webhook_requires_base_url),
}
def manifest_field_default(
spec: PaymentProviderSpec,
manifest_field: ProviderManifestField,
@@ -1,5 +1,5 @@
<script>
import { ChevronRight, Eye, EyeOff, Search, X } from "$components/ui/icons.js";
import { Check, ChevronRight, Copy, Eye, EyeOff, Search, X } from "$components/ui/icons.js";
import * as UiIcons from "$components/ui/icons.js";
import { Accordion, Switch } from "$components/ui/primitives.js";
import Dialog from "$components/ui/dialog.svelte";
@@ -9,7 +9,7 @@
AdminEmptyState,
AdminSelect,
} from "$components/patterns/admin/index.js";
import { getContext, onMount } from "svelte";
import { getContext, onDestroy, onMount } from "svelte";
export let at;
export let onSettingsSaved;
@@ -26,6 +26,8 @@
let revealedSecrets = new Set();
let iconPickerField = null;
let iconPickerSearch = "";
let copiedWebhookKey = "";
let copiedWebhookTimer = null;
$: settingsAllOpen =
visibleSettingsSections.length > 0 &&
@@ -48,6 +50,12 @@
});
});
onDestroy(() => {
if (copiedWebhookTimer && typeof window !== "undefined") {
window.clearTimeout(copiedWebhookTimer);
}
});
function toggleAllSections() {
if (settingsOpenSections.length === visibleSettingsSections.length) {
settingsOpenSections = [];
@@ -123,6 +131,60 @@
closeIconPicker();
}
function normalizeWebhookPath(path) {
const normalized = String(path || "").trim();
if (!normalized) return "";
return normalized.startsWith("/") ? normalized : `/${normalized}`;
}
function webhookUrlForField(field) {
const explicit = String(field?.webhook_url || "").trim();
if (explicit) return explicit;
const path = normalizeWebhookPath(field?.webhook_path);
if (!path) return "";
if (field?.webhook_requires_base_url && field?.webhook_base_url_configured === false) {
return "";
}
if (typeof window !== "undefined" && window.location?.origin) {
return `${window.location.origin}${path}`;
}
return path;
}
function groupWebhook(fields) {
const field = (fields || []).find((item) => item.webhook_path || item.webhook_url);
if (!field) return null;
const path = normalizeWebhookPath(field.webhook_path);
const url = webhookUrlForField(field);
if (!url && !path) return null;
return {
key: `${field.provider_id || field.key || "provider"}:${path || url}`,
path,
url,
requiresBaseUrl: Boolean(field.webhook_requires_base_url),
baseConfigured: field.webhook_base_url_configured !== false,
};
}
async function copyWebhookUrl(webhook) {
if (!webhook?.url) return;
try {
await navigator.clipboard.writeText(webhook.url);
copiedWebhookKey = webhook.key;
if (copiedWebhookTimer && typeof window !== "undefined") {
window.clearTimeout(copiedWebhookTimer);
}
if (typeof window !== "undefined") {
copiedWebhookTimer = window.setTimeout(() => {
copiedWebhookKey = "";
copiedWebhookTimer = null;
}, 1400);
}
} catch {
copiedWebhookKey = "";
}
}
function groupSectionFields(section) {
const groups = new Map();
for (const field of section.fields || []) {
@@ -140,6 +202,7 @@
id,
label: id === "_root" ? null : id,
i18nLabelKey: group.i18nLabelKey,
webhook: groupWebhook(group.fields),
fields: group.fields,
}));
}
@@ -219,6 +282,47 @@
}
</script>
{#snippet renderWebhookHint(webhook)}
{@const displayValue = webhook.url || webhook.path}
<div class="admin-webhook-hint">
<div class="admin-webhook-hint-meta">
<strong>{at("settings_provider_webhook_url", {}, "Webhook URL")}</strong>
<small>
{webhook.url
? at(
"settings_provider_webhook_url_hint",
{},
"Use this URL in the provider webhook settings."
)
: at(
"settings_provider_webhook_base_missing",
{ path: webhook.path },
`Set WEBHOOK_BASE_URL to show the full URL for ${webhook.path}.`
)}
</small>
</div>
<div class="admin-webhook-value">
<code title={displayValue}>{displayValue}</code>
<AdminButton
class="admin-webhook-copy"
size="sm"
variant="ghost"
disabled={!webhook.url}
title={at("copy", {}, "Copy")}
onclick={() => copyWebhookUrl(webhook)}
>
{#if copiedWebhookKey === webhook.key}
<Check size={13} />
<span>{at("copied", {}, "Copied")}</span>
{:else}
<Copy size={13} />
<span>{at("copy", {}, "Copy")}</span>
{/if}
</AdminButton>
</div>
</div>
{/snippet}
{#snippet renderField(field)}
{@const revealed = isSecretRevealed(field.key)}
<div class="admin-setting" class:is-overridden={isOverridden(field)}>
@@ -420,6 +524,9 @@
{@const labelGroups = groups.filter((g) => g.label)}
<div class="admin-settings-fields">
{#if rootGroup}
{#if rootGroup.webhook}
{@render renderWebhookHint(rootGroup.webhook)}
{/if}
{#each rootGroup.fields as field}
{@render renderField(field)}
{/each}
@@ -463,6 +570,9 @@
</Accordion.Header>
<Accordion.Content class="admin-accordion-content">
<div class="admin-settings-subsection-body">
{#if group.webhook}
{@render renderWebhookHint(group.webhook)}
{/if}
{#each group.fields as field}
{@render renderField(field)}
{/each}
+79
View File
@@ -1889,6 +1889,65 @@
align-items: center;
}
.admin-webhook-hint {
display: grid;
grid-template-columns: minmax(0, 0.9fr) minmax(0, 1.1fr);
gap: 16px;
align-items: center;
min-width: 0;
padding: 14px 18px;
border-bottom: 1px solid var(--admin-border);
background: color-mix(in srgb, var(--info) 7%, transparent);
}
.admin-webhook-hint-meta {
display: grid;
gap: 4px;
min-width: 0;
}
.admin-webhook-hint-meta strong {
color: var(--admin-text);
font-size: 12px;
font-weight: 700;
text-transform: uppercase;
letter-spacing: 0.04em;
}
.admin-webhook-hint-meta small {
color: var(--admin-muted);
font-size: 12px;
line-height: 1.45;
overflow-wrap: anywhere;
}
.admin-webhook-value {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.admin-webhook-value code {
flex: 1 1 auto;
min-width: 0;
padding: 8px 10px;
border: 1px solid var(--admin-border);
border-radius: 8px;
background: color-mix(in srgb, var(--admin-bg) 82%, var(--admin-surface-2));
color: var(--admin-text);
font-family: var(--font-mono);
font-size: 11px;
line-height: 1.35;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.admin-webhook-copy {
flex: 0 0 auto;
}
.admin-setting:last-child {
border-bottom: 0;
}
@@ -2625,6 +2684,26 @@
padding: 14px 14px;
}
.admin-webhook-hint {
grid-template-columns: minmax(0, 1fr);
gap: 10px;
padding: 14px;
}
.admin-webhook-value {
align-items: stretch;
flex-direction: column;
}
.admin-webhook-value code {
white-space: normal;
overflow-wrap: anywhere;
}
.admin-webhook-copy {
align-self: flex-start;
}
.admin-card-head {
padding: 12px 14px;
}
+5
View File
@@ -956,6 +956,11 @@
"admin_settings_subsection_cryptopay": "CryptoPay",
"admin_settings_subsection_wata": "Wata",
"admin_settings_subsection_heleket": "Heleket",
"admin_settings_provider_webhook_url": "Webhook URL",
"admin_settings_provider_webhook_url_hint": "Use this URL in the provider webhook settings.",
"admin_settings_provider_webhook_base_missing": "Set WEBHOOK_BASE_URL in .env to show the full URL for {path}.",
"admin_copy": "Copy",
"admin_copied": "Copied",
"admin_settings_validation_errors": "Errors: {errors}",
"admin_settings_save_error": "Error: {error}",
"admin_sync_started": "Synchronization started",
+5
View File
@@ -956,6 +956,11 @@
"admin_settings_subsection_cryptopay": "CryptoPay",
"admin_settings_subsection_wata": "Wata",
"admin_settings_subsection_heleket": "Heleket",
"admin_settings_provider_webhook_url": "Webhook URL",
"admin_settings_provider_webhook_url_hint": "Укажите этот адрес в настройках вебхуков провайдера.",
"admin_settings_provider_webhook_base_missing": "Укажите WEBHOOK_BASE_URL в .env, чтобы увидеть полный адрес для {path}.",
"admin_copy": "Копировать",
"admin_copied": "Скопировано",
"admin_settings_validation_errors": "Ошибки: {errors}",
"admin_settings_save_error": "Ошибка: {error}",
"admin_sync_started": "Синхронизация запущена",
@@ -68,3 +68,13 @@ def test_subscription_purchase_description_settings_i18n_keys_exist():
assert field["section"] == "pricing"
assert field["i18n_label_key"] in messages
assert field["i18n_description_key"] in messages
def test_payment_provider_settings_include_webhook_metadata():
manifest = _manifest_by_key()
assert manifest["FREEKASSA_ENABLED"]["webhook_path"] == "/webhook/freekassa"
assert manifest["FREEKASSA_ENABLED"]["provider_id"] == "freekassa"
assert manifest["PAYMENT_PLATEGA_CRYPTO_WEBAPP_LABEL_RU"]["webhook_path"] == "/webhook/platega"
assert manifest["YOOKASSA_SHOP_ID"]["webhook_requires_base_url"] is True
assert "webhook_path" not in manifest["PAYMENT_STARS_WEBAPP_LABEL_RU"]
+55
View File
@@ -722,6 +722,61 @@ class AdminSettingsSecurityTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(secret_field["has_value"])
self.assertNotIn("super-secret", response.text)
async def test_admin_settings_exposes_payment_webhook_urls(self):
class AsyncSessionFactory:
def __call__(self):
return self
async def __aenter__(self):
return object()
async def __aexit__(self, exc_type, exc, tb):
return False
settings = Settings(
_env_file=None,
BOT_TOKEN="token",
POSTGRES_USER="app_user",
POSTGRES_PASSWORD="app_password",
SHOP_NAME="Visible shop",
WEBHOOK_BASE_URL="https://web.tnnl.cc/",
)
request = SimpleNamespace(
app={"settings": settings, "async_session_factory": AsyncSessionFactory()},
headers={},
cookies={},
admin_telegram_id=1,
)
request.get = lambda key, default=None: getattr(request, key, default)
with (
patch.object(admin_settings_routes, "_require_admin_user_id", return_value=1),
patch.object(
admin_api.app_settings_dal,
"get_overrides_with_meta",
AsyncMock(return_value=[]),
),
):
response = await admin_api.admin_settings_get_route(request)
payload = json.loads(response.text)
fields = {
field["key"]: field
for section in payload["sections"]
for field in section["fields"]
}
self.assertEqual(
fields["FREEKASSA_ENABLED"]["webhook_url"],
"https://web.tnnl.cc/webhook/freekassa",
)
self.assertTrue(fields["FREEKASSA_ENABLED"]["webhook_base_url_configured"])
self.assertEqual(
fields["PAYMENT_PLATEGA_CRYPTO_WEBAPP_LABEL_RU"]["webhook_url"],
"https://web.tnnl.cc/webhook/platega",
)
self.assertNotIn("webhook_url", fields["PAYMENT_STARS_WEBAPP_LABEL_RU"])
class DatabaseLoggingSecurityTests(unittest.TestCase):
def test_database_url_redaction_hides_password(self):