Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create refill functional #3

Merged
merged 3 commits into from
Mar 17, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion backend/payments/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ TODO
- `DEBUG`- настройка Django для ключения отладочного режима.
- `ALLOWED_HOSTS` - список разрешенных хостов.
- `DATABASE_URL` - адрес для подключения к БД PostgreSQL. [Формат записи](https://github.com/jacobian/dj-database-url#url-schema)
- `JWT_SECRET_KEY` - ключ для расшифроки JWT-токена.
- `account_id` - id вашего магазина yookassa.
- `shop_secret_key` - api ключ вашего магазина yookassa.

## Установка и настройка flake8
На проекте используется линтер flake8 с плагинами. Flake8 не дает возможности перечислить используемые плагины,
Expand Down
19 changes: 19 additions & 0 deletions backend/payments/apps/payment_accounts/serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from django.conf import settings
from django.core.validators import MinValueValidator
from rest_framework import serializers


class CreatePaymentSerializer(serializers.Serializer):
uuid = serializers.UUIDField()
value = serializers.DecimalField(
decimal_places=2,
max_digits=settings.MAX_BALANCE_DIGITS,
validators=[MinValueValidator(0, message='Insufficient Funds')],
)
commission = serializers.DecimalField(
decimal_places=1,
max_digits=settings.MAX_BALANCE_DIGITS,
validators=[MinValueValidator(0, message='Insufficient Funds')],
)
payment_type = serializers.CharField(max_length=20)
return_url = serializers.URLField()
51 changes: 51 additions & 0 deletions backend/payments/apps/payment_accounts/services/create_payment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from environs import Env
from yookassa import Configuration, Payment

from ..models import Account, BalanceChange

env = Env()
env.read_env()
Configuration.account_id = env.int('account_id')
Configuration.secret_key = env.str('shop_secret_key')


def create_payment(uuid, value, commission, payment_type, return_url):
pay_value = value * (1 / (1 - commission / 100))
clownkill marked this conversation as resolved.
Show resolved Hide resolved
try:
user = Account.objects.get(user_uid=uuid)
clownkill marked this conversation as resolved.
Show resolved Hide resolved
except BaseException:
user = Account.objects.create(
clownkill marked this conversation as resolved.
Show resolved Hide resolved
user_uid=uuid,
)
user.save()

changing = BalanceChange.objects.create(
clownkill marked this conversation as resolved.
Show resolved Hide resolved
account_id=user,
amount=value,
is_accepted=False,
operation_type='DEPOSIT',
)
changing.save()

payment = Payment.create({
'amount': {
'value': pay_value,
'currency': 'RUB',
},
'payment_method_data': {
'type': payment_type,
},
'confirmation': {
'type': 'redirect',
'return_url': return_url,
},
'metadata': {
'table_id': changing.id,
'user_id': user.id,
},
'capture': True,
'refundable': False,
'description': 'Пополнение на ' + str(value),
})

return payment.confirmation.confirmation_url
4 changes: 3 additions & 1 deletion backend/payments/apps/payment_accounts/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.urls import path

from . import views

urlpatterns = [

path('create_payment/', views.CreatePaymentView.as_view()),
path('payment_acceptance/', views.CreatePaymentAcceptanceView.as_view()),
]
53 changes: 51 additions & 2 deletions backend/payments/apps/payment_accounts/views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,52 @@
from django.shortcuts import render
import json
from decimal import Decimal

# Create your views here.
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response

from .models import Account, BalanceChange
from .serializers import CreatePaymentSerializer
from .services.create_payment import create_payment


class CreatePaymentView(CreateAPIView):
serializer_class = CreatePaymentSerializer

def post(self, request, *args, **kwargs):
serializer = CreatePaymentSerializer(data=request.POST)

if serializer.is_valid():
data = serializer.validated_data
clownkill marked this conversation as resolved.
Show resolved Hide resolved
else:
return Response(400)

confirmation_url = create_payment(
uuid=data.get('uuid'),
value=data.get('value'),
commission=data.get('commission'),
payment_type=data.get('payment_type'),
return_url=data.get('return_url'),
)

return Response({'confirmation_url': confirmation_url}, 200)


class CreatePaymentAcceptanceView(CreateAPIView):

def post(self, request, *args, **kwargs):
response = json.loads(request.body)
table = BalanceChange.objects.get(
clownkill marked this conversation as resolved.
Show resolved Hide resolved
id=response['object']['metadata']['table_id'],
)

if response['event'] == 'payment.succeeded':
table.is_accepted = True
table.save()
Account.deposit(
pk=response['object']['metadata']['user_id'],
amount=Decimal(response['object']['income_amount']['value']),
)
elif response['event'] == 'payment.canceled':
table.delete()

return Response(200)
1 change: 0 additions & 1 deletion backend/payments/apps/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from django.urls import include, path


urlpatterns = [
path('payment_accounts/', include('apps.payment_accounts.urls')),
path('transactions/', include('apps.transactions.urls')),
Expand Down
2 changes: 1 addition & 1 deletion backend/payments/config/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 100,
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
'rest_framework.permissions.AllowAny',
],
}

Expand Down
4 changes: 1 addition & 3 deletions backend/payments/config/urls.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from django.contrib import admin
from django.urls import include, path
from drf_spectacular.views import SpectacularAPIView
from drf_spectacular.views import SpectacularSwaggerView

from drf_spectacular.views import SpectacularAPIView, SpectacularSwaggerView

urlpatterns = [
path('admin/', admin.site.urls),
Expand Down
1 change: 1 addition & 0 deletions backend/payments/requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,4 @@ djangorestframework==3.14.0
drf-spectacular==0.26.0
pyjwt==2.6.0
django-extensions==3.2.1
yookassa==2.3.5