Files
goodtimes/manage_wallets/api/views.py
2024-03-05 16:11:58 +05:30

380 lines
14 KiB
Python

import json
from django.shortcuts import get_object_or_404
import requests
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from accounts.models import IAmPrincipal, IAmPrincipalType
from goodtimes import services, constants
from decimal import Decimal
from manage_wallets import models
from django.conf import settings
from . import serializers
from goodtimes.utils import ApiResponse
# from PayTm import Checksum, check
# from Paytm_Python.paytmchecksum import PaytmChecksum
# from paytmchecksum import PaytmChecksum
# from nifty11_project.services import SMSError, SMSService
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework_simplejwt.authentication import JWTAuthentication
import stripe
class BecomeAMerchantView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
stripe.api_key = settings.STRIPE_SECRET_KEY
def post(self, request, type):
print(request.data)
amount = 1000
principal_type = request.data["principal_type"]
try:
payment_intent = stripe.PaymentIntent.create(
amount=100000,
currency="INR",
description="Merchant Registration",
metadata={
"principal_id": request.user.id,
"principal_type": principal_type,
},
)
# payment_intent_id = payment_intent.id # Get the payment_intent ID
return Response(
{
"client_secret": payment_intent.client_secret,
"message": "Payment intent created successfully",
}
)
except stripe.error.StripeError as e:
# Handle Stripe-related errors
return Response({"error": str(e)}, status=400)
@method_decorator(csrf_exempt, name="dispatch")
class StripeWebhookTest(APIView):
authentication_classes = []
permission_classes = [AllowAny]
def post(self, request):
stripe.api_key = settings.STRIPE_SECRET_KEY
payload = request.body
print("payload", payload)
sig_header = request.META["HTTP_STRIPE_SIGNATURE"]
# endpoint_secret = settings.STRIPE_WEBHOOK_SECRET
endpoint_secret = (
"whsec_ccf1f87295603cdd1733995ee2d3c0d6f74c7ceaf28916ea45114a54b7ce1d0f"
)
event = None
try:
event = stripe.Webhook.construct_event(payload, sig_header, endpoint_secret)
except ValueError as e:
value_error_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": constants.ERROR_OCCURR.format(str(e)),
"errors": str(e),
}
return ApiResponse.error(**value_error_response)
except stripe.error.SignatureVerificationError as e:
signature_error_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": constants.ERROR_OCCURR.format(str(e)),
"errors": str(e),
}
return ApiResponse.error(**signature_error_response)
if event["type"] == "payment_intent.succeeded":
payment_intent = event["data"]["object"]
print("Intent succ")
print("payment_intent: ", payment_intent)
metadata = event.data.object.metadata
print("metadata: ", metadata)
principal_id = metadata.get("principal_id")
principal_type = metadata.get("principal_type")
print("user_id: ", principal_id)
print("user_type: ", principal_type)
try:
principal = IAmPrincipal.objects.get(id=principal_id)
except IAmPrincipal.DoesNotExist as e:
error_response = {
"status": status.HTTP_404_NOT_FOUND,
"message": constants.RECORD_NOT_FOUND,
"errors": str(e),
}
return ApiResponse.error(**error_response)
wallet_manager = services.WalletManager(
principal=get_object_or_404(IAmPrincipal, id=principal_id),
principal_type=principal_type,
)
deposit_amount = event.data.object.amount
deposit_transaction = wallet_manager.deposit(
deposit_amount, "merchant_deposit"
)
print("Passed Through principal_wallet Object")
success_response = {
"status": status.HTTP_200_OK,
"message": "Webhook received, payment succeeded",
}
return ApiResponse.success(**success_response)
else:
intent_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": "Webhook received, but payment failed",
}
return ApiResponse.success(**intent_response)
class GetWallet(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
model = models.Wallet
def get(self, request):
try:
# Get the Wallet associated with the request.user
wallet_obj = models.Wallet.objects.get(principal_id=request.user.id)
# Serialize the wallet data
serializer = serializers.WalletSerializer(wallet_obj)
return ApiResponse.success(
status=status.HTTP_200_OK,
message=constants.SUCCESS,
data=serializer.data,
)
except Exception as e:
# Handle any exceptions and return an error response
error_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": constants.FAILURE,
"errors": str(e),
}
return ApiResponse.error(**error_response)
class IsMerchant(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
model = models.Wallet
def get(self, request):
try:
# Get the Wallet associated with the request.user
wallet_obj = models.Wallet.objects.get(principal_id=request.user.id)
merchant_deposit = wallet_obj.merchant_deposit
if merchant_deposit >= 1.00:
success_response = {
"status": status.HTTP_200_OK,
"message": constants.SUCCESS,
"data": {"is_merchant": True},
}
return ApiResponse.success(**success_response)
data_response = {
"status": status.HTTP_200_OK,
"message": constants.SUCCESS,
"data": {"is_merchant": False},
}
return ApiResponse.success(**data_response)
except Exception as e:
# Handle any exceptions and return an error response
error_response = {
"status": status.HTTP_500_INTERNAL_SERVER_ERROR,
"message": constants.INTERNAL_SERVER_ERROR,
"errors": str(e),
}
return ApiResponse.error(**error_response)
class TransactionView(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def get(self, request):
queryset = models.Transaction.objects.filter(principal_id=request.user.id)
serializer = serializers.TransactionSerializer(queryset, many=True)
response = {
"status": status.HTTP_200_OK,
"message": constants.SUCCESS,
"data": serializer.data,
}
return ApiResponse.success(**response)
class TestWebhookAPI(APIView):
authentication_classes = []
permission_classes = [AllowAny]
# event = None
def post(self, request):
event = request.data.get("event", {})
print(event)
# return Response({"data": data})
if event.get("type") == "payment_intent.succeeded":
payment_intent = event.get("data", {}).get("object", {})
print("Intent succ")
print("payment_intent: ", payment_intent)
metadata = payment_intent.get("metadata", {})
print("metadata: ", metadata)
principal_id = metadata.get("principal_id")
principal_type = metadata.get("principal_type")
print("user_id: ", principal_id)
print("user_type: ", principal_type)
try:
principal = IAmPrincipal.objects.get(id=principal_id)
except IAmPrincipal.DoesNotExist as e:
principal_error_response = {
"status": status.HTTP_404_NOT_FOUND,
"message": constants.RECORD_NOT_FOUND,
"errors": str(e),
}
return ApiResponse.error(**principal_error_response)
wallet_manager = services.WalletManager(
principal=get_object_or_404(IAmPrincipal, id=principal_id),
principal_type=principal_type,
)
deposit_amount = event.get("data", {}).get("object", {}).get("amount", {})
deposit_transaction = wallet_manager.deposit(
deposit_amount, "merchant_deposit"
)
print("Passed Through principal_wallet Object")
success_response = {
"status": status.HTTP_200_OK,
"message": "Webhook received, payment succeeded",
}
return ApiResponse.success(**success_response)
else:
intent_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": "Webhook received, but payment failed",
}
return ApiResponse.success(**intent_response)
class TestWebhookAPIWithdraw(APIView):
authentication_classes = []
permission_classes = [AllowAny]
# event = None
def post(self, request):
event = request.data.get("event", {})
print(event)
# return Response({"data": data})
if event.get("type") == "payment_intent.succeeded":
payment_intent = event.get("data", {}).get("object", {})
print("Intent succ")
print("payment_intent: ", payment_intent)
metadata = payment_intent.get("metadata", {})
print("metadata: ", metadata)
principal_id = metadata.get("principal_id")
principal_type = metadata.get("principal_type")
print("user_id: ", principal_id)
print("user_type: ", principal_type)
try:
principal = IAmPrincipal.objects.get(id=principal_id)
except IAmPrincipal.DoesNotExist as e:
error_response = {
"status": status.HTTP_404_NOT_FOUND,
"message": constants.RECORD_NOT_FOUND,
"errors": str(e),
}
return ApiResponse.error(**error_response)
wallet_manager = services.WalletManager(
principal=get_object_or_404(IAmPrincipal, id=principal_id),
principal_type=principal_type,
)
withdraw_amount = event.get("data", {}).get("object", {}).get("amount", {})
try:
withdraw_transaction = wallet_manager.withdraw(
withdraw_amount, "player_deposit"
)
except Exception as e:
exception_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": constants.WITHDRAWAL_FAILED,
"errors": str(e),
}
return ApiResponse.error(**exception_response)
print("Passed Through principal_wallet Object")
success_response = {
"status": status.HTTP_200_OK,
"message": "Webhook received, payment succeeded",
}
return ApiResponse.success(**success_response)
else:
intent_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": "Webhook received, but payment failed",
}
return ApiResponse.success(**intent_response)
class MerchantDeposit(APIView):
authentication_classes = [JWTAuthentication]
permission_classes = [IsAuthenticated]
def post(self, request):
# print(request.data)
serializer = serializers.MerchantDepositSerializer(data=request.data)
# print("serializer: ", serializer)
if serializer.is_valid():
print(serializer.validated_data)
wallet_manager = services.WalletManager(
principal=request.user,
principal_type=IAmPrincipalType.objects.filter(
name=serializer.validated_data["principal_type"]
).first(),
)
deposit_amount = serializer.validated_data["amount"]
deposit_field = serializer.validated_data["field"]
deposit_transaction = wallet_manager.deposit(deposit_amount, deposit_field)
print("Passed Through principal_wallet Object")
current_balance = models.Wallet.objects.get(principal=request.user)
success_response = {
"status": status.HTTP_200_OK,
"message": "Deposit Received",
"data": {
**serializer.data,
"merchant_deposit": current_balance.merchant_deposit,
},
}
return ApiResponse.success(**success_response)
else:
intent_response = {
"status": status.HTTP_400_BAD_REQUEST,
"message": "Deposit Failed",
"errors": serializer.errors,
}
return ApiResponse.error(**intent_response)