django-cfg 1.2.21__py3-none-any.whl → 1.2.22__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- django_cfg/__init__.py +1 -1
- django_cfg/apps/newsletter/signals.py +9 -8
- django_cfg/apps/payments/__init__.py +8 -0
- django_cfg/apps/payments/apps.py +22 -0
- django_cfg/apps/payments/managers/__init__.py +22 -0
- django_cfg/apps/payments/managers/api_key_manager.py +35 -0
- django_cfg/apps/payments/managers/balance_manager.py +361 -0
- django_cfg/apps/payments/managers/currency_manager.py +32 -0
- django_cfg/apps/payments/managers/payment_manager.py +44 -0
- django_cfg/apps/payments/managers/subscription_manager.py +37 -0
- django_cfg/apps/payments/managers/tariff_manager.py +29 -0
- django_cfg/apps/payments/middleware/__init__.py +13 -0
- django_cfg/apps/payments/migrations/0001_initial.py +982 -0
- django_cfg/apps/payments/migrations/__init__.py +1 -0
- django_cfg/apps/payments/models/__init__.py +49 -0
- django_cfg/apps/payments/models/api_keys.py +96 -0
- django_cfg/apps/payments/models/balance.py +209 -0
- django_cfg/apps/payments/models/base.py +14 -0
- django_cfg/apps/payments/models/currencies.py +138 -0
- django_cfg/apps/payments/models/events.py +73 -0
- django_cfg/apps/payments/models/payments.py +301 -0
- django_cfg/apps/payments/models/subscriptions.py +270 -0
- django_cfg/apps/payments/models/tariffs.py +102 -0
- django_cfg/apps/payments/serializers/__init__.py +56 -0
- django_cfg/apps/payments/serializers/api_keys.py +51 -0
- django_cfg/apps/payments/serializers/balance.py +59 -0
- django_cfg/apps/payments/serializers/currencies.py +55 -0
- django_cfg/apps/payments/serializers/payments.py +62 -0
- django_cfg/apps/payments/serializers/subscriptions.py +71 -0
- django_cfg/apps/payments/serializers/tariffs.py +56 -0
- django_cfg/apps/payments/services/__init__.py +14 -0
- django_cfg/apps/payments/services/base.py +68 -0
- django_cfg/apps/payments/services/nowpayments.py +78 -0
- django_cfg/apps/payments/services/providers.py +77 -0
- django_cfg/apps/payments/services/redis_service.py +215 -0
- django_cfg/apps/payments/urls.py +78 -0
- django_cfg/apps/payments/views/__init__.py +62 -0
- django_cfg/apps/payments/views/api_key_views.py +164 -0
- django_cfg/apps/payments/views/balance_views.py +75 -0
- django_cfg/apps/payments/views/currency_views.py +111 -0
- django_cfg/apps/payments/views/payment_views.py +111 -0
- django_cfg/apps/payments/views/subscription_views.py +135 -0
- django_cfg/apps/payments/views/tariff_views.py +131 -0
- django_cfg/core/config.py +6 -0
- django_cfg/models/revolution.py +14 -0
- django_cfg/modules/base.py +9 -0
- {django_cfg-1.2.21.dist-info → django_cfg-1.2.22.dist-info}/METADATA +1 -1
- {django_cfg-1.2.21.dist-info → django_cfg-1.2.22.dist-info}/RECORD +51 -10
- {django_cfg-1.2.21.dist-info → django_cfg-1.2.22.dist-info}/WHEEL +0 -0
- {django_cfg-1.2.21.dist-info → django_cfg-1.2.22.dist-info}/entry_points.txt +0 -0
- {django_cfg-1.2.21.dist-info → django_cfg-1.2.22.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,56 @@
|
|
1
|
+
"""
|
2
|
+
DRF serializers for the universal payments system.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from .balance import (
|
6
|
+
UserBalanceSerializer, TransactionSerializer, TransactionListSerializer
|
7
|
+
)
|
8
|
+
from .payments import (
|
9
|
+
UniversalPaymentSerializer, PaymentCreateSerializer, PaymentListSerializer
|
10
|
+
)
|
11
|
+
from .subscriptions import (
|
12
|
+
SubscriptionSerializer, SubscriptionCreateSerializer, SubscriptionListSerializer,
|
13
|
+
EndpointGroupSerializer
|
14
|
+
)
|
15
|
+
from .api_keys import (
|
16
|
+
APIKeySerializer, APIKeyCreateSerializer, APIKeyListSerializer
|
17
|
+
)
|
18
|
+
from .currencies import (
|
19
|
+
CurrencySerializer, CurrencyNetworkSerializer, CurrencyListSerializer
|
20
|
+
)
|
21
|
+
from .tariffs import (
|
22
|
+
TariffSerializer, TariffEndpointGroupSerializer, TariffListSerializer
|
23
|
+
)
|
24
|
+
|
25
|
+
__all__ = [
|
26
|
+
# Balance
|
27
|
+
'UserBalanceSerializer',
|
28
|
+
'TransactionSerializer',
|
29
|
+
'TransactionListSerializer',
|
30
|
+
|
31
|
+
# Payments
|
32
|
+
'UniversalPaymentSerializer',
|
33
|
+
'PaymentCreateSerializer',
|
34
|
+
'PaymentListSerializer',
|
35
|
+
|
36
|
+
# Subscriptions
|
37
|
+
'SubscriptionSerializer',
|
38
|
+
'SubscriptionCreateSerializer',
|
39
|
+
'SubscriptionListSerializer',
|
40
|
+
'EndpointGroupSerializer',
|
41
|
+
|
42
|
+
# API Keys
|
43
|
+
'APIKeySerializer',
|
44
|
+
'APIKeyCreateSerializer',
|
45
|
+
'APIKeyListSerializer',
|
46
|
+
|
47
|
+
# Currencies
|
48
|
+
'CurrencySerializer',
|
49
|
+
'CurrencyNetworkSerializer',
|
50
|
+
'CurrencyListSerializer',
|
51
|
+
|
52
|
+
# Tariffs
|
53
|
+
'TariffSerializer',
|
54
|
+
'TariffEndpointGroupSerializer',
|
55
|
+
'TariffListSerializer',
|
56
|
+
]
|
@@ -0,0 +1,51 @@
|
|
1
|
+
"""
|
2
|
+
API key serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import APIKey
|
7
|
+
|
8
|
+
|
9
|
+
class APIKeySerializer(serializers.ModelSerializer):
|
10
|
+
"""API key with usage stats."""
|
11
|
+
|
12
|
+
is_valid = serializers.SerializerMethodField()
|
13
|
+
|
14
|
+
class Meta:
|
15
|
+
model = APIKey
|
16
|
+
fields = [
|
17
|
+
'id', 'name', 'key_value', 'key_prefix', 'usage_count',
|
18
|
+
'is_active', 'is_valid', 'last_used', 'expires_at',
|
19
|
+
'created_at'
|
20
|
+
]
|
21
|
+
read_only_fields = ['key_value', 'key_prefix', 'usage_count', 'last_used', 'created_at']
|
22
|
+
|
23
|
+
def get_is_valid(self, obj):
|
24
|
+
"""Get validation status."""
|
25
|
+
return obj.is_valid()
|
26
|
+
|
27
|
+
|
28
|
+
class APIKeyCreateSerializer(serializers.ModelSerializer):
|
29
|
+
"""Create API key."""
|
30
|
+
|
31
|
+
class Meta:
|
32
|
+
model = APIKey
|
33
|
+
fields = ['name', 'expires_at']
|
34
|
+
|
35
|
+
|
36
|
+
class APIKeyListSerializer(serializers.ModelSerializer):
|
37
|
+
"""Simplified API key for lists."""
|
38
|
+
|
39
|
+
is_valid = serializers.SerializerMethodField()
|
40
|
+
|
41
|
+
class Meta:
|
42
|
+
model = APIKey
|
43
|
+
fields = [
|
44
|
+
'id', 'name', 'key_prefix', 'usage_count', 'is_active', 'is_valid',
|
45
|
+
'last_used', 'expires_at', 'created_at'
|
46
|
+
]
|
47
|
+
read_only_fields = ['key_prefix', 'usage_count', 'last_used', 'created_at']
|
48
|
+
|
49
|
+
def get_is_valid(self, obj):
|
50
|
+
"""Get validation status."""
|
51
|
+
return obj.is_valid()
|
@@ -0,0 +1,59 @@
|
|
1
|
+
"""
|
2
|
+
Balance serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import UserBalance, Transaction
|
7
|
+
|
8
|
+
|
9
|
+
class UserBalanceSerializer(serializers.ModelSerializer):
|
10
|
+
"""User balance with computed fields."""
|
11
|
+
|
12
|
+
total_balance = serializers.ReadOnlyField()
|
13
|
+
pending_payments_count = serializers.SerializerMethodField()
|
14
|
+
|
15
|
+
class Meta:
|
16
|
+
model = UserBalance
|
17
|
+
fields = [
|
18
|
+
'amount_usd', 'reserved_usd', 'total_balance',
|
19
|
+
'total_earned', 'total_spent', 'last_transaction_at',
|
20
|
+
'pending_payments_count', 'created_at', 'updated_at'
|
21
|
+
]
|
22
|
+
read_only_fields = [
|
23
|
+
'total_earned', 'total_spent', 'last_transaction_at',
|
24
|
+
'created_at', 'updated_at'
|
25
|
+
]
|
26
|
+
|
27
|
+
def get_pending_payments_count(self, obj):
|
28
|
+
"""Get count of pending payments."""
|
29
|
+
return obj.user.universal_payments.filter(status='pending').count()
|
30
|
+
|
31
|
+
|
32
|
+
class TransactionSerializer(serializers.ModelSerializer):
|
33
|
+
"""Transaction with details."""
|
34
|
+
|
35
|
+
transaction_type_display = serializers.CharField(source='get_transaction_type_display', read_only=True)
|
36
|
+
is_credit = serializers.ReadOnlyField()
|
37
|
+
is_debit = serializers.ReadOnlyField()
|
38
|
+
|
39
|
+
class Meta:
|
40
|
+
model = Transaction
|
41
|
+
fields = [
|
42
|
+
'id', 'amount_usd', 'transaction_type', 'transaction_type_display',
|
43
|
+
'description', 'balance_before', 'balance_after',
|
44
|
+
'is_credit', 'is_debit', 'reference_id', 'created_at'
|
45
|
+
]
|
46
|
+
read_only_fields = ['id', 'balance_before', 'balance_after', 'created_at']
|
47
|
+
|
48
|
+
|
49
|
+
class TransactionListSerializer(serializers.ModelSerializer):
|
50
|
+
"""Simplified transaction for lists."""
|
51
|
+
|
52
|
+
transaction_type_display = serializers.CharField(source='get_transaction_type_display', read_only=True)
|
53
|
+
|
54
|
+
class Meta:
|
55
|
+
model = Transaction
|
56
|
+
fields = [
|
57
|
+
'id', 'amount_usd', 'transaction_type', 'transaction_type_display',
|
58
|
+
'description', 'balance_after', 'created_at'
|
59
|
+
]
|
@@ -0,0 +1,55 @@
|
|
1
|
+
"""
|
2
|
+
Currency serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import Currency, CurrencyNetwork
|
7
|
+
|
8
|
+
|
9
|
+
class CurrencySerializer(serializers.ModelSerializer):
|
10
|
+
"""Currency with type info."""
|
11
|
+
|
12
|
+
currency_type_display = serializers.CharField(source='get_currency_type_display', read_only=True)
|
13
|
+
is_crypto = serializers.SerializerMethodField()
|
14
|
+
is_fiat = serializers.SerializerMethodField()
|
15
|
+
|
16
|
+
class Meta:
|
17
|
+
model = Currency
|
18
|
+
fields = [
|
19
|
+
'id', 'code', 'name', 'symbol', 'currency_type', 'currency_type_display',
|
20
|
+
'is_crypto', 'is_fiat', 'decimal_places', 'usd_rate', 'rate_updated_at',
|
21
|
+
'is_active', 'min_payment_amount'
|
22
|
+
]
|
23
|
+
read_only_fields = ['rate_updated_at']
|
24
|
+
|
25
|
+
def get_is_crypto(self, obj):
|
26
|
+
"""Check if currency is crypto."""
|
27
|
+
return obj.is_crypto
|
28
|
+
|
29
|
+
def get_is_fiat(self, obj):
|
30
|
+
"""Check if currency is fiat."""
|
31
|
+
return obj.is_fiat
|
32
|
+
|
33
|
+
|
34
|
+
class CurrencyNetworkSerializer(serializers.ModelSerializer):
|
35
|
+
"""Currency network with status."""
|
36
|
+
|
37
|
+
currency_code = serializers.CharField(source='currency.code', read_only=True)
|
38
|
+
currency_name = serializers.CharField(source='currency.name', read_only=True)
|
39
|
+
|
40
|
+
class Meta:
|
41
|
+
model = CurrencyNetwork
|
42
|
+
fields = [
|
43
|
+
'id', 'currency', 'currency_code', 'currency_name', 'network_code',
|
44
|
+
'network_name', 'is_active', 'confirmation_blocks'
|
45
|
+
]
|
46
|
+
|
47
|
+
|
48
|
+
class CurrencyListSerializer(serializers.ModelSerializer):
|
49
|
+
"""Simplified currency for lists."""
|
50
|
+
|
51
|
+
currency_type_display = serializers.CharField(source='get_currency_type_display', read_only=True)
|
52
|
+
|
53
|
+
class Meta:
|
54
|
+
model = Currency
|
55
|
+
fields = ['id', 'code', 'name', 'currency_type', 'currency_type_display', 'is_active']
|
@@ -0,0 +1,62 @@
|
|
1
|
+
"""
|
2
|
+
Payment serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import UniversalPayment
|
7
|
+
|
8
|
+
|
9
|
+
class UniversalPaymentSerializer(serializers.ModelSerializer):
|
10
|
+
"""Universal payment with status info."""
|
11
|
+
|
12
|
+
status_display = serializers.CharField(source='get_status_display', read_only=True)
|
13
|
+
provider_display = serializers.CharField(source='get_provider_display', read_only=True)
|
14
|
+
is_pending = serializers.ReadOnlyField()
|
15
|
+
is_completed = serializers.ReadOnlyField()
|
16
|
+
is_failed = serializers.ReadOnlyField()
|
17
|
+
|
18
|
+
class Meta:
|
19
|
+
model = UniversalPayment
|
20
|
+
fields = [
|
21
|
+
'id', 'internal_payment_id', 'provider_payment_id', 'order_id',
|
22
|
+
'amount_usd', 'currency_code', 'actual_amount_usd', 'actual_currency_code',
|
23
|
+
'fee_amount_usd', 'provider', 'provider_display', 'status', 'status_display',
|
24
|
+
'pay_address', 'pay_amount', 'network', 'description',
|
25
|
+
'is_pending', 'is_completed', 'is_failed',
|
26
|
+
'expires_at', 'completed_at', 'created_at', 'updated_at'
|
27
|
+
]
|
28
|
+
read_only_fields = [
|
29
|
+
'id', 'internal_payment_id', 'provider_payment_id',
|
30
|
+
'actual_amount_usd', 'actual_currency_code', 'fee_amount_usd',
|
31
|
+
'pay_address', 'pay_amount', 'completed_at', 'processed_at',
|
32
|
+
'created_at', 'updated_at'
|
33
|
+
]
|
34
|
+
|
35
|
+
|
36
|
+
class PaymentCreateSerializer(serializers.ModelSerializer):
|
37
|
+
"""Create payment request."""
|
38
|
+
|
39
|
+
class Meta:
|
40
|
+
model = UniversalPayment
|
41
|
+
fields = [
|
42
|
+
'amount_usd', 'currency_code', 'provider', 'description', 'order_id'
|
43
|
+
]
|
44
|
+
|
45
|
+
def validate_amount_usd(self, value):
|
46
|
+
"""Validate payment amount."""
|
47
|
+
if value < 1.0:
|
48
|
+
raise serializers.ValidationError("Minimum payment amount is $1.00")
|
49
|
+
return value
|
50
|
+
|
51
|
+
|
52
|
+
class PaymentListSerializer(serializers.ModelSerializer):
|
53
|
+
"""Simplified payment for lists."""
|
54
|
+
|
55
|
+
status_display = serializers.CharField(source='get_status_display', read_only=True)
|
56
|
+
|
57
|
+
class Meta:
|
58
|
+
model = UniversalPayment
|
59
|
+
fields = [
|
60
|
+
'id', 'internal_payment_id', 'amount_usd', 'currency_code',
|
61
|
+
'provider', 'status', 'status_display', 'description', 'created_at'
|
62
|
+
]
|
@@ -0,0 +1,71 @@
|
|
1
|
+
"""
|
2
|
+
Subscription serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import Subscription, EndpointGroup
|
7
|
+
|
8
|
+
|
9
|
+
class EndpointGroupSerializer(serializers.ModelSerializer):
|
10
|
+
"""Endpoint group with pricing tiers."""
|
11
|
+
|
12
|
+
class Meta:
|
13
|
+
model = EndpointGroup
|
14
|
+
fields = [
|
15
|
+
'id', 'name', 'display_name', 'description',
|
16
|
+
'basic_price', 'premium_price', 'enterprise_price',
|
17
|
+
'basic_limit', 'premium_limit', 'enterprise_limit',
|
18
|
+
'is_active', 'require_api_key'
|
19
|
+
]
|
20
|
+
|
21
|
+
|
22
|
+
class SubscriptionSerializer(serializers.ModelSerializer):
|
23
|
+
"""Subscription with computed fields."""
|
24
|
+
|
25
|
+
endpoint_group_name = serializers.CharField(source='endpoint_group.name', read_only=True)
|
26
|
+
endpoint_group_display = serializers.CharField(source='endpoint_group.display_name', read_only=True)
|
27
|
+
status_display = serializers.CharField(source='get_status_display', read_only=True)
|
28
|
+
tier_display = serializers.CharField(source='get_tier_display', read_only=True)
|
29
|
+
is_active_subscription = serializers.ReadOnlyField(source='is_active')
|
30
|
+
is_usage_exceeded = serializers.ReadOnlyField()
|
31
|
+
|
32
|
+
class Meta:
|
33
|
+
model = Subscription
|
34
|
+
fields = [
|
35
|
+
'id', 'endpoint_group', 'endpoint_group_name', 'endpoint_group_display',
|
36
|
+
'tier', 'tier_display', 'status', 'status_display', 'monthly_price',
|
37
|
+
'usage_limit', 'usage_current', 'is_active_subscription', 'is_usage_exceeded',
|
38
|
+
'last_billed', 'next_billing', 'expires_at', 'created_at'
|
39
|
+
]
|
40
|
+
read_only_fields = [
|
41
|
+
'usage_current', 'last_billed', 'next_billing', 'cancelled_at', 'created_at'
|
42
|
+
]
|
43
|
+
|
44
|
+
|
45
|
+
class SubscriptionCreateSerializer(serializers.Serializer):
|
46
|
+
"""Create subscription request."""
|
47
|
+
|
48
|
+
endpoint_group_id = serializers.IntegerField()
|
49
|
+
tier = serializers.ChoiceField(choices=Subscription.SubscriptionTier.choices)
|
50
|
+
|
51
|
+
def validate_endpoint_group_id(self, value):
|
52
|
+
"""Validate endpoint group exists."""
|
53
|
+
try:
|
54
|
+
endpoint_group = EndpointGroup.objects.get(id=value, is_active=True)
|
55
|
+
return value
|
56
|
+
except EndpointGroup.DoesNotExist:
|
57
|
+
raise serializers.ValidationError("Endpoint group not found or inactive")
|
58
|
+
|
59
|
+
|
60
|
+
class SubscriptionListSerializer(serializers.ModelSerializer):
|
61
|
+
"""Simplified subscription for lists."""
|
62
|
+
|
63
|
+
endpoint_group_name = serializers.CharField(source='endpoint_group.name', read_only=True)
|
64
|
+
status_display = serializers.CharField(source='get_status_display', read_only=True)
|
65
|
+
|
66
|
+
class Meta:
|
67
|
+
model = Subscription
|
68
|
+
fields = [
|
69
|
+
'id', 'endpoint_group_name', 'tier', 'status', 'status_display',
|
70
|
+
'monthly_price', 'usage_current', 'usage_limit', 'expires_at'
|
71
|
+
]
|
@@ -0,0 +1,56 @@
|
|
1
|
+
"""
|
2
|
+
Tariff serializers.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from rest_framework import serializers
|
6
|
+
from ..models import Tariff, TariffEndpointGroup
|
7
|
+
|
8
|
+
|
9
|
+
class TariffSerializer(serializers.ModelSerializer):
|
10
|
+
"""Tariff with pricing info."""
|
11
|
+
|
12
|
+
is_free = serializers.SerializerMethodField()
|
13
|
+
endpoint_groups_count = serializers.SerializerMethodField()
|
14
|
+
|
15
|
+
class Meta:
|
16
|
+
model = Tariff
|
17
|
+
fields = [
|
18
|
+
'id', 'name', 'display_name', 'description', 'monthly_price',
|
19
|
+
'request_limit', 'is_free', 'is_active', 'endpoint_groups_count'
|
20
|
+
]
|
21
|
+
|
22
|
+
def get_is_free(self, obj):
|
23
|
+
"""Check if tariff is free."""
|
24
|
+
return obj.is_free
|
25
|
+
|
26
|
+
def get_endpoint_groups_count(self, obj):
|
27
|
+
"""Get count of enabled endpoint groups."""
|
28
|
+
return obj.endpoint_groups.filter(is_enabled=True).count()
|
29
|
+
|
30
|
+
|
31
|
+
class TariffEndpointGroupSerializer(serializers.ModelSerializer):
|
32
|
+
"""Tariff endpoint group association."""
|
33
|
+
|
34
|
+
tariff_name = serializers.CharField(source='tariff.name', read_only=True)
|
35
|
+
endpoint_group_name = serializers.CharField(source='endpoint_group.name', read_only=True)
|
36
|
+
|
37
|
+
class Meta:
|
38
|
+
model = TariffEndpointGroup
|
39
|
+
fields = [
|
40
|
+
'id', 'tariff', 'tariff_name', 'endpoint_group', 'endpoint_group_name',
|
41
|
+
'is_enabled'
|
42
|
+
]
|
43
|
+
|
44
|
+
|
45
|
+
class TariffListSerializer(serializers.ModelSerializer):
|
46
|
+
"""Simplified tariff for lists."""
|
47
|
+
|
48
|
+
is_free = serializers.SerializerMethodField()
|
49
|
+
|
50
|
+
class Meta:
|
51
|
+
model = Tariff
|
52
|
+
fields = ['id', 'name', 'display_name', 'monthly_price', 'is_free', 'is_active']
|
53
|
+
|
54
|
+
def get_is_free(self, obj):
|
55
|
+
"""Check if tariff is free."""
|
56
|
+
return obj.is_free
|
@@ -0,0 +1,14 @@
|
|
1
|
+
"""
|
2
|
+
Universal payment services.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from .base import PaymentProvider, PaymentService
|
6
|
+
from .nowpayments import NowPaymentsProvider
|
7
|
+
from .redis_service import RedisService
|
8
|
+
|
9
|
+
__all__ = [
|
10
|
+
'PaymentProvider',
|
11
|
+
'PaymentService',
|
12
|
+
'NowPaymentsProvider',
|
13
|
+
'RedisService',
|
14
|
+
]
|
@@ -0,0 +1,68 @@
|
|
1
|
+
"""
|
2
|
+
Base payment service classes.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from abc import ABC, abstractmethod
|
6
|
+
from typing import Dict, Any, Optional
|
7
|
+
from decimal import Decimal
|
8
|
+
|
9
|
+
|
10
|
+
class PaymentProvider(ABC):
|
11
|
+
"""Abstract base class for payment providers."""
|
12
|
+
|
13
|
+
def __init__(self, config: Dict[str, Any]):
|
14
|
+
"""Initialize provider with config."""
|
15
|
+
self.config = config
|
16
|
+
self.name = self.__class__.__name__.lower().replace('provider', '')
|
17
|
+
|
18
|
+
@abstractmethod
|
19
|
+
def create_payment(self, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
20
|
+
"""Create a payment request."""
|
21
|
+
pass
|
22
|
+
|
23
|
+
@abstractmethod
|
24
|
+
def check_payment_status(self, payment_id: str) -> Dict[str, Any]:
|
25
|
+
"""Check payment status."""
|
26
|
+
pass
|
27
|
+
|
28
|
+
@abstractmethod
|
29
|
+
def process_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
30
|
+
"""Process webhook payload."""
|
31
|
+
pass
|
32
|
+
|
33
|
+
@abstractmethod
|
34
|
+
def get_supported_currencies(self) -> list[str]:
|
35
|
+
"""Get list of supported currencies."""
|
36
|
+
pass
|
37
|
+
|
38
|
+
|
39
|
+
class PaymentService:
|
40
|
+
"""Main payment service with provider management."""
|
41
|
+
|
42
|
+
def __init__(self):
|
43
|
+
"""Initialize payment service."""
|
44
|
+
self.providers: Dict[str, PaymentProvider] = {}
|
45
|
+
|
46
|
+
def register_provider(self, provider: PaymentProvider) -> None:
|
47
|
+
"""Register a payment provider."""
|
48
|
+
self.providers[provider.name] = provider
|
49
|
+
|
50
|
+
def get_provider(self, name: str) -> Optional[PaymentProvider]:
|
51
|
+
"""Get provider by name."""
|
52
|
+
return self.providers.get(name)
|
53
|
+
|
54
|
+
def create_payment(self, provider_name: str, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
55
|
+
"""Create payment using specified provider."""
|
56
|
+
provider = self.get_provider(provider_name)
|
57
|
+
if not provider:
|
58
|
+
raise ValueError(f"Provider {provider_name} not found")
|
59
|
+
|
60
|
+
return provider.create_payment(amount, currency, **kwargs)
|
61
|
+
|
62
|
+
def process_webhook(self, provider_name: str, payload: Dict[str, Any]) -> Dict[str, Any]:
|
63
|
+
"""Process webhook for specified provider."""
|
64
|
+
provider = self.get_provider(provider_name)
|
65
|
+
if not provider:
|
66
|
+
raise ValueError(f"Provider {provider_name} not found")
|
67
|
+
|
68
|
+
return provider.process_webhook(payload)
|
@@ -0,0 +1,78 @@
|
|
1
|
+
"""
|
2
|
+
NowPayments provider implementation.
|
3
|
+
"""
|
4
|
+
|
5
|
+
from typing import Dict, Any
|
6
|
+
from decimal import Decimal
|
7
|
+
import requests
|
8
|
+
from .base import PaymentProvider
|
9
|
+
|
10
|
+
|
11
|
+
class NowPaymentsProvider(PaymentProvider):
|
12
|
+
"""NowPayments crypto payment provider."""
|
13
|
+
|
14
|
+
def __init__(self, config: Dict[str, Any]):
|
15
|
+
"""Initialize NowPayments provider."""
|
16
|
+
super().__init__(config)
|
17
|
+
self.api_key = config.get('api_key')
|
18
|
+
self.base_url = config.get('base_url', 'https://api.nowpayments.io/v1')
|
19
|
+
self.headers = {'x-api-key': self.api_key}
|
20
|
+
|
21
|
+
def create_payment(self, amount: Decimal, currency: str, **kwargs) -> Dict[str, Any]:
|
22
|
+
"""Create payment via NowPayments API."""
|
23
|
+
payload = {
|
24
|
+
'price_amount': float(amount),
|
25
|
+
'price_currency': 'USD',
|
26
|
+
'pay_currency': currency.upper(),
|
27
|
+
'order_id': kwargs.get('order_id'),
|
28
|
+
'order_description': kwargs.get('description', 'Payment'),
|
29
|
+
'ipn_callback_url': kwargs.get('callback_url'),
|
30
|
+
'success_url': kwargs.get('success_url'),
|
31
|
+
'cancel_url': kwargs.get('cancel_url'),
|
32
|
+
}
|
33
|
+
|
34
|
+
response = requests.post(
|
35
|
+
f"{self.base_url}/payment",
|
36
|
+
json=payload,
|
37
|
+
headers=self.headers,
|
38
|
+
timeout=30
|
39
|
+
)
|
40
|
+
response.raise_for_status()
|
41
|
+
return response.json()
|
42
|
+
|
43
|
+
def check_payment_status(self, payment_id: str) -> Dict[str, Any]:
|
44
|
+
"""Check payment status via NowPayments API."""
|
45
|
+
response = requests.get(
|
46
|
+
f"{self.base_url}/payment/{payment_id}",
|
47
|
+
headers=self.headers,
|
48
|
+
timeout=30
|
49
|
+
)
|
50
|
+
response.raise_for_status()
|
51
|
+
return response.json()
|
52
|
+
|
53
|
+
def process_webhook(self, payload: Dict[str, Any]) -> Dict[str, Any]:
|
54
|
+
"""Process NowPayments webhook."""
|
55
|
+
# Extract important fields from webhook
|
56
|
+
return {
|
57
|
+
'payment_id': payload.get('payment_id'),
|
58
|
+
'payment_status': payload.get('payment_status'),
|
59
|
+
'pay_address': payload.get('pay_address'),
|
60
|
+
'pay_amount': payload.get('pay_amount'),
|
61
|
+
'pay_currency': payload.get('pay_currency'),
|
62
|
+
'price_amount': payload.get('price_amount'),
|
63
|
+
'price_currency': payload.get('price_currency'),
|
64
|
+
'order_id': payload.get('order_id'),
|
65
|
+
'outcome_amount': payload.get('outcome_amount'),
|
66
|
+
'outcome_currency': payload.get('outcome_currency'),
|
67
|
+
}
|
68
|
+
|
69
|
+
def get_supported_currencies(self) -> list[str]:
|
70
|
+
"""Get supported cryptocurrencies from NowPayments."""
|
71
|
+
response = requests.get(
|
72
|
+
f"{self.base_url}/currencies",
|
73
|
+
headers=self.headers,
|
74
|
+
timeout=30
|
75
|
+
)
|
76
|
+
response.raise_for_status()
|
77
|
+
data = response.json()
|
78
|
+
return data.get('currencies', [])
|
@@ -0,0 +1,77 @@
|
|
1
|
+
"""
|
2
|
+
Payment provider integrations using Pydantic for external data validation.
|
3
|
+
Only for provider responses and internal service communication.
|
4
|
+
"""
|
5
|
+
|
6
|
+
from pydantic import BaseModel, Field, ConfigDict, field_validator
|
7
|
+
from decimal import Decimal
|
8
|
+
from datetime import datetime, timezone
|
9
|
+
from typing import Optional, Dict, Any
|
10
|
+
|
11
|
+
|
12
|
+
class NowPaymentsWebhook(BaseModel):
|
13
|
+
"""NowPayments webhook data validation."""
|
14
|
+
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
15
|
+
|
16
|
+
payment_id: str
|
17
|
+
payment_status: str
|
18
|
+
pay_address: str
|
19
|
+
pay_amount: Decimal
|
20
|
+
pay_currency: str
|
21
|
+
order_id: str
|
22
|
+
order_description: Optional[str] = None
|
23
|
+
ipn_callback_url: Optional[str] = None
|
24
|
+
created_at: Optional[datetime] = None
|
25
|
+
updated_at: Optional[datetime] = None
|
26
|
+
|
27
|
+
@field_validator('pay_amount')
|
28
|
+
@classmethod
|
29
|
+
def validate_amount(cls, v: Decimal) -> Decimal:
|
30
|
+
if v <= 0:
|
31
|
+
raise ValueError("Payment amount must be positive")
|
32
|
+
return v
|
33
|
+
|
34
|
+
|
35
|
+
class NowPaymentsCreateResponse(BaseModel):
|
36
|
+
"""NowPayments payment creation response."""
|
37
|
+
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
38
|
+
|
39
|
+
payment_id: str
|
40
|
+
payment_status: str
|
41
|
+
pay_address: str
|
42
|
+
pay_amount: Decimal
|
43
|
+
pay_currency: str
|
44
|
+
order_id: str
|
45
|
+
order_description: Optional[str] = None
|
46
|
+
ipn_callback_url: Optional[str] = None
|
47
|
+
created_at: datetime
|
48
|
+
updated_at: datetime
|
49
|
+
|
50
|
+
|
51
|
+
class NowPaymentsStatusResponse(BaseModel):
|
52
|
+
"""NowPayments payment status response."""
|
53
|
+
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
54
|
+
|
55
|
+
payment_id: str
|
56
|
+
payment_status: str
|
57
|
+
pay_address: str
|
58
|
+
pay_amount: Decimal
|
59
|
+
actually_paid: Optional[Decimal] = None
|
60
|
+
pay_currency: str
|
61
|
+
order_id: str
|
62
|
+
outcome_amount: Optional[Decimal] = None
|
63
|
+
outcome_currency: Optional[str] = None
|
64
|
+
|
65
|
+
|
66
|
+
class ProviderWebhookData(BaseModel):
|
67
|
+
"""Generic webhook data for any provider."""
|
68
|
+
model_config = ConfigDict(validate_assignment=True, extra="forbid")
|
69
|
+
|
70
|
+
provider: str
|
71
|
+
payment_id: str
|
72
|
+
status: str
|
73
|
+
amount: Optional[Decimal] = None
|
74
|
+
currency: Optional[str] = None
|
75
|
+
raw_data: Dict[str, Any] = Field(default_factory=dict)
|
76
|
+
signature: Optional[str] = None
|
77
|
+
received_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc))
|