feat: Adds revolut checkout and subscriptions (#3968)
Co-authored-by: alan <alan@lnbits.com>
This commit is contained in:
committed by
Vlad Stan
co-authored by
alan
parent
c4ee3a7c6b
commit
751bd42169
@@ -200,6 +200,52 @@ def check_square_signature(
|
|||||||
raise ValueError("Square signature verification failed.")
|
raise ValueError("Square signature verification failed.")
|
||||||
|
|
||||||
|
|
||||||
|
def check_revolut_signature(
|
||||||
|
payload: bytes,
|
||||||
|
sig_header: str | None,
|
||||||
|
timestamp_header: str | None,
|
||||||
|
secret: str | None,
|
||||||
|
tolerance_seconds=300,
|
||||||
|
):
|
||||||
|
if not sig_header:
|
||||||
|
logger.warning("Revolut signature header is missing.")
|
||||||
|
raise ValueError("Revolut signature header is missing.")
|
||||||
|
|
||||||
|
if not timestamp_header:
|
||||||
|
logger.warning("Revolut timestamp header is missing.")
|
||||||
|
raise ValueError("Revolut timestamp header is missing.")
|
||||||
|
|
||||||
|
if not secret:
|
||||||
|
logger.warning("Revolut webhook signing secret is not set.")
|
||||||
|
raise ValueError("Revolut webhook cannot be verified.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
timestamp = int(timestamp_header)
|
||||||
|
except ValueError as exc:
|
||||||
|
logger.warning("Invalid Revolut timestamp.")
|
||||||
|
raise ValueError("Invalid Revolut timestamp.") from exc
|
||||||
|
|
||||||
|
timestamp_seconds = timestamp / 1000 if timestamp > 9999999999 else timestamp
|
||||||
|
|
||||||
|
if abs(time.time() - timestamp_seconds) > tolerance_seconds:
|
||||||
|
logger.warning("Timestamp outside tolerance.")
|
||||||
|
raise ValueError("Timestamp outside tolerance." f"Timestamp: {timestamp}")
|
||||||
|
|
||||||
|
signed_payload = b"v1." + timestamp_header.encode() + b"." + payload
|
||||||
|
digest = hmac.new(
|
||||||
|
key=secret.encode(), msg=signed_payload, digestmod=hashlib.sha256
|
||||||
|
).hexdigest()
|
||||||
|
expected_signature = f"v1={digest}"
|
||||||
|
|
||||||
|
provided_signatures = [sig.strip() for sig in sig_header.split(",") if sig.strip()]
|
||||||
|
if not any(
|
||||||
|
hmac.compare_digest(expected_signature, provided)
|
||||||
|
for provided in provided_signatures
|
||||||
|
):
|
||||||
|
logger.warning("Revolut signature verification failed.")
|
||||||
|
raise ValueError("Revolut signature verification failed.")
|
||||||
|
|
||||||
|
|
||||||
async def test_connection(provider: str) -> SimpleStatus:
|
async def test_connection(provider: str) -> SimpleStatus:
|
||||||
"""
|
"""
|
||||||
Test the connection to Stripe by checking if the API key is valid.
|
Test the connection to Stripe by checking if the API key is valid.
|
||||||
|
|||||||
@@ -13,14 +13,20 @@ from lnbits.core.models.misc import SimpleStatus
|
|||||||
from lnbits.core.models.payments import CreateInvoice
|
from lnbits.core.models.payments import CreateInvoice
|
||||||
from lnbits.core.services.fiat_providers import (
|
from lnbits.core.services.fiat_providers import (
|
||||||
check_fiat_status,
|
check_fiat_status,
|
||||||
|
check_revolut_signature,
|
||||||
check_square_signature,
|
check_square_signature,
|
||||||
check_stripe_signature,
|
check_stripe_signature,
|
||||||
verify_paypal_webhook,
|
verify_paypal_webhook,
|
||||||
)
|
)
|
||||||
from lnbits.core.services.payments import create_fiat_invoice
|
from lnbits.core.services.payments import (
|
||||||
|
create_fiat_invoice,
|
||||||
|
create_wallet_invoice,
|
||||||
|
service_fee_fiat,
|
||||||
|
)
|
||||||
from lnbits.db import Filter, Filters
|
from lnbits.db import Filter, Filters
|
||||||
from lnbits.fiat import get_fiat_provider
|
from lnbits.fiat import get_fiat_provider
|
||||||
from lnbits.fiat.base import FiatSubscriptionPaymentOptions
|
from lnbits.fiat.base import FiatSubscriptionPaymentOptions
|
||||||
|
from lnbits.fiat.revolut import RevolutWallet
|
||||||
from lnbits.fiat.square import SquareWallet
|
from lnbits.fiat.square import SquareWallet
|
||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|
||||||
@@ -74,6 +80,24 @@ async def api_generic_webhook_handler(
|
|||||||
message=f"Callback received successfully from '{provider_name}'.",
|
message=f"Callback received successfully from '{provider_name}'.",
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if provider_name.lower() == "revolut":
|
||||||
|
payload = await request.body()
|
||||||
|
sig_header = request.headers.get("Revolut-Signature")
|
||||||
|
timestamp_header = request.headers.get("Revolut-Request-Timestamp")
|
||||||
|
check_revolut_signature(
|
||||||
|
payload,
|
||||||
|
sig_header,
|
||||||
|
timestamp_header,
|
||||||
|
settings.revolut_webhook_signing_secret,
|
||||||
|
)
|
||||||
|
event = await request.json()
|
||||||
|
await handle_revolut_event(event)
|
||||||
|
|
||||||
|
return SimpleStatus(
|
||||||
|
success=True,
|
||||||
|
message=f"Callback received successfully from '{provider_name}'.",
|
||||||
|
)
|
||||||
|
|
||||||
return SimpleStatus(
|
return SimpleStatus(
|
||||||
success=False,
|
success=False,
|
||||||
message=f"Unknown fiat provider '{provider_name}'.",
|
message=f"Unknown fiat provider '{provider_name}'.",
|
||||||
@@ -322,6 +346,139 @@ async def handle_square_event(event: dict):
|
|||||||
logger.warning(f"Unhandled Square event type: '{event_type}'.")
|
logger.warning(f"Unhandled Square event type: '{event_type}'.")
|
||||||
|
|
||||||
|
|
||||||
|
async def handle_revolut_event(event: dict):
|
||||||
|
event_type = event.get("event", "")
|
||||||
|
order_id = event.get("order_id")
|
||||||
|
logger.info(f"Handling Revolut event: '{event_type}'. Order ID: '{order_id}'.")
|
||||||
|
|
||||||
|
if event_type in ["ORDER_AUTHORISED", "ORDER_COMPLETED"]:
|
||||||
|
if not order_id:
|
||||||
|
logger.warning("Revolut event missing order_id.")
|
||||||
|
return
|
||||||
|
|
||||||
|
payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
||||||
|
if not payment:
|
||||||
|
logger.warning(f"No payment found for Revolut order: '{order_id}'.")
|
||||||
|
return
|
||||||
|
|
||||||
|
await check_fiat_status(payment)
|
||||||
|
return
|
||||||
|
|
||||||
|
if event_type == "SUBSCRIPTION_INITIATED":
|
||||||
|
await _handle_revolut_subscription_initiated(event)
|
||||||
|
return
|
||||||
|
|
||||||
|
if event_type in [
|
||||||
|
"SUBSCRIPTION_CANCELLED",
|
||||||
|
"SUBSCRIPTION_FINISHED",
|
||||||
|
"SUBSCRIPTION_OVERDUE",
|
||||||
|
]:
|
||||||
|
logger.info(f"Revolut subscription lifecycle event received: '{event_type}'.")
|
||||||
|
return
|
||||||
|
|
||||||
|
logger.warning(f"Unhandled Revolut event type: '{event_type}'.")
|
||||||
|
|
||||||
|
|
||||||
|
async def _handle_revolut_subscription_initiated(event: dict):
|
||||||
|
subscription_id = event.get("subscription_id")
|
||||||
|
if not subscription_id:
|
||||||
|
logger.warning("Revolut subscription event missing subscription_id.")
|
||||||
|
return
|
||||||
|
|
||||||
|
fiat_provider = await get_fiat_provider("revolut")
|
||||||
|
if not isinstance(fiat_provider, RevolutWallet):
|
||||||
|
logger.warning("Revolut fiat provider is not configured.")
|
||||||
|
return
|
||||||
|
|
||||||
|
subscription = await fiat_provider.get_subscription(subscription_id)
|
||||||
|
reference = fiat_provider.deserialize_subscription_reference(
|
||||||
|
subscription.get("external_reference")
|
||||||
|
)
|
||||||
|
if not reference:
|
||||||
|
logger.warning("Revolut subscription event missing LNbits metadata.")
|
||||||
|
return
|
||||||
|
|
||||||
|
cycle_id = subscription.get("current_cycle_id")
|
||||||
|
if not cycle_id:
|
||||||
|
logger.warning("Revolut subscription missing current_cycle_id.")
|
||||||
|
return
|
||||||
|
|
||||||
|
cycle = await fiat_provider.get_subscription_cycle(subscription_id, cycle_id)
|
||||||
|
order_id = cycle.get("order_id")
|
||||||
|
if not order_id:
|
||||||
|
logger.warning("Revolut subscription cycle missing order_id.")
|
||||||
|
return
|
||||||
|
|
||||||
|
existing_payment = await get_standalone_payment(f"fiat_revolut_order_{order_id}")
|
||||||
|
if existing_payment:
|
||||||
|
if existing_payment.external_id != subscription_id:
|
||||||
|
existing_payment.external_id = subscription_id
|
||||||
|
await update_payment(existing_payment)
|
||||||
|
await check_fiat_status(existing_payment)
|
||||||
|
return
|
||||||
|
|
||||||
|
order = await fiat_provider.get_order(order_id)
|
||||||
|
amount_minor = order.get("amount")
|
||||||
|
currency = (order.get("currency") or "").upper()
|
||||||
|
if amount_minor is None or not currency:
|
||||||
|
raise ValueError("Revolut subscription order missing amount or currency.")
|
||||||
|
|
||||||
|
extra = {
|
||||||
|
**(reference.extra or {}),
|
||||||
|
"subscription_request_id": reference.subscription_request_id,
|
||||||
|
"fiat_method": "subscription",
|
||||||
|
"tag": reference.tag,
|
||||||
|
"subscription": {
|
||||||
|
"checking_id": f"order_{order_id}",
|
||||||
|
"payment_request": order.get("checkout_url") or "",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
lnbits_payment = await _create_revolut_subscription_payment(
|
||||||
|
wallet_id=reference.wallet_id,
|
||||||
|
amount_minor=amount_minor,
|
||||||
|
currency=currency,
|
||||||
|
memo=reference.memo or "",
|
||||||
|
extra=extra,
|
||||||
|
order_id=order_id,
|
||||||
|
payment_request=order.get("checkout_url") or "",
|
||||||
|
subscription_id=subscription_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
await check_fiat_status(lnbits_payment)
|
||||||
|
|
||||||
|
|
||||||
|
async def _create_revolut_subscription_payment(
|
||||||
|
wallet_id: str,
|
||||||
|
amount_minor: int,
|
||||||
|
currency: str,
|
||||||
|
memo: str,
|
||||||
|
extra: dict,
|
||||||
|
order_id: str,
|
||||||
|
payment_request: str,
|
||||||
|
subscription_id: str,
|
||||||
|
) -> Payment:
|
||||||
|
amount = RevolutWallet.minor_units_to_amount(amount_minor, currency)
|
||||||
|
payment = await create_wallet_invoice(
|
||||||
|
wallet_id,
|
||||||
|
CreateInvoice(
|
||||||
|
unit=currency,
|
||||||
|
amount=amount,
|
||||||
|
memo=memo,
|
||||||
|
extra=extra,
|
||||||
|
internal=True,
|
||||||
|
external_id=subscription_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
payment.fee = -abs(service_fee_fiat(payment.msat, "revolut"))
|
||||||
|
payment.fiat_provider = "revolut"
|
||||||
|
payment.extra["fiat_checking_id"] = f"order_{order_id}"
|
||||||
|
payment.extra["fiat_payment_request"] = payment_request
|
||||||
|
checking_id = f"fiat_revolut_order_{order_id}"
|
||||||
|
await update_payment(payment, checking_id)
|
||||||
|
payment.checking_id = checking_id
|
||||||
|
return payment
|
||||||
|
|
||||||
|
|
||||||
async def _handle_square_payment_event(event: dict):
|
async def _handle_square_payment_event(event: dict):
|
||||||
payment = _square_extract_payment(event)
|
payment = _square_extract_payment(event)
|
||||||
payment_options = _deserialize_square_metadata(_square_payment_note(payment))
|
payment_options = _deserialize_square_metadata(_square_payment_note(payment))
|
||||||
|
|||||||
@@ -2,17 +2,35 @@ from http import HTTPStatus
|
|||||||
|
|
||||||
from fastapi import APIRouter, Depends, HTTPException
|
from fastapi import APIRouter, Depends, HTTPException
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
from lnbits.core.crud.settings import set_settings_field
|
||||||
from lnbits.core.models.misc import SimpleStatus
|
from lnbits.core.models.misc import SimpleStatus
|
||||||
from lnbits.core.models.wallets import WalletTypeInfo
|
from lnbits.core.models.wallets import WalletTypeInfo
|
||||||
|
from lnbits.core.services import update_cached_settings
|
||||||
from lnbits.core.services.fiat_providers import test_connection
|
from lnbits.core.services.fiat_providers import test_connection
|
||||||
from lnbits.decorators import check_admin, require_admin_key
|
from lnbits.decorators import check_admin, require_admin_key
|
||||||
from lnbits.fiat import StripeWallet, get_fiat_provider
|
from lnbits.fiat import RevolutWallet, StripeWallet, get_fiat_provider
|
||||||
from lnbits.fiat.base import CreateFiatSubscription, FiatSubscriptionResponse
|
from lnbits.fiat.base import CreateFiatSubscription, FiatSubscriptionResponse
|
||||||
|
|
||||||
fiat_router = APIRouter(tags=["Fiat API"], prefix="/api/v1/fiat")
|
fiat_router = APIRouter(tags=["Fiat API"], prefix="/api/v1/fiat")
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutCreateWebhook(BaseModel):
|
||||||
|
url: str
|
||||||
|
endpoint: str | None = None
|
||||||
|
api_secret_key: str | None = None
|
||||||
|
api_version: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutCreateWebhookResponse(BaseModel):
|
||||||
|
id: str | None = None
|
||||||
|
url: str
|
||||||
|
events: list[str] = []
|
||||||
|
signing_secret: str
|
||||||
|
already_exists: bool = False
|
||||||
|
|
||||||
|
|
||||||
@fiat_router.put(
|
@fiat_router.put(
|
||||||
"/check/{provider}",
|
"/check/{provider}",
|
||||||
status_code=HTTPStatus.OK,
|
status_code=HTTPStatus.OK,
|
||||||
@@ -22,6 +40,54 @@ async def api_test_fiat_provider(provider: str) -> SimpleStatus:
|
|||||||
return await test_connection(provider)
|
return await test_connection(provider)
|
||||||
|
|
||||||
|
|
||||||
|
@fiat_router.post(
|
||||||
|
"/revolut/webhook",
|
||||||
|
status_code=HTTPStatus.OK,
|
||||||
|
dependencies=[Depends(check_admin)],
|
||||||
|
)
|
||||||
|
async def api_create_revolut_webhook(
|
||||||
|
data: RevolutCreateWebhook,
|
||||||
|
) -> RevolutCreateWebhookResponse:
|
||||||
|
try:
|
||||||
|
webhook = await RevolutWallet.create_webhook(
|
||||||
|
url=data.url,
|
||||||
|
endpoint=data.endpoint,
|
||||||
|
api_secret_key=data.api_secret_key,
|
||||||
|
api_version=data.api_version,
|
||||||
|
)
|
||||||
|
except ValueError as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
raise HTTPException(status_code=400, detail=str(exc)) from exc
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=500, detail="Failed to create Revolut webhook."
|
||||||
|
) from exc
|
||||||
|
|
||||||
|
signing_secret = webhook.get("signing_secret")
|
||||||
|
webhook_url = webhook.get("url") or data.url
|
||||||
|
if not signing_secret:
|
||||||
|
raise HTTPException(
|
||||||
|
status_code=502, detail="Revolut returned no webhook signing secret."
|
||||||
|
)
|
||||||
|
|
||||||
|
updated_settings = {
|
||||||
|
"revolut_payment_webhook_url": webhook_url,
|
||||||
|
"revolut_webhook_signing_secret": signing_secret,
|
||||||
|
}
|
||||||
|
for key, value in updated_settings.items():
|
||||||
|
await set_settings_field(key, value)
|
||||||
|
update_cached_settings(updated_settings)
|
||||||
|
|
||||||
|
return RevolutCreateWebhookResponse(
|
||||||
|
id=webhook.get("id"),
|
||||||
|
url=webhook_url,
|
||||||
|
events=webhook.get("events") or [],
|
||||||
|
signing_secret=signing_secret,
|
||||||
|
already_exists=webhook.get("already_exists", False),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@fiat_router.post(
|
@fiat_router.post(
|
||||||
"/{provider}/subscription",
|
"/{provider}/subscription",
|
||||||
status_code=HTTPStatus.OK,
|
status_code=HTTPStatus.OK,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ from lnbits.fiat.base import FiatProvider
|
|||||||
from lnbits.settings import settings
|
from lnbits.settings import settings
|
||||||
|
|
||||||
from .paypal import PayPalWallet
|
from .paypal import PayPalWallet
|
||||||
|
from .revolut import RevolutWallet
|
||||||
from .square import SquareWallet
|
from .square import SquareWallet
|
||||||
from .stripe import StripeWallet
|
from .stripe import StripeWallet
|
||||||
|
|
||||||
@@ -19,6 +20,7 @@ class FiatProviderType(Enum):
|
|||||||
stripe = "StripeWallet"
|
stripe = "StripeWallet"
|
||||||
paypal = "PayPalWallet"
|
paypal = "PayPalWallet"
|
||||||
square = "SquareWallet"
|
square = "SquareWallet"
|
||||||
|
revolut = "RevolutWallet"
|
||||||
|
|
||||||
|
|
||||||
async def get_fiat_provider(name: str) -> FiatProvider | None:
|
async def get_fiat_provider(name: str) -> FiatProvider | None:
|
||||||
@@ -54,6 +56,7 @@ fiat_providers: dict[str, FiatProvider] = {}
|
|||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
"PayPalWallet",
|
"PayPalWallet",
|
||||||
|
"RevolutWallet",
|
||||||
"SquareWallet",
|
"SquareWallet",
|
||||||
"StripeWallet",
|
"StripeWallet",
|
||||||
]
|
]
|
||||||
|
|||||||
@@ -0,0 +1,535 @@
|
|||||||
|
import asyncio
|
||||||
|
import ipaddress
|
||||||
|
import json
|
||||||
|
from decimal import Decimal, ROUND_HALF_UP
|
||||||
|
from collections.abc import AsyncGenerator
|
||||||
|
from typing import Any
|
||||||
|
from urllib.parse import urlparse
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from loguru import logger
|
||||||
|
from pydantic import BaseModel, Field, ValidationError
|
||||||
|
|
||||||
|
from lnbits.helpers import normalize_endpoint, urlsafe_short_hash
|
||||||
|
from lnbits.settings import settings
|
||||||
|
|
||||||
|
from .base import (
|
||||||
|
FiatInvoiceResponse,
|
||||||
|
FiatPaymentFailedStatus,
|
||||||
|
FiatPaymentPendingStatus,
|
||||||
|
FiatPaymentResponse,
|
||||||
|
FiatPaymentStatus,
|
||||||
|
FiatPaymentSuccessStatus,
|
||||||
|
FiatProvider,
|
||||||
|
FiatStatusResponse,
|
||||||
|
FiatSubscriptionPaymentOptions,
|
||||||
|
FiatSubscriptionResponse,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutCheckoutOptions(BaseModel):
|
||||||
|
class Config:
|
||||||
|
extra = "ignore"
|
||||||
|
|
||||||
|
success_url: str | None = None
|
||||||
|
metadata: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
description: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutCreateInvoiceOptions(BaseModel):
|
||||||
|
class Config:
|
||||||
|
extra = "ignore"
|
||||||
|
|
||||||
|
checkout: RevolutCheckoutOptions | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutSubscriptionReference(BaseModel):
|
||||||
|
wallet_id: str
|
||||||
|
tag: str | None = None
|
||||||
|
subscription_request_id: str | None = None
|
||||||
|
extra: dict[str, Any] | None = None
|
||||||
|
memo: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
REVOLUT_WEBHOOK_EVENTS = [
|
||||||
|
"ORDER_AUTHORISED",
|
||||||
|
"ORDER_COMPLETED",
|
||||||
|
"SUBSCRIPTION_INITIATED",
|
||||||
|
]
|
||||||
|
|
||||||
|
ZERO_DECIMAL_CURRENCIES = {
|
||||||
|
"BIF",
|
||||||
|
"CLP",
|
||||||
|
"DJF",
|
||||||
|
"GNF",
|
||||||
|
"ISK",
|
||||||
|
"JPY",
|
||||||
|
"KMF",
|
||||||
|
"KRW",
|
||||||
|
"PYG",
|
||||||
|
"RWF",
|
||||||
|
"UGX",
|
||||||
|
"VND",
|
||||||
|
"VUV",
|
||||||
|
"XAF",
|
||||||
|
"XOF",
|
||||||
|
"XPF",
|
||||||
|
}
|
||||||
|
THREE_DECIMAL_CURRENCIES = {
|
||||||
|
"BHD",
|
||||||
|
"IQD",
|
||||||
|
"JOD",
|
||||||
|
"KWD",
|
||||||
|
"LYD",
|
||||||
|
"OMR",
|
||||||
|
"TND",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutWallet(FiatProvider):
|
||||||
|
"""https://developer.revolut.com/docs/merchant"""
|
||||||
|
|
||||||
|
def __init__(self):
|
||||||
|
logger.debug("Initializing RevolutWallet")
|
||||||
|
self._settings_fields = self._settings_connection_fields()
|
||||||
|
if not settings.revolut_api_endpoint:
|
||||||
|
raise ValueError("Cannot initialize RevolutWallet: missing endpoint.")
|
||||||
|
if not settings.revolut_api_secret_key:
|
||||||
|
raise ValueError("Cannot initialize RevolutWallet: missing API secret key.")
|
||||||
|
|
||||||
|
self.endpoint = normalize_endpoint(settings.revolut_api_endpoint)
|
||||||
|
self.headers = {
|
||||||
|
"Authorization": f"Bearer {settings.revolut_api_secret_key}",
|
||||||
|
"Revolut-Api-Version": settings.revolut_api_version,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": settings.user_agent,
|
||||||
|
}
|
||||||
|
self.client = httpx.AsyncClient(base_url=self.endpoint, headers=self.headers)
|
||||||
|
logger.info("RevolutWallet initialized.")
|
||||||
|
|
||||||
|
async def cleanup(self):
|
||||||
|
try:
|
||||||
|
await self.client.aclose()
|
||||||
|
except RuntimeError as e:
|
||||||
|
logger.warning(f"Error closing Revolut wallet connection: {e}")
|
||||||
|
|
||||||
|
async def status(
|
||||||
|
self, only_check_settings: bool | None = False
|
||||||
|
) -> FiatStatusResponse:
|
||||||
|
if only_check_settings:
|
||||||
|
if self._settings_fields != self._settings_connection_fields():
|
||||||
|
return FiatStatusResponse("Connection settings have changed.", 0)
|
||||||
|
return FiatStatusResponse(balance=0)
|
||||||
|
|
||||||
|
try:
|
||||||
|
r = await self.client.get("/api/orders", params={"limit": 1}, timeout=15)
|
||||||
|
r.raise_for_status()
|
||||||
|
_ = r.json()
|
||||||
|
return FiatStatusResponse(balance=0)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return FiatStatusResponse("Server error: 'invalid json response'", 0)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
return FiatStatusResponse(f"Unable to connect to {self.endpoint}.", 0)
|
||||||
|
|
||||||
|
async def create_invoice(
|
||||||
|
self,
|
||||||
|
amount: float,
|
||||||
|
payment_hash: str,
|
||||||
|
currency: str,
|
||||||
|
memo: str | None = None,
|
||||||
|
extra: dict[str, Any] | None = None,
|
||||||
|
**kwargs,
|
||||||
|
) -> FiatInvoiceResponse:
|
||||||
|
opts = self._parse_create_opts(extra or {})
|
||||||
|
if opts is None:
|
||||||
|
return FiatInvoiceResponse(
|
||||||
|
ok=False, error_message="Invalid Revolut options"
|
||||||
|
)
|
||||||
|
|
||||||
|
amount_minor = self.amount_to_minor_units(amount, currency)
|
||||||
|
checkout = opts.checkout or RevolutCheckoutOptions()
|
||||||
|
success_url = (
|
||||||
|
checkout.success_url
|
||||||
|
or settings.revolut_payment_success_url
|
||||||
|
or "https://lnbits.com"
|
||||||
|
)
|
||||||
|
|
||||||
|
payload = {
|
||||||
|
"amount": amount_minor,
|
||||||
|
"currency": currency.upper(),
|
||||||
|
"description": checkout.description or memo or "LNbits Invoice",
|
||||||
|
"redirect_url": success_url,
|
||||||
|
"metadata": {
|
||||||
|
**checkout.metadata,
|
||||||
|
"payment_hash": payment_hash,
|
||||||
|
"alan_action": "invoice",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
r = await self.client.post("/api/orders", json=payload)
|
||||||
|
r.raise_for_status()
|
||||||
|
data = r.json()
|
||||||
|
order_id = data.get("id")
|
||||||
|
checkout_url = data.get("checkout_url")
|
||||||
|
if not order_id or not checkout_url:
|
||||||
|
return FiatInvoiceResponse(
|
||||||
|
ok=False, error_message="Server error: missing order id or url"
|
||||||
|
)
|
||||||
|
return FiatInvoiceResponse(
|
||||||
|
ok=True,
|
||||||
|
checking_id=f"order_{order_id}",
|
||||||
|
payment_request=checkout_url,
|
||||||
|
)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return FiatInvoiceResponse(
|
||||||
|
ok=False, error_message="Server error: invalid json response"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
return FiatInvoiceResponse(
|
||||||
|
ok=False, error_message=f"Unable to connect to {self.endpoint}."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def create_subscription(
|
||||||
|
self,
|
||||||
|
subscription_id: str,
|
||||||
|
quantity: int,
|
||||||
|
payment_options: FiatSubscriptionPaymentOptions,
|
||||||
|
**kwargs,
|
||||||
|
) -> FiatSubscriptionResponse:
|
||||||
|
if quantity != 1:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False,
|
||||||
|
error_message="Revolut subscriptions do not support quantity.",
|
||||||
|
)
|
||||||
|
|
||||||
|
wallet_id = payment_options.wallet_id
|
||||||
|
if not wallet_id:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message="Wallet ID is required."
|
||||||
|
)
|
||||||
|
|
||||||
|
extra = payment_options.extra or {}
|
||||||
|
customer_id = extra.get("customer_id")
|
||||||
|
if not customer_id:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False,
|
||||||
|
error_message="Revolut subscriptions require extra.customer_id.",
|
||||||
|
)
|
||||||
|
|
||||||
|
if not payment_options.subscription_request_id:
|
||||||
|
payment_options.subscription_request_id = urlsafe_short_hash()
|
||||||
|
|
||||||
|
reference = RevolutSubscriptionReference(
|
||||||
|
wallet_id=wallet_id,
|
||||||
|
tag=payment_options.tag,
|
||||||
|
subscription_request_id=payment_options.subscription_request_id,
|
||||||
|
extra=extra,
|
||||||
|
memo=payment_options.memo,
|
||||||
|
)
|
||||||
|
payload: dict[str, Any] = {
|
||||||
|
"plan_variation_id": subscription_id,
|
||||||
|
"customer_id": customer_id,
|
||||||
|
"external_reference": self._serialize_subscription_reference(reference),
|
||||||
|
"setup_order_redirect_url": (
|
||||||
|
payment_options.success_url
|
||||||
|
or settings.revolut_payment_success_url
|
||||||
|
or "https://lnbits.com"
|
||||||
|
),
|
||||||
|
}
|
||||||
|
if extra.get("trial_duration"):
|
||||||
|
payload["trial_duration"] = extra["trial_duration"]
|
||||||
|
|
||||||
|
headers = {
|
||||||
|
**self.headers,
|
||||||
|
"Idempotency-Key": payment_options.subscription_request_id,
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
r = await self.client.post(
|
||||||
|
"/api/subscriptions", json=payload, headers=headers
|
||||||
|
)
|
||||||
|
r.raise_for_status()
|
||||||
|
data = r.json()
|
||||||
|
revolut_subscription_id = data.get("id")
|
||||||
|
setup_order_id = data.get("setup_order_id")
|
||||||
|
if not revolut_subscription_id or not setup_order_id:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False,
|
||||||
|
error_message=(
|
||||||
|
"Server error: missing subscription id or setup order id"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
setup_order = await self.get_order(setup_order_id)
|
||||||
|
checkout_url = setup_order.get("checkout_url")
|
||||||
|
if not checkout_url:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message="Server error: missing setup checkout url"
|
||||||
|
)
|
||||||
|
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=True,
|
||||||
|
checkout_session_url=checkout_url,
|
||||||
|
subscription_request_id=revolut_subscription_id,
|
||||||
|
)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message="Server error: invalid json response"
|
||||||
|
)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message=f"Unable to connect to {self.endpoint}."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def cancel_subscription(
|
||||||
|
self,
|
||||||
|
subscription_id: str,
|
||||||
|
correlation_id: str,
|
||||||
|
**kwargs,
|
||||||
|
) -> FiatSubscriptionResponse:
|
||||||
|
try:
|
||||||
|
r = await self.client.post(f"/api/subscriptions/{subscription_id}/cancel")
|
||||||
|
r.raise_for_status()
|
||||||
|
return FiatSubscriptionResponse(ok=True)
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
return FiatSubscriptionResponse(
|
||||||
|
ok=False, error_message="Unable to cancel subscription."
|
||||||
|
)
|
||||||
|
|
||||||
|
async def pay_invoice(self, payment_request: str) -> FiatPaymentResponse:
|
||||||
|
raise NotImplementedError("Revolut does not support paying invoices directly.")
|
||||||
|
|
||||||
|
async def get_invoice_status(self, checking_id: str) -> FiatPaymentStatus:
|
||||||
|
try:
|
||||||
|
order_id = self._normalize_revolut_id(checking_id)
|
||||||
|
return self._status_from_order(await self.get_order(order_id))
|
||||||
|
except Exception as exc:
|
||||||
|
logger.debug(f"Error getting Revolut invoice status: {exc}")
|
||||||
|
return FiatPaymentPendingStatus()
|
||||||
|
|
||||||
|
async def get_payment_status(self, checking_id: str) -> FiatPaymentStatus:
|
||||||
|
raise NotImplementedError("Revolut does not support outgoing payments.")
|
||||||
|
|
||||||
|
async def paid_invoices_stream(self) -> AsyncGenerator[str, None]:
|
||||||
|
logger.warning(
|
||||||
|
"Revolut does not support paid invoices stream. Use webhooks instead."
|
||||||
|
)
|
||||||
|
mock_queue: asyncio.Queue[str] = asyncio.Queue(0)
|
||||||
|
while settings.lnbits_running:
|
||||||
|
value = await mock_queue.get()
|
||||||
|
yield value
|
||||||
|
|
||||||
|
def _normalize_revolut_id(self, checking_id: str) -> str:
|
||||||
|
value = (
|
||||||
|
checking_id.replace("fiat_revolut_", "", 1)
|
||||||
|
if checking_id.startswith("fiat_revolut_")
|
||||||
|
else checking_id
|
||||||
|
)
|
||||||
|
return value.replace("order_", "", 1) if value.startswith("order_") else value
|
||||||
|
|
||||||
|
async def get_order(self, order_id: str) -> dict[str, Any]:
|
||||||
|
r = await self.client.get(f"/api/orders/{order_id}")
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
async def get_subscription(self, subscription_id: str) -> dict[str, Any]:
|
||||||
|
r = await self.client.get(f"/api/subscriptions/{subscription_id}")
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
async def get_subscription_cycle(
|
||||||
|
self, subscription_id: str, cycle_id: str
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
r = await self.client.get(
|
||||||
|
f"/api/subscriptions/{subscription_id}/cycles/{cycle_id}"
|
||||||
|
)
|
||||||
|
r.raise_for_status()
|
||||||
|
return r.json()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def create_webhook(
|
||||||
|
cls,
|
||||||
|
url: str,
|
||||||
|
endpoint: str | None = None,
|
||||||
|
api_secret_key: str | None = None,
|
||||||
|
api_version: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if not url:
|
||||||
|
raise ValueError("Missing Revolut webhook URL.")
|
||||||
|
cls._validate_webhook_url(url)
|
||||||
|
if not endpoint and not settings.revolut_api_endpoint:
|
||||||
|
raise ValueError("Missing Revolut API endpoint.")
|
||||||
|
if not api_secret_key and not settings.revolut_api_secret_key:
|
||||||
|
raise ValueError("Missing Revolut API secret key.")
|
||||||
|
|
||||||
|
base_url = normalize_endpoint(endpoint or settings.revolut_api_endpoint)
|
||||||
|
secret_key = api_secret_key or settings.revolut_api_secret_key
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {secret_key}",
|
||||||
|
"Revolut-Api-Version": api_version or settings.revolut_api_version,
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
"User-Agent": settings.user_agent,
|
||||||
|
}
|
||||||
|
payload = {"url": url, "events": REVOLUT_WEBHOOK_EVENTS}
|
||||||
|
async with httpx.AsyncClient(base_url=base_url, headers=headers) as client:
|
||||||
|
webhooks = await cls._list_webhooks(client)
|
||||||
|
existing = await cls._get_existing_webhook(client, webhooks, url)
|
||||||
|
if existing:
|
||||||
|
existing["already_exists"] = True
|
||||||
|
return existing
|
||||||
|
|
||||||
|
response = await client.post("/api/webhooks", json=payload, timeout=15)
|
||||||
|
response.raise_for_status()
|
||||||
|
return response.json()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def _list_webhooks(cls, client: httpx.AsyncClient) -> list[dict[str, Any]]:
|
||||||
|
response = await client.get("/api/webhooks", timeout=15)
|
||||||
|
response.raise_for_status()
|
||||||
|
data = response.json()
|
||||||
|
if isinstance(data, list):
|
||||||
|
return data
|
||||||
|
if isinstance(data, dict):
|
||||||
|
for field in ["webhooks", "data", "items"]:
|
||||||
|
if isinstance(data.get(field), list):
|
||||||
|
return data[field]
|
||||||
|
return []
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def _get_existing_webhook(
|
||||||
|
cls, client: httpx.AsyncClient, webhooks: list[dict[str, Any]], url: str
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
for webhook in webhooks:
|
||||||
|
if cls._normalize_webhook_url(webhook.get("url")) != (
|
||||||
|
cls._normalize_webhook_url(url)
|
||||||
|
):
|
||||||
|
continue
|
||||||
|
|
||||||
|
webhook_id = webhook.get("id")
|
||||||
|
if webhook_id and (
|
||||||
|
not webhook.get("events") or not webhook.get("signing_secret")
|
||||||
|
):
|
||||||
|
response = await client.get(f"/api/webhooks/{webhook_id}", timeout=15)
|
||||||
|
response.raise_for_status()
|
||||||
|
webhook = response.json()
|
||||||
|
|
||||||
|
events = set(webhook.get("events") or [])
|
||||||
|
missing_events = set(REVOLUT_WEBHOOK_EVENTS) - events
|
||||||
|
if missing_events:
|
||||||
|
raise ValueError(
|
||||||
|
"A Revolut webhook already exists for this URL, but it is "
|
||||||
|
f"missing required events: {', '.join(sorted(missing_events))}."
|
||||||
|
)
|
||||||
|
|
||||||
|
if not webhook.get("signing_secret"):
|
||||||
|
raise ValueError(
|
||||||
|
"A Revolut webhook already exists for this URL, but Revolut "
|
||||||
|
"did not return a signing secret."
|
||||||
|
)
|
||||||
|
|
||||||
|
return webhook
|
||||||
|
return None
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _normalize_webhook_url(cls, url: str | None) -> str:
|
||||||
|
return (url or "").strip().rstrip("/")
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def _validate_webhook_url(cls, url: str) -> None:
|
||||||
|
parsed = urlparse(url)
|
||||||
|
hostname = parsed.hostname
|
||||||
|
if parsed.scheme not in ["http", "https"] or not hostname:
|
||||||
|
raise ValueError("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
|
||||||
|
host = hostname.lower()
|
||||||
|
if host == "localhost" or host.endswith(".localhost"):
|
||||||
|
raise ValueError("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
if host.endswith(".local") or host.endswith(".onion"):
|
||||||
|
raise ValueError("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
|
||||||
|
try:
|
||||||
|
ip = ipaddress.ip_address(host)
|
||||||
|
except ValueError:
|
||||||
|
return
|
||||||
|
|
||||||
|
if (
|
||||||
|
ip.is_loopback
|
||||||
|
or ip.is_private
|
||||||
|
or ip.is_link_local
|
||||||
|
or ip.is_reserved
|
||||||
|
or ip.is_unspecified
|
||||||
|
):
|
||||||
|
raise ValueError("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
|
||||||
|
def _status_from_order(self, order: dict[str, Any]) -> FiatPaymentStatus:
|
||||||
|
status = (order.get("state") or "").upper()
|
||||||
|
if status == "COMPLETED":
|
||||||
|
return FiatPaymentSuccessStatus()
|
||||||
|
if status in ["CANCELLED", "FAILED"]:
|
||||||
|
return FiatPaymentFailedStatus()
|
||||||
|
return FiatPaymentPendingStatus()
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def amount_to_minor_units(cls, amount: float | Decimal, currency: str) -> int:
|
||||||
|
scale = Decimal(10) ** cls.currency_exponent(currency)
|
||||||
|
return int((Decimal(str(amount)) * scale).quantize(Decimal("1"), ROUND_HALF_UP))
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def minor_units_to_amount(cls, amount: int, currency: str) -> float:
|
||||||
|
scale = Decimal(10) ** cls.currency_exponent(currency)
|
||||||
|
return float(Decimal(amount) / scale)
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
def currency_exponent(cls, currency: str) -> int:
|
||||||
|
normalized = currency.upper()
|
||||||
|
if normalized in ZERO_DECIMAL_CURRENCIES:
|
||||||
|
return 0
|
||||||
|
if normalized in THREE_DECIMAL_CURRENCIES:
|
||||||
|
return 3
|
||||||
|
return 2
|
||||||
|
|
||||||
|
def _parse_create_opts(
|
||||||
|
self, raw_opts: dict[str, Any]
|
||||||
|
) -> RevolutCreateInvoiceOptions | None:
|
||||||
|
try:
|
||||||
|
return RevolutCreateInvoiceOptions.parse_obj(raw_opts)
|
||||||
|
except ValidationError as e:
|
||||||
|
logger.warning(f"Invalid Revolut options: {e}")
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _serialize_subscription_reference(
|
||||||
|
self, reference: RevolutSubscriptionReference
|
||||||
|
) -> str:
|
||||||
|
payload = reference.dict(exclude_none=True)
|
||||||
|
serialized = json.dumps(payload, separators=(",", ":"))
|
||||||
|
if len(serialized) > 1024:
|
||||||
|
raise ValueError("Revolut subscription external_reference is too long.")
|
||||||
|
return serialized
|
||||||
|
|
||||||
|
def deserialize_subscription_reference(
|
||||||
|
self, external_reference: str | None
|
||||||
|
) -> RevolutSubscriptionReference | None:
|
||||||
|
if not external_reference:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return RevolutSubscriptionReference.parse_obj(
|
||||||
|
json.loads(external_reference)
|
||||||
|
)
|
||||||
|
except (json.JSONDecodeError, ValidationError) as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
return None
|
||||||
|
|
||||||
|
def _settings_connection_fields(self) -> str:
|
||||||
|
return "-".join(
|
||||||
|
[
|
||||||
|
str(settings.revolut_api_endpoint),
|
||||||
|
str(settings.revolut_api_secret_key),
|
||||||
|
str(settings.revolut_api_version),
|
||||||
|
str(settings.revolut_webhook_signing_secret),
|
||||||
|
]
|
||||||
|
)
|
||||||
+52
-47
@@ -548,55 +548,60 @@ class SquareWallet(FiatProvider):
|
|||||||
async def _get_square_subscription_id(
|
async def _get_square_subscription_id(
|
||||||
self, subscription_id: str, wallet_id: str
|
self, subscription_id: str, wallet_id: str
|
||||||
) -> str:
|
) -> str:
|
||||||
from lnbits.core.crud.payments import get_payments
|
try:
|
||||||
from lnbits.core.models import PaymentFilters
|
from lnbits.core.crud.payments import get_payments
|
||||||
from lnbits.db import Filter, Filters
|
from lnbits.core.models import PaymentFilters
|
||||||
|
from lnbits.db import Filter, Filters
|
||||||
|
|
||||||
payments = await get_payments(
|
payments = await get_payments(
|
||||||
wallet_id=wallet_id,
|
wallet_id=wallet_id,
|
||||||
filters=Filters(
|
filters=Filters(
|
||||||
filters=[
|
filters=[
|
||||||
Filter.parse_query("external_id", [subscription_id], PaymentFilters)
|
Filter.parse_query(
|
||||||
],
|
"external_id", [subscription_id], PaymentFilters
|
||||||
model=PaymentFilters,
|
)
|
||||||
sortby="created_at",
|
],
|
||||||
direction="desc",
|
model=PaymentFilters,
|
||||||
limit=1,
|
sortby="created_at",
|
||||||
),
|
direction="desc",
|
||||||
)
|
limit=1,
|
||||||
payment = next(
|
),
|
||||||
(
|
)
|
||||||
payment
|
payment = next(
|
||||||
for payment in payments
|
(
|
||||||
if payment.external_id and payment.fiat_provider == "square"
|
payment
|
||||||
),
|
for payment in payments
|
||||||
None,
|
if payment.external_id and payment.fiat_provider == "square"
|
||||||
)
|
),
|
||||||
if payment and payment.external_id:
|
None,
|
||||||
return payment.external_id
|
)
|
||||||
|
if payment and payment.external_id:
|
||||||
|
return payment.external_id
|
||||||
|
|
||||||
payments = await get_payments(
|
payments = await get_payments(
|
||||||
wallet_id=wallet_id,
|
wallet_id=wallet_id,
|
||||||
incoming=True,
|
incoming=True,
|
||||||
filters=Filters(
|
filters=Filters(
|
||||||
model=PaymentFilters,
|
model=PaymentFilters,
|
||||||
sortby="created_at",
|
sortby="created_at",
|
||||||
direction="desc",
|
direction="desc",
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
payment = next(
|
payment = next(
|
||||||
(
|
(
|
||||||
payment
|
payment
|
||||||
for payment in payments
|
for payment in payments
|
||||||
if payment.external_id
|
if payment.external_id
|
||||||
and payment.fiat_provider == "square"
|
and payment.fiat_provider == "square"
|
||||||
and (payment.extra or {}).get("subscription_request_id")
|
and (payment.extra or {}).get("subscription_request_id")
|
||||||
== subscription_id
|
== subscription_id
|
||||||
),
|
),
|
||||||
None,
|
None,
|
||||||
)
|
)
|
||||||
if payment and payment.external_id:
|
if payment and payment.external_id:
|
||||||
return payment.external_id
|
return payment.external_id
|
||||||
|
except Exception as exc:
|
||||||
|
logger.warning(exc)
|
||||||
|
|
||||||
return subscription_id
|
return subscription_id
|
||||||
|
|
||||||
|
|||||||
+28
-1
@@ -713,6 +713,20 @@ class SquareFiatProvider(LNbitsSettings):
|
|||||||
square_limits: FiatProviderLimits = Field(default_factory=FiatProviderLimits)
|
square_limits: FiatProviderLimits = Field(default_factory=FiatProviderLimits)
|
||||||
|
|
||||||
|
|
||||||
|
class RevolutFiatProvider(LNbitsSettings):
|
||||||
|
revolut_enabled: bool = Field(default=False)
|
||||||
|
revolut_api_endpoint: str = Field(default="https://merchant.revolut.com")
|
||||||
|
revolut_api_secret_key: str | None = Field(default=None)
|
||||||
|
revolut_api_version: str = Field(default="2026-04-20")
|
||||||
|
revolut_payment_success_url: str = Field(default="https://lnbits.com")
|
||||||
|
revolut_payment_webhook_url: str = Field(
|
||||||
|
default="https://your-lnbits-domain-here.com/api/v1/callback/revolut"
|
||||||
|
)
|
||||||
|
revolut_webhook_signing_secret: str | None = Field(default=None)
|
||||||
|
|
||||||
|
revolut_limits: FiatProviderLimits = Field(default_factory=FiatProviderLimits)
|
||||||
|
|
||||||
|
|
||||||
class LightningSettings(LNbitsSettings):
|
class LightningSettings(LNbitsSettings):
|
||||||
lightning_invoice_expiry: int = Field(default=3600, gt=0)
|
lightning_invoice_expiry: int = Field(default=3600, gt=0)
|
||||||
|
|
||||||
@@ -750,7 +764,12 @@ class FundingSourcesSettings(
|
|||||||
funding_source_max_retries: int = Field(default=4, ge=0)
|
funding_source_max_retries: int = Field(default=4, ge=0)
|
||||||
|
|
||||||
|
|
||||||
class FiatProvidersSettings(StripeFiatProvider, PayPalFiatProvider, SquareFiatProvider):
|
class FiatProvidersSettings(
|
||||||
|
StripeFiatProvider,
|
||||||
|
PayPalFiatProvider,
|
||||||
|
SquareFiatProvider,
|
||||||
|
RevolutFiatProvider,
|
||||||
|
):
|
||||||
def is_fiat_provider_enabled(self, provider: str | None) -> bool:
|
def is_fiat_provider_enabled(self, provider: str | None) -> bool:
|
||||||
"""
|
"""
|
||||||
Checks if a specific fiat provider is enabled.
|
Checks if a specific fiat provider is enabled.
|
||||||
@@ -763,6 +782,8 @@ class FiatProvidersSettings(StripeFiatProvider, PayPalFiatProvider, SquareFiatPr
|
|||||||
return self.paypal_enabled
|
return self.paypal_enabled
|
||||||
if provider == "square":
|
if provider == "square":
|
||||||
return self.square_enabled
|
return self.square_enabled
|
||||||
|
if provider == "revolut":
|
||||||
|
return self.revolut_enabled
|
||||||
return False
|
return False
|
||||||
|
|
||||||
def get_fiat_providers_for_user(self, user_id: str) -> list[str]:
|
def get_fiat_providers_for_user(self, user_id: str) -> list[str]:
|
||||||
@@ -788,6 +809,12 @@ class FiatProvidersSettings(StripeFiatProvider, PayPalFiatProvider, SquareFiatPr
|
|||||||
):
|
):
|
||||||
allowed_providers.append("square")
|
allowed_providers.append("square")
|
||||||
|
|
||||||
|
if self.revolut_enabled and (
|
||||||
|
not self.revolut_limits.allowed_users
|
||||||
|
or user_id in self.revolut_limits.allowed_users
|
||||||
|
):
|
||||||
|
allowed_providers.append("revolut")
|
||||||
|
|
||||||
return allowed_providers
|
return allowed_providers
|
||||||
|
|
||||||
def get_fiat_provider_limits(self, provider_name: str) -> FiatProviderLimits | None:
|
def get_fiat_provider_limits(self, provider_name: str) -> FiatProviderLimits | None:
|
||||||
|
|||||||
+1
-1
File diff suppressed because one or more lines are too long
@@ -6,6 +6,8 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
formAddStripeUser: '',
|
formAddStripeUser: '',
|
||||||
formAddPaypalUser: '',
|
formAddPaypalUser: '',
|
||||||
formAddSquareUser: '',
|
formAddSquareUser: '',
|
||||||
|
formAddRevolutUser: '',
|
||||||
|
creatingRevolutWebhook: false,
|
||||||
hideInputToggle: true
|
hideInputToggle: true
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@@ -21,6 +23,12 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
this.formData?.paypal_payment_webhook_url ||
|
this.formData?.paypal_payment_webhook_url ||
|
||||||
this.calculateWebhookUrl('paypal')
|
this.calculateWebhookUrl('paypal')
|
||||||
)
|
)
|
||||||
|
},
|
||||||
|
revolutWebhookUrl() {
|
||||||
|
return (
|
||||||
|
this.formData?.revolut_payment_webhook_url ||
|
||||||
|
this.calculateWebhookUrl('revolut')
|
||||||
|
)
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
watch: {
|
watch: {
|
||||||
@@ -60,6 +68,7 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
this.maybeSetWebhookUrl('stripe_payment_webhook_url', 'stripe')
|
this.maybeSetWebhookUrl('stripe_payment_webhook_url', 'stripe')
|
||||||
this.maybeSetWebhookUrl('paypal_payment_webhook_url', 'paypal')
|
this.maybeSetWebhookUrl('paypal_payment_webhook_url', 'paypal')
|
||||||
this.maybeSetWebhookUrl('square_payment_webhook_url', 'square')
|
this.maybeSetWebhookUrl('square_payment_webhook_url', 'square')
|
||||||
|
this.maybeSetWebhookUrl('revolut_payment_webhook_url', 'revolut')
|
||||||
},
|
},
|
||||||
maybeSetWebhookUrl(fieldName, provider) {
|
maybeSetWebhookUrl(fieldName, provider) {
|
||||||
if (!this.formData) {
|
if (!this.formData) {
|
||||||
@@ -79,6 +88,47 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
}
|
}
|
||||||
this.copyText(url)
|
this.copyText(url)
|
||||||
},
|
},
|
||||||
|
isClearnetWebhookUrl(url) {
|
||||||
|
let parsedUrl
|
||||||
|
try {
|
||||||
|
parsedUrl = new URL(url)
|
||||||
|
} catch (e) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
const host = parsedUrl.hostname.toLowerCase()
|
||||||
|
if (!['http:', 'https:'].includes(parsedUrl.protocol)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
host === 'localhost' ||
|
||||||
|
host.endsWith('.localhost') ||
|
||||||
|
host.endsWith('.local') ||
|
||||||
|
host.endsWith('.onion')
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
/^127\./.test(host) ||
|
||||||
|
/^10\./.test(host) ||
|
||||||
|
/^192\.168\./.test(host) ||
|
||||||
|
/^169\.254\./.test(host) ||
|
||||||
|
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host) ||
|
||||||
|
host === '0.0.0.0' ||
|
||||||
|
host === '::1'
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
notifyRevolutWebhookWarning(message) {
|
||||||
|
Quasar.Notify.create({
|
||||||
|
type: 'warning',
|
||||||
|
message,
|
||||||
|
icon: null,
|
||||||
|
closeBtn: true
|
||||||
|
})
|
||||||
|
},
|
||||||
addStripeAllowedUser() {
|
addStripeAllowedUser() {
|
||||||
const addUser = this.formAddStripeUser || ''
|
const addUser = this.formAddStripeUser || ''
|
||||||
if (
|
if (
|
||||||
@@ -130,6 +180,23 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
this.formData.square_limits.allowed_users =
|
this.formData.square_limits.allowed_users =
|
||||||
this.formData.square_limits.allowed_users.filter(u => u !== user)
|
this.formData.square_limits.allowed_users.filter(u => u !== user)
|
||||||
},
|
},
|
||||||
|
addRevolutAllowedUser() {
|
||||||
|
const addUser = this.formAddRevolutUser || ''
|
||||||
|
if (
|
||||||
|
addUser.length &&
|
||||||
|
!this.formData.revolut_limits.allowed_users.includes(addUser)
|
||||||
|
) {
|
||||||
|
this.formData.revolut_limits.allowed_users = [
|
||||||
|
...this.formData.revolut_limits.allowed_users,
|
||||||
|
addUser
|
||||||
|
]
|
||||||
|
this.formAddRevolutUser = ''
|
||||||
|
}
|
||||||
|
},
|
||||||
|
removeRevolutAllowedUser(user) {
|
||||||
|
this.formData.revolut_limits.allowed_users =
|
||||||
|
this.formData.revolut_limits.allowed_users.filter(u => u !== user)
|
||||||
|
},
|
||||||
checkFiatProvider(providerName) {
|
checkFiatProvider(providerName) {
|
||||||
LNbits.api
|
LNbits.api
|
||||||
.request('PUT', `/api/v1/fiat/check/${providerName}`)
|
.request('PUT', `/api/v1/fiat/check/${providerName}`)
|
||||||
@@ -143,6 +210,48 @@ window.app.component('lnbits-admin-fiat-providers', {
|
|||||||
})
|
})
|
||||||
})
|
})
|
||||||
.catch(LNbits.utils.notifyApiError)
|
.catch(LNbits.utils.notifyApiError)
|
||||||
|
},
|
||||||
|
createRevolutWebhook() {
|
||||||
|
const webhookUrl = this.calculateWebhookUrl('revolut')
|
||||||
|
this.formData.revolut_payment_webhook_url = webhookUrl
|
||||||
|
|
||||||
|
if (!this.formData.revolut_api_secret_key) {
|
||||||
|
this.notifyRevolutWebhookWarning(
|
||||||
|
'Add your Revolut API secret key before creating a webhook.'
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!this.isClearnetWebhookUrl(webhookUrl)) {
|
||||||
|
this.notifyRevolutWebhookWarning(
|
||||||
|
'Revolut webhook URL must be a clearnet URL.'
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.creatingRevolutWebhook = true
|
||||||
|
LNbits.api
|
||||||
|
.request('POST', '/api/v1/fiat/revolut/webhook', null, {
|
||||||
|
url: webhookUrl,
|
||||||
|
endpoint: this.formData.revolut_api_endpoint,
|
||||||
|
api_secret_key: this.formData.revolut_api_secret_key,
|
||||||
|
api_version: this.formData.revolut_api_version
|
||||||
|
})
|
||||||
|
.then(response => {
|
||||||
|
const data = response.data
|
||||||
|
this.formData.revolut_payment_webhook_url = data.url
|
||||||
|
this.formData.revolut_webhook_signing_secret = data.signing_secret
|
||||||
|
Quasar.Notify.create({
|
||||||
|
type: 'positive',
|
||||||
|
message: `Revolut webhook ${
|
||||||
|
data.already_exists ? 'already exists' : 'created'
|
||||||
|
}${data.id ? `: ${data.id}` : ''}.`,
|
||||||
|
icon: null
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.catch(LNbits.utils.notifyApiError)
|
||||||
|
.finally(() => {
|
||||||
|
this.creatingRevolutWebhook = false
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -866,6 +866,266 @@
|
|||||||
</q-expansion-item>
|
</q-expansion-item>
|
||||||
</q-card>
|
</q-card>
|
||||||
</q-expansion-item>
|
</q-expansion-item>
|
||||||
|
<q-expansion-item header-class="text-primary text-bold">
|
||||||
|
<template v-slot:header>
|
||||||
|
<q-item-section avatar>
|
||||||
|
<q-avatar color="deep-orange-7" text-color="white">R</q-avatar>
|
||||||
|
</q-item-section>
|
||||||
|
|
||||||
|
<q-item-section> Revolut </q-item-section>
|
||||||
|
|
||||||
|
<q-item-section side>
|
||||||
|
<div class="row items-center">
|
||||||
|
<q-toggle
|
||||||
|
size="md"
|
||||||
|
:label="$t('enabled')"
|
||||||
|
v-model="formData.revolut_enabled"
|
||||||
|
color="green"
|
||||||
|
unchecked-icon="clear"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</q-item-section>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<q-card class="q-pb-xl">
|
||||||
|
<q-expansion-item :label="$t('api')" default-opened>
|
||||||
|
<q-card-section class="q-pa-md">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
type="text"
|
||||||
|
v-model="formData.revolut_api_endpoint"
|
||||||
|
:label="$t('endpoint')"
|
||||||
|
></q-input>
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-mt-md"
|
||||||
|
:type="hideInputToggle ? 'password' : 'text'"
|
||||||
|
v-model="formData.revolut_api_secret_key"
|
||||||
|
label="API secret key"
|
||||||
|
></q-input>
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-mt-md"
|
||||||
|
type="text"
|
||||||
|
v-model="formData.revolut_api_version"
|
||||||
|
:label="$t('api_version')"
|
||||||
|
></q-input>
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-mt-md"
|
||||||
|
type="text"
|
||||||
|
v-model="formData.revolut_payment_success_url"
|
||||||
|
:label="$t('callback_success_url')"
|
||||||
|
:hint="$t('callback_success_url_hint')"
|
||||||
|
></q-input>
|
||||||
|
</q-card-section>
|
||||||
|
<q-card-section class="q-pa-md">
|
||||||
|
<div class="row">
|
||||||
|
<div class="col">
|
||||||
|
<q-btn
|
||||||
|
outline
|
||||||
|
color="grey"
|
||||||
|
class="float-right"
|
||||||
|
:label="$t('check_connection')"
|
||||||
|
@click="checkFiatProvider('revolut')"
|
||||||
|
></q-btn>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</q-card-section>
|
||||||
|
</q-expansion-item>
|
||||||
|
|
||||||
|
<q-expansion-item :label="$t('webhook')" default-opened>
|
||||||
|
<q-card-section>
|
||||||
|
Configure a Revolut Merchant webhook that points to your LNbits
|
||||||
|
server. LNbits will create it through the Revolut API and
|
||||||
|
subscribe to <code>ORDER_AUTHORISED</code>,
|
||||||
|
<code>ORDER_COMPLETED</code>, and
|
||||||
|
<code>SUBSCRIPTION_INITIATED</code>.
|
||||||
|
</q-card-section>
|
||||||
|
<q-card-section>
|
||||||
|
<div class="row items-center q-gutter-sm q-mt-md">
|
||||||
|
<div class="col">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
type="text"
|
||||||
|
disable
|
||||||
|
:model-value="revolutWebhookUrl"
|
||||||
|
:label="$t('webhook_url')"
|
||||||
|
readonly
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
<div class="col-auto">
|
||||||
|
<q-btn
|
||||||
|
outline
|
||||||
|
color="grey"
|
||||||
|
icon="content_copy"
|
||||||
|
@click="copyWebhookUrl(revolutWebhookUrl)"
|
||||||
|
:aria-label="$t('copy_webhook_url')"
|
||||||
|
>
|
||||||
|
<q-tooltip>
|
||||||
|
<span v-text="$t('copy_webhook_url')"></span>
|
||||||
|
</q-tooltip>
|
||||||
|
</q-btn>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="row items-center q-gutter-sm q-mt-md">
|
||||||
|
<q-btn
|
||||||
|
type="button"
|
||||||
|
color="primary"
|
||||||
|
icon="add_link"
|
||||||
|
label="Create webhook"
|
||||||
|
:loading="creatingRevolutWebhook"
|
||||||
|
@click="createRevolutWebhook"
|
||||||
|
></q-btn>
|
||||||
|
<q-chip
|
||||||
|
v-if="formData.revolut_webhook_signing_secret"
|
||||||
|
dense
|
||||||
|
color="positive"
|
||||||
|
text-color="white"
|
||||||
|
icon="verified"
|
||||||
|
>
|
||||||
|
Signing secret saved
|
||||||
|
</q-chip>
|
||||||
|
</div>
|
||||||
|
</q-card-section>
|
||||||
|
<q-card-section>
|
||||||
|
<span v-text="$t('webhook_events_list')"></span>
|
||||||
|
<ul>
|
||||||
|
<li>
|
||||||
|
<code>ORDER_AUTHORISED</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<code>ORDER_COMPLETED</code>
|
||||||
|
</li>
|
||||||
|
<li>
|
||||||
|
<code>SUBSCRIPTION_INITIATED</code>
|
||||||
|
</li>
|
||||||
|
</ul>
|
||||||
|
</q-card-section>
|
||||||
|
</q-expansion-item>
|
||||||
|
|
||||||
|
<q-expansion-item :label="$t('service_fee')">
|
||||||
|
<q-card-section>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
v-model="formData.revolut_limits.service_fee_percent"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('service_fee_label')"
|
||||||
|
:hint="$t('service_fee_hint')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
v-model="formData.revolut_limits.service_max_fee_sats"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('service_fee_max')"
|
||||||
|
:hint="$t('service_fee_max_hint')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
type="text"
|
||||||
|
v-model="formData.revolut_limits.service_fee_wallet_id"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('fee_wallet_label')"
|
||||||
|
:hint="$t('fee_wallet_hint')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</q-card-section>
|
||||||
|
</q-expansion-item>
|
||||||
|
|
||||||
|
<q-expansion-item :label="$t('amount_limits')">
|
||||||
|
<q-card-section>
|
||||||
|
<div class="row">
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
v-model="formData.revolut_limits.service_min_amount_sats"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('min_incoming_payment_amount')"
|
||||||
|
:hint="$t('min_incoming_payment_amount_desc')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
type="number"
|
||||||
|
min="0"
|
||||||
|
v-model="formData.revolut_limits.service_max_amount_sats"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('max_incoming_payment_amount')"
|
||||||
|
:hint="$t('max_incoming_payment_amount_desc')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
<div class="col-md-4 col-sm-12">
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
class="q-ma-sm"
|
||||||
|
v-model="formData.revolut_limits.service_faucet_wallet_id"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:label="$t('faucest_wallet_id')"
|
||||||
|
:hint="$t('faucest_wallet_id_hint')"
|
||||||
|
></q-input>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</q-card-section>
|
||||||
|
</q-expansion-item>
|
||||||
|
|
||||||
|
<q-expansion-item :label="$t('allowed_users')">
|
||||||
|
<q-card-section>
|
||||||
|
<q-input
|
||||||
|
filled
|
||||||
|
v-model="formAddRevolutUser"
|
||||||
|
@keydown.enter="addRevolutAllowedUser"
|
||||||
|
type="text"
|
||||||
|
:label="$t('allowed_users_label')"
|
||||||
|
:hint="
|
||||||
|
$t('allowed_users_hint_feature', {
|
||||||
|
feature: 'Revolut'
|
||||||
|
})
|
||||||
|
"
|
||||||
|
>
|
||||||
|
<q-btn
|
||||||
|
@click="addRevolutAllowedUser"
|
||||||
|
dense
|
||||||
|
flat
|
||||||
|
icon="add"
|
||||||
|
></q-btn>
|
||||||
|
</q-input>
|
||||||
|
<div>
|
||||||
|
<q-chip
|
||||||
|
v-for="user in formData.revolut_limits.allowed_users"
|
||||||
|
@update:model-value="formData.touch = null"
|
||||||
|
:key="user"
|
||||||
|
removable
|
||||||
|
@remove="removeRevolutAllowedUser(user)"
|
||||||
|
color="primary"
|
||||||
|
text-color="white"
|
||||||
|
:label="user"
|
||||||
|
class="ellipsis"
|
||||||
|
>
|
||||||
|
</q-chip>
|
||||||
|
</div>
|
||||||
|
</q-card-section>
|
||||||
|
</q-expansion-item>
|
||||||
|
</q-card>
|
||||||
|
</q-expansion-item>
|
||||||
</q-list>
|
</q-list>
|
||||||
<div
|
<div
|
||||||
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
class="q-my-md q-pa-sm text-body2 text-grey-4 bg-grey-9 rounded-borders"
|
||||||
@@ -925,6 +1185,21 @@
|
|||||||
>Regions: Square-supported countries</q-chip
|
>Regions: Square-supported countries</q-chip
|
||||||
>
|
>
|
||||||
</div>
|
</div>
|
||||||
|
<div class="row items-center q-gutter-sm">
|
||||||
|
<div class="text-bold" style="min-width: 140px">Revolut</div>
|
||||||
|
<q-chip dense color="positive" text-color="white" icon="check"
|
||||||
|
>Checkout</q-chip
|
||||||
|
>
|
||||||
|
<q-chip dense color="positive" text-color="white" icon="check"
|
||||||
|
>Subscriptions</q-chip
|
||||||
|
>
|
||||||
|
<q-chip dense color="negative" text-color="white" icon="close"
|
||||||
|
>Tap-to-pay</q-chip
|
||||||
|
>
|
||||||
|
<q-chip dense color="grey-9" text-color="white" icon="public"
|
||||||
|
>Regions: Revolut-supported countries</q-chip
|
||||||
|
>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</q-card>
|
</q-card>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -414,6 +414,24 @@
|
|||||||
<span v-text="$t('pay_with', {provider: 'Square'})"></span>
|
<span v-text="$t('pay_with', {provider: 'Square'})"></span>
|
||||||
</q-item-section>
|
</q-item-section>
|
||||||
</q-item>
|
</q-item>
|
||||||
|
<q-separator
|
||||||
|
v-if="g.user.fiat_providers?.includes('revolut')"
|
||||||
|
></q-separator>
|
||||||
|
<q-item
|
||||||
|
v-if="g.user.fiat_providers?.includes('revolut')"
|
||||||
|
:active="receive.fiatProvider === 'revolut'"
|
||||||
|
@click="receive.fiatProvider = 'revolut'"
|
||||||
|
active-class="bg-teal-1 text-grey-8 text-weight-bold"
|
||||||
|
clickable
|
||||||
|
v-ripple
|
||||||
|
>
|
||||||
|
<q-item-section avatar>
|
||||||
|
<q-avatar color="deep-orange-7" text-color="white">R</q-avatar>
|
||||||
|
</q-item-section>
|
||||||
|
<q-item-section>
|
||||||
|
<span v-text="$t('pay_with', {provider: 'Revolut'})"></span>
|
||||||
|
</q-item-section>
|
||||||
|
</q-item>
|
||||||
</q-list>
|
</q-list>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
@@ -9,9 +9,11 @@ from lnbits.core.services.payments import create_wallet_invoice
|
|||||||
from lnbits.core.services.users import create_user_account
|
from lnbits.core.services.users import create_user_account
|
||||||
from lnbits.core.views.callback_api import (
|
from lnbits.core.views.callback_api import (
|
||||||
handle_paypal_event,
|
handle_paypal_event,
|
||||||
|
handle_revolut_event,
|
||||||
handle_square_event,
|
handle_square_event,
|
||||||
handle_stripe_event,
|
handle_stripe_event,
|
||||||
)
|
)
|
||||||
|
from lnbits.fiat.revolut import RevolutWallet
|
||||||
from lnbits.fiat.square import SquareWallet
|
from lnbits.fiat.square import SquareWallet
|
||||||
from lnbits.settings import Settings
|
from lnbits.settings import Settings
|
||||||
|
|
||||||
@@ -29,8 +31,12 @@ async def test_callback_api_generic_webhook_handler_routes_providers(
|
|||||||
square_mock = mocker.patch(
|
square_mock = mocker.patch(
|
||||||
"lnbits.core.views.callback_api.handle_square_event", mocker.AsyncMock()
|
"lnbits.core.views.callback_api.handle_square_event", mocker.AsyncMock()
|
||||||
)
|
)
|
||||||
|
revolut_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.handle_revolut_event", mocker.AsyncMock()
|
||||||
|
)
|
||||||
mocker.patch("lnbits.core.views.callback_api.check_stripe_signature")
|
mocker.patch("lnbits.core.views.callback_api.check_stripe_signature")
|
||||||
mocker.patch("lnbits.core.views.callback_api.check_square_signature")
|
mocker.patch("lnbits.core.views.callback_api.check_square_signature")
|
||||||
|
mocker.patch("lnbits.core.views.callback_api.check_revolut_signature")
|
||||||
mocker.patch(
|
mocker.patch(
|
||||||
"lnbits.core.views.callback_api.verify_paypal_webhook", mocker.AsyncMock()
|
"lnbits.core.views.callback_api.verify_paypal_webhook", mocker.AsyncMock()
|
||||||
)
|
)
|
||||||
@@ -61,6 +67,18 @@ async def test_callback_api_generic_webhook_handler_routes_providers(
|
|||||||
assert square.json()["success"] is True
|
assert square.json()["success"] is True
|
||||||
square_mock.assert_awaited_once()
|
square_mock.assert_awaited_once()
|
||||||
|
|
||||||
|
revolut = await http_client.post(
|
||||||
|
"/api/v1/callback/revolut",
|
||||||
|
headers={
|
||||||
|
"Revolut-Signature": "sig",
|
||||||
|
"Revolut-Request-Timestamp": "1700000000",
|
||||||
|
},
|
||||||
|
json={"event": "ORDER_COMPLETED", "order_id": "order_1"},
|
||||||
|
)
|
||||||
|
assert revolut.status_code == 200
|
||||||
|
assert revolut.json()["success"] is True
|
||||||
|
revolut_mock.assert_awaited_once()
|
||||||
|
|
||||||
unknown = await http_client.post("/api/v1/callback/unknown", json={"id": "evt_3"})
|
unknown = await http_client.post("/api/v1/callback/unknown", json={"id": "evt_3"})
|
||||||
assert unknown.status_code == 200
|
assert unknown.status_code == 200
|
||||||
assert unknown.json()["success"] is False
|
assert unknown.json()["success"] is False
|
||||||
@@ -141,6 +159,119 @@ async def test_callback_api_handles_square_paid_events(mocker):
|
|||||||
fiat_status_mock.assert_awaited_once_with(payment)
|
fiat_status_mock.assert_awaited_once_with(payment)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_callback_api_handles_revolut_paid_events(mocker):
|
||||||
|
payment = mocker.Mock()
|
||||||
|
get_payment = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.get_standalone_payment",
|
||||||
|
mocker.AsyncMock(return_value=payment),
|
||||||
|
)
|
||||||
|
fiat_status_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
|
||||||
|
)
|
||||||
|
|
||||||
|
await handle_revolut_event(
|
||||||
|
{
|
||||||
|
"event": "ORDER_COMPLETED",
|
||||||
|
"order_id": "order_1",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
get_payment.assert_awaited_once_with("fiat_revolut_order_order_1")
|
||||||
|
fiat_status_mock.assert_awaited_once_with(payment)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_callback_api_handles_revolut_subscription_event(
|
||||||
|
mocker, settings: Settings
|
||||||
|
):
|
||||||
|
wallet_id = "wallet_1"
|
||||||
|
payment = mocker.Mock()
|
||||||
|
payment.extra = {}
|
||||||
|
payment.msat = 925_000
|
||||||
|
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
revolut_provider = RevolutWallet()
|
||||||
|
mocker.patch.object(
|
||||||
|
revolut_provider,
|
||||||
|
"get_subscription",
|
||||||
|
return_value={
|
||||||
|
"id": "SUBSCRIPTION_1",
|
||||||
|
"current_cycle_id": "CYCLE_1",
|
||||||
|
"external_reference": json.dumps(
|
||||||
|
{
|
||||||
|
"wallet_id": wallet_id,
|
||||||
|
"tag": "members",
|
||||||
|
"subscription_request_id": "request_1",
|
||||||
|
"extra": {"link": "link-1", "customer_id": "customer_1"},
|
||||||
|
"memo": "Revolut Members",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
mocker.patch.object(
|
||||||
|
revolut_provider,
|
||||||
|
"get_subscription_cycle",
|
||||||
|
return_value={"id": "CYCLE_1", "order_id": "ORDER_SUB_1"},
|
||||||
|
)
|
||||||
|
mocker.patch.object(
|
||||||
|
revolut_provider,
|
||||||
|
"get_order",
|
||||||
|
return_value={
|
||||||
|
"id": "ORDER_SUB_1",
|
||||||
|
"amount": 925,
|
||||||
|
"currency": "USD",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_1",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.get_fiat_provider",
|
||||||
|
mocker.AsyncMock(return_value=revolut_provider),
|
||||||
|
)
|
||||||
|
mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.get_standalone_payment",
|
||||||
|
mocker.AsyncMock(side_effect=[None]),
|
||||||
|
)
|
||||||
|
create_wallet_invoice_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.create_wallet_invoice",
|
||||||
|
mocker.AsyncMock(return_value=payment),
|
||||||
|
)
|
||||||
|
mocker.patch("lnbits.core.views.callback_api.service_fee_fiat", return_value=2)
|
||||||
|
update_payment_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.update_payment", mocker.AsyncMock()
|
||||||
|
)
|
||||||
|
fiat_status_mock = mocker.patch(
|
||||||
|
"lnbits.core.views.callback_api.check_fiat_status", mocker.AsyncMock()
|
||||||
|
)
|
||||||
|
|
||||||
|
await handle_revolut_event(
|
||||||
|
{
|
||||||
|
"event": "SUBSCRIPTION_INITIATED",
|
||||||
|
"subscription_id": "SUBSCRIPTION_1",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
assert create_wallet_invoice_mock.await_count == 1
|
||||||
|
called_wallet_id, invoice = create_wallet_invoice_mock.await_args.args
|
||||||
|
assert called_wallet_id == "wallet_1"
|
||||||
|
assert invoice.amount == 9.25
|
||||||
|
assert invoice.memo == "Revolut Members"
|
||||||
|
assert invoice.external_id == "SUBSCRIPTION_1"
|
||||||
|
assert invoice.internal is True
|
||||||
|
assert invoice.extra["fiat_method"] == "subscription"
|
||||||
|
assert invoice.extra["subscription"]["checking_id"] == "order_ORDER_SUB_1"
|
||||||
|
assert payment.fiat_provider == "revolut"
|
||||||
|
assert payment.fee == -2
|
||||||
|
assert payment.extra["fiat_checking_id"] == "order_ORDER_SUB_1"
|
||||||
|
assert payment.checking_id == "fiat_revolut_order_ORDER_SUB_1"
|
||||||
|
update_payment_mock.assert_awaited_once_with(
|
||||||
|
payment, "fiat_revolut_order_ORDER_SUB_1"
|
||||||
|
)
|
||||||
|
fiat_status_mock.assert_awaited_once_with(payment)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_callback_api_handles_subscription_flows_and_validation(
|
async def test_callback_api_handles_subscription_flows_and_validation(
|
||||||
mocker, settings: Settings
|
mocker, settings: Settings
|
||||||
|
|||||||
@@ -4,6 +4,8 @@ from pytest_mock.plugin import MockerFixture
|
|||||||
|
|
||||||
from lnbits.core.models.misc import SimpleStatus
|
from lnbits.core.models.misc import SimpleStatus
|
||||||
from lnbits.fiat.base import FiatSubscriptionResponse
|
from lnbits.fiat.base import FiatSubscriptionResponse
|
||||||
|
from lnbits.fiat.revolut import REVOLUT_WEBHOOK_EVENTS
|
||||||
|
from lnbits.settings import Settings
|
||||||
|
|
||||||
|
|
||||||
class _UnsetSecret:
|
class _UnsetSecret:
|
||||||
@@ -144,3 +146,82 @@ async def test_fiat_api_connection_token_validates_provider_configuration(
|
|||||||
assert ok.status_code == 200
|
assert ok.status_code == 200
|
||||||
assert ok.json() == {"secret": "tok_live"}
|
assert ok.json() == {"secret": "tok_live"}
|
||||||
assert good_provider.await_count == 1
|
assert good_provider.await_count == 1
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_fiat_api_creates_revolut_webhook(
|
||||||
|
client: AsyncClient,
|
||||||
|
superuser_token: str,
|
||||||
|
settings: Settings,
|
||||||
|
mocker: MockerFixture,
|
||||||
|
):
|
||||||
|
create_webhook = mocker.patch(
|
||||||
|
"lnbits.core.views.fiat_api.RevolutWallet.create_webhook",
|
||||||
|
mocker.AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"id": "webhook_1",
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
|
"signing_secret": "whsec_1",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/fiat/revolut/webhook",
|
||||||
|
headers={"Authorization": f"Bearer {superuser_token}"},
|
||||||
|
json={
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"endpoint": "https://sandbox-merchant.revolut.com",
|
||||||
|
"api_secret_key": "secret_1",
|
||||||
|
"api_version": "2026-04-20",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {
|
||||||
|
"id": "webhook_1",
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
|
"signing_secret": "whsec_1",
|
||||||
|
"already_exists": False,
|
||||||
|
}
|
||||||
|
create_webhook.assert_awaited_once_with(
|
||||||
|
url="https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
endpoint="https://sandbox-merchant.revolut.com",
|
||||||
|
api_secret_key="secret_1",
|
||||||
|
api_version="2026-04-20",
|
||||||
|
)
|
||||||
|
assert settings.revolut_payment_webhook_url == (
|
||||||
|
"https://lnbits.example/api/v1/callback/revolut"
|
||||||
|
)
|
||||||
|
assert settings.revolut_webhook_signing_secret == "whsec_1"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_fiat_api_rejects_local_revolut_webhook(
|
||||||
|
client: AsyncClient,
|
||||||
|
superuser_token: str,
|
||||||
|
mocker: MockerFixture,
|
||||||
|
):
|
||||||
|
create_webhook = mocker.patch(
|
||||||
|
"lnbits.core.views.fiat_api.RevolutWallet.create_webhook",
|
||||||
|
mocker.AsyncMock(
|
||||||
|
side_effect=ValueError("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await client.post(
|
||||||
|
"/api/v1/fiat/revolut/webhook",
|
||||||
|
headers={"Authorization": f"Bearer {superuser_token}"},
|
||||||
|
json={
|
||||||
|
"url": "http://localhost:5000/api/v1/callback/revolut",
|
||||||
|
"endpoint": "https://sandbox-merchant.revolut.com",
|
||||||
|
"api_secret_key": "secret_1",
|
||||||
|
"api_version": "2026-04-20",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.status_code == 400
|
||||||
|
assert response.json()["detail"] == ("Revolut webhook URL must be a clearnet URL.")
|
||||||
|
create_webhook.assert_awaited_once()
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ from lnbits.core.models.wallets import Wallet
|
|||||||
from lnbits.core.services import check_payment_status, payments
|
from lnbits.core.services import check_payment_status, payments
|
||||||
from lnbits.core.services.fiat_providers import (
|
from lnbits.core.services.fiat_providers import (
|
||||||
check_fiat_status,
|
check_fiat_status,
|
||||||
|
check_revolut_signature,
|
||||||
check_square_signature,
|
check_square_signature,
|
||||||
check_stripe_signature,
|
check_stripe_signature,
|
||||||
handle_fiat_payment_confirmation,
|
handle_fiat_payment_confirmation,
|
||||||
@@ -32,6 +33,7 @@ from lnbits.fiat.base import (
|
|||||||
FiatStatusResponse,
|
FiatStatusResponse,
|
||||||
FiatSubscriptionPaymentOptions,
|
FiatSubscriptionPaymentOptions,
|
||||||
)
|
)
|
||||||
|
from lnbits.fiat.revolut import REVOLUT_WEBHOOK_EVENTS, RevolutWallet
|
||||||
from lnbits.fiat.square import SquareWallet
|
from lnbits.fiat.square import SquareWallet
|
||||||
from lnbits.settings import Settings
|
from lnbits.settings import Settings
|
||||||
from tests.helpers import get_random_string
|
from tests.helpers import get_random_string
|
||||||
@@ -83,9 +85,18 @@ def fiat_provider_test_settings(settings: Settings):
|
|||||||
original_square_payment_webhook_url = settings.square_payment_webhook_url
|
original_square_payment_webhook_url = settings.square_payment_webhook_url
|
||||||
original_square_webhook_signature_key = settings.square_webhook_signature_key
|
original_square_webhook_signature_key = settings.square_webhook_signature_key
|
||||||
original_square_limits = settings.square_limits.copy(deep=True)
|
original_square_limits = settings.square_limits.copy(deep=True)
|
||||||
|
original_revolut_enabled = settings.revolut_enabled
|
||||||
|
original_revolut_api_endpoint = settings.revolut_api_endpoint
|
||||||
|
original_revolut_api_secret_key = settings.revolut_api_secret_key
|
||||||
|
original_revolut_api_version = settings.revolut_api_version
|
||||||
|
original_revolut_payment_success_url = settings.revolut_payment_success_url
|
||||||
|
original_revolut_payment_webhook_url = settings.revolut_payment_webhook_url
|
||||||
|
original_revolut_webhook_signing_secret = settings.revolut_webhook_signing_secret
|
||||||
|
original_revolut_limits = settings.revolut_limits.copy(deep=True)
|
||||||
settings.lnbits_allowed_currencies = []
|
settings.lnbits_allowed_currencies = []
|
||||||
settings.paypal_enabled = False
|
settings.paypal_enabled = False
|
||||||
settings.square_enabled = False
|
settings.square_enabled = False
|
||||||
|
settings.revolut_enabled = False
|
||||||
yield
|
yield
|
||||||
settings.lnbits_allowed_currencies = original_allowed_currencies
|
settings.lnbits_allowed_currencies = original_allowed_currencies
|
||||||
settings.paypal_enabled = original_paypal_enabled
|
settings.paypal_enabled = original_paypal_enabled
|
||||||
@@ -98,6 +109,14 @@ def fiat_provider_test_settings(settings: Settings):
|
|||||||
settings.square_payment_webhook_url = original_square_payment_webhook_url
|
settings.square_payment_webhook_url = original_square_payment_webhook_url
|
||||||
settings.square_webhook_signature_key = original_square_webhook_signature_key
|
settings.square_webhook_signature_key = original_square_webhook_signature_key
|
||||||
settings.square_limits = original_square_limits
|
settings.square_limits = original_square_limits
|
||||||
|
settings.revolut_enabled = original_revolut_enabled
|
||||||
|
settings.revolut_api_endpoint = original_revolut_api_endpoint
|
||||||
|
settings.revolut_api_secret_key = original_revolut_api_secret_key
|
||||||
|
settings.revolut_api_version = original_revolut_api_version
|
||||||
|
settings.revolut_payment_success_url = original_revolut_payment_success_url
|
||||||
|
settings.revolut_payment_webhook_url = original_revolut_payment_webhook_url
|
||||||
|
settings.revolut_webhook_signing_secret = original_revolut_webhook_signing_secret
|
||||||
|
settings.revolut_limits = original_revolut_limits
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
@@ -178,6 +197,23 @@ async def test_create_wallet_fiat_invoice_allowed_users(
|
|||||||
assert user
|
assert user
|
||||||
assert user.fiat_providers == ["square"]
|
assert user.fiat_providers == ["square"]
|
||||||
|
|
||||||
|
settings.square_enabled = False
|
||||||
|
settings.revolut_enabled = True
|
||||||
|
settings.revolut_limits.allowed_users = []
|
||||||
|
user = await get_user(to_user.id)
|
||||||
|
assert user
|
||||||
|
assert user.fiat_providers == ["revolut"]
|
||||||
|
|
||||||
|
settings.revolut_limits.allowed_users = ["some_other_user_id"]
|
||||||
|
user = await get_user(to_user.id)
|
||||||
|
assert user
|
||||||
|
assert user.fiat_providers == []
|
||||||
|
|
||||||
|
settings.revolut_limits.allowed_users.append(to_user.id)
|
||||||
|
user = await get_user(to_user.id)
|
||||||
|
assert user
|
||||||
|
assert user.fiat_providers == ["revolut"]
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_create_wallet_fiat_invoice_fiat_limits_fail(
|
async def test_create_wallet_fiat_invoice_fiat_limits_fail(
|
||||||
@@ -695,6 +731,380 @@ async def test_square_wallet_get_invoice_status(settings: Settings):
|
|||||||
assert client.calls[1][0] == "/v2/payments/PAYMENT123"
|
assert client.calls[1][0] == "/v2/payments/PAYMENT123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_create_wallet_revolut_fiat_invoice_success(
|
||||||
|
to_wallet: Wallet, settings: Settings, mocker: MockerFixture
|
||||||
|
):
|
||||||
|
settings.revolut_enabled = True
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_limits.service_min_amount_sats = 0
|
||||||
|
settings.revolut_limits.service_max_amount_sats = 0
|
||||||
|
settings.revolut_limits.service_faucet_wallet_id = None
|
||||||
|
|
||||||
|
invoice_data = CreateInvoice(
|
||||||
|
unit="USD", amount=1.0, memo="Test", fiat_provider="revolut"
|
||||||
|
)
|
||||||
|
fiat_mock_response = FiatInvoiceResponse(
|
||||||
|
ok=True,
|
||||||
|
checking_id="order_ORDER123",
|
||||||
|
payment_request="https://checkout.revolut.com/payment-link/ORDER123",
|
||||||
|
)
|
||||||
|
|
||||||
|
mocker.patch(
|
||||||
|
"lnbits.fiat.RevolutWallet.create_invoice",
|
||||||
|
AsyncMock(return_value=fiat_mock_response),
|
||||||
|
)
|
||||||
|
mocker.patch(
|
||||||
|
"lnbits.utils.exchange_rates.get_fiat_rate_satoshis",
|
||||||
|
AsyncMock(return_value=1000),
|
||||||
|
)
|
||||||
|
payment = await payments.create_fiat_invoice(to_wallet.id, invoice_data)
|
||||||
|
assert payment.status == PaymentState.PENDING
|
||||||
|
assert payment.fiat_provider == "revolut"
|
||||||
|
assert payment.extra.get("fiat_checking_id") == fiat_mock_response.checking_id
|
||||||
|
assert payment.checking_id.startswith("fiat_revolut_order_ORDER123")
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_invoice(settings: Settings):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
settings.revolut_payment_success_url = "https://lnbits.example/success"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/abc123",
|
||||||
|
}
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
response = await wallet.create_invoice(
|
||||||
|
amount=1.23,
|
||||||
|
payment_hash="hash123",
|
||||||
|
currency="USD",
|
||||||
|
memo="LNbits Revolut invoice",
|
||||||
|
extra={"checkout": {"metadata": {"source": "test"}}},
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert response.checking_id == "order_ORDER123"
|
||||||
|
assert (
|
||||||
|
response.payment_request == "https://checkout.revolut.com/payment-link/abc123"
|
||||||
|
)
|
||||||
|
assert client.calls[0][0] == "/api/orders"
|
||||||
|
payload = client.calls[0][1]["json"]
|
||||||
|
assert payload["amount"] == 123
|
||||||
|
assert payload["currency"] == "USD"
|
||||||
|
assert payload["metadata"]["payment_hash"] == "hash123"
|
||||||
|
assert payload["metadata"]["alan_action"] == "invoice"
|
||||||
|
assert payload["metadata"]["source"] == "test"
|
||||||
|
assert payload["redirect_url"] == "https://lnbits.example/success"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_invoice_uses_currency_minor_units(
|
||||||
|
settings: Settings,
|
||||||
|
):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER_JPY",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/jpy",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER_KWD",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/kwd",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
await wallet.create_invoice(
|
||||||
|
amount=123,
|
||||||
|
payment_hash="hash_jpy",
|
||||||
|
currency="JPY",
|
||||||
|
)
|
||||||
|
await wallet.create_invoice(
|
||||||
|
amount=1.234,
|
||||||
|
payment_hash="hash_kwd",
|
||||||
|
currency="KWD",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert client.calls[0][1]["json"]["amount"] == 123
|
||||||
|
assert client.calls[1][1]["json"]["amount"] == 1234
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_get_invoice_status(settings: Settings):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient([MockHTTPResponse(json_data={"state": "COMPLETED"})])
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
status = await wallet.get_invoice_status("fiat_revolut_order_ORDER123")
|
||||||
|
|
||||||
|
assert status.success is True
|
||||||
|
assert client.calls[0][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_subscription(settings: Settings):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
settings.revolut_payment_success_url = "https://lnbits.example/subscription-success"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "SUBSCRIPTION123",
|
||||||
|
"setup_order_id": "ORDER123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
MockHTTPResponse(
|
||||||
|
json_data={
|
||||||
|
"id": "ORDER123",
|
||||||
|
"checkout_url": "https://checkout.revolut.com/payment-link/sub_123",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
payment_options = FiatSubscriptionPaymentOptions(
|
||||||
|
wallet_id="wallet_1",
|
||||||
|
memo="Monthly Gold",
|
||||||
|
tag="gold",
|
||||||
|
extra={"customer_id": "CUSTOMER123", "link": "link-1"},
|
||||||
|
success_url="https://lnbits.example/subscription-success",
|
||||||
|
)
|
||||||
|
|
||||||
|
response = await wallet.create_subscription(
|
||||||
|
"PLAN_VARIATION_123", 1, payment_options
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert response.subscription_request_id == "SUBSCRIPTION123"
|
||||||
|
assert (
|
||||||
|
response.checkout_session_url
|
||||||
|
== "https://checkout.revolut.com/payment-link/sub_123"
|
||||||
|
)
|
||||||
|
assert client.calls[0][0] == "/api/subscriptions"
|
||||||
|
payload = client.calls[0][1]["json"]
|
||||||
|
assert payload["plan_variation_id"] == "PLAN_VARIATION_123"
|
||||||
|
assert payload["customer_id"] == "CUSTOMER123"
|
||||||
|
assert payload["setup_order_redirect_url"] == (
|
||||||
|
"https://lnbits.example/subscription-success"
|
||||||
|
)
|
||||||
|
reference = json.loads(payload["external_reference"])
|
||||||
|
assert reference["wallet_id"] == "wallet_1"
|
||||||
|
assert reference["tag"] == "gold"
|
||||||
|
assert reference["memo"] == "Monthly Gold"
|
||||||
|
assert reference["extra"]["customer_id"] == "CUSTOMER123"
|
||||||
|
assert client.calls[1][0] == "/api/orders/ORDER123"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_cancel_subscription(settings: Settings):
|
||||||
|
settings.revolut_api_endpoint = "https://sandbox-merchant.revolut.com"
|
||||||
|
settings.revolut_api_secret_key = "revolut-secret"
|
||||||
|
settings.revolut_api_version = "2026-04-20"
|
||||||
|
|
||||||
|
wallet = RevolutWallet()
|
||||||
|
client = MockHTTPClient([MockHTTPResponse(json_data={})])
|
||||||
|
wallet.client = client # type: ignore[assignment]
|
||||||
|
|
||||||
|
response = await wallet.cancel_subscription("SUBSCRIPTION123", "wallet_1")
|
||||||
|
|
||||||
|
assert response.ok is True
|
||||||
|
assert client.calls[0][0] == "/api/subscriptions/SUBSCRIPTION123/cancel"
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_create_webhook(mocker: MockerFixture):
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse({"webhooks": []}),
|
||||||
|
MockHTTPResponse(
|
||||||
|
{
|
||||||
|
"id": "webhook_1",
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
|
"signing_secret": "whsec_1",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
async_client = mocker.patch("lnbits.fiat.revolut.httpx.AsyncClient")
|
||||||
|
async_client.return_value = client
|
||||||
|
|
||||||
|
response = await RevolutWallet.create_webhook(
|
||||||
|
url="https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
endpoint="https://sandbox-merchant.revolut.com",
|
||||||
|
api_secret_key="revolut-secret",
|
||||||
|
api_version="2026-04-20",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response["signing_secret"] == "whsec_1"
|
||||||
|
async_client.assert_called_once()
|
||||||
|
assert async_client.call_args.kwargs["base_url"] == (
|
||||||
|
"https://sandbox-merchant.revolut.com"
|
||||||
|
)
|
||||||
|
assert async_client.call_args.kwargs["headers"]["Authorization"] == (
|
||||||
|
"Bearer revolut-secret"
|
||||||
|
)
|
||||||
|
assert client.calls == [
|
||||||
|
(
|
||||||
|
"/api/webhooks",
|
||||||
|
{
|
||||||
|
"timeout": 15,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"/api/webhooks",
|
||||||
|
{
|
||||||
|
"json": {
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
|
},
|
||||||
|
"timeout": 15,
|
||||||
|
},
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_reuses_existing_webhook(mocker: MockerFixture):
|
||||||
|
client = MockHTTPClient(
|
||||||
|
[
|
||||||
|
MockHTTPResponse(
|
||||||
|
{
|
||||||
|
"webhooks": [
|
||||||
|
{
|
||||||
|
"id": "webhook_1",
|
||||||
|
"url": "https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
"events": REVOLUT_WEBHOOK_EVENTS,
|
||||||
|
"signing_secret": "whsec_1",
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
async_client = mocker.patch("lnbits.fiat.revolut.httpx.AsyncClient")
|
||||||
|
async_client.return_value = client
|
||||||
|
|
||||||
|
response = await RevolutWallet.create_webhook(
|
||||||
|
url="https://lnbits.example/api/v1/callback/revolut",
|
||||||
|
endpoint="https://sandbox-merchant.revolut.com",
|
||||||
|
api_secret_key="revolut-secret",
|
||||||
|
api_version="2026-04-20",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert response["already_exists"] is True
|
||||||
|
assert response["signing_secret"] == "whsec_1"
|
||||||
|
assert client.calls == [
|
||||||
|
(
|
||||||
|
"/api/webhooks",
|
||||||
|
{
|
||||||
|
"timeout": 15,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.anyio
|
||||||
|
async def test_revolut_wallet_rejects_local_webhook_url():
|
||||||
|
with pytest.raises(ValueError, match="clearnet URL"):
|
||||||
|
await RevolutWallet.create_webhook(
|
||||||
|
url="http://localhost:5000/api/v1/callback/revolut",
|
||||||
|
endpoint="https://sandbox-merchant.revolut.com",
|
||||||
|
api_secret_key="revolut-secret",
|
||||||
|
api_version="2026-04-20",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_revolut_signature():
|
||||||
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
|
timestamp = str(int(time.time() * 1000))
|
||||||
|
secret = "revolut-secret"
|
||||||
|
signed_payload = b"v1." + timestamp.encode() + b"." + payload
|
||||||
|
sig = "v1=" + hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
check_revolut_signature(payload, sig, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_revolut_signature_rejects_payload_only_signature():
|
||||||
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
|
timestamp = str(int(time.time() * 1000))
|
||||||
|
secret = "revolut-secret"
|
||||||
|
sig = hmac.new(secret.encode(), payload, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="signature verification failed"):
|
||||||
|
check_revolut_signature(payload, sig, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_revolut_signature_v1_header():
|
||||||
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
|
timestamp = str(int(time.time() * 1000))
|
||||||
|
secret = "revolut-secret"
|
||||||
|
signed_payload = b"v1." + timestamp.encode() + b"." + payload
|
||||||
|
sig = "v1=" + hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
|
||||||
|
|
||||||
|
check_revolut_signature(payload, sig, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_revolut_signature_multiple_v1_headers():
|
||||||
|
payload = b'{"event":"ORDER_COMPLETED","order_id":"ORDER123"}'
|
||||||
|
timestamp = str(int(time.time() * 1000))
|
||||||
|
secret = "revolut-secret"
|
||||||
|
signed_payload = b"v1." + timestamp.encode() + b"." + payload
|
||||||
|
valid_sig = (
|
||||||
|
"v1=" + hmac.new(secret.encode(), signed_payload, hashlib.sha256).hexdigest()
|
||||||
|
)
|
||||||
|
sig_header = f"v1=deadbeef,{valid_sig}"
|
||||||
|
|
||||||
|
check_revolut_signature(payload, sig_header, timestamp, secret)
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_revolut_signature_docs_vector():
|
||||||
|
payload = (
|
||||||
|
b'{"data":{"id":"645a7696-22f3-aa47-9c74-cbae0449cc46",'
|
||||||
|
b'"new_state":"completed","old_state":"pending",'
|
||||||
|
b'"request_id":"app_charges-9f5d5eb3-1e06-46c5-b1c0-3914763e0bcb"},'
|
||||||
|
b'"event":"TransactionStateChanged",'
|
||||||
|
b'"timestamp":"2023-05-09T16:36:38.028960Z"}'
|
||||||
|
)
|
||||||
|
timestamp = "1683650202360"
|
||||||
|
secret = "wsk_r59a4HfWVAKycbCaNO1RvgCJec02gRd8"
|
||||||
|
sig = "v1=bca326fb378d0da7f7c490ad584a8106bab9723d8d9cdd0d50b4c5b3be3837c0"
|
||||||
|
|
||||||
|
check_revolut_signature(
|
||||||
|
payload, sig, timestamp, secret, tolerance_seconds=100000000
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.anyio
|
@pytest.mark.anyio
|
||||||
async def test_fiat_service_fee(settings: Settings):
|
async def test_fiat_service_fee(settings: Settings):
|
||||||
# settings.stripe_limits.service_min_amount_sats = 0
|
# settings.stripe_limits.service_min_amount_sats = 0
|
||||||
|
|||||||
Reference in New Issue
Block a user