Skip to content

Commit

Permalink
Completed transaction logs process for stripe
Browse files Browse the repository at this point in the history
  • Loading branch information
riadelimemmedov committed Mar 19, 2024
1 parent e68adb2 commit b29c573
Show file tree
Hide file tree
Showing 24 changed files with 277 additions and 102 deletions.
15 changes: 15 additions & 0 deletions backend/abstract/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,24 @@ class AppName(Enum):
ImageExtension = ["png", "jpg", "jpeg"]


# !PaymentMethods
PaymentOptions = [
("STRIPE", _("stripe")),
("ETHEREUM", _("ethereum")),
]

# !Configure stripe
stripe_keys = {
"secret_key": config("STRIPE_SECRET_KEY"),
"publishable_key": config("STRIPE_PUBLISHABLE_KEY"),
}
stripe.api_key = stripe_keys["secret_key"]


# session = stripe.checkout.Session.retrieve(
# "cs_test_b1vTOtKpWL95zEGz7wg7BrsGmVZeLUGufdnarAq3BW7jWtMiScuNYkL8pV"
# )


# payment_intent = stripe.PaymentIntent.retrieve(session["payment_intent"])
# print("Payment intend value ", payment_intent)
Empty file.
36 changes: 25 additions & 11 deletions backend/apps/order/views.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import json

from django.contrib.auth.models import User
from rest_framework import authentication, permissions
from rest_framework.response import Response
from rest_framework.views import APIView

from abstract.constants import stripe, stripe_keys
from apps.transaction.helpers import save_transaction


# !OrderView
Expand All @@ -17,24 +20,35 @@ class OrderView(APIView):

def post(self, request, format=None):
domain_url = "http://localhost:8001/"

body = json.loads(request.body.decode("utf-8"))
line_items = []
pet_data = []
for pet in body["pets"]:
item = {
"name": str(pet[2]),
"quantity": 1,
"currency": "usd",
"amount": round(int(pet[4]["hex"], 16) * 100),
}
pet_data.append(
{
"adopted_pet_slug": str(pet[1]),
"value": round(int(pet[4]["hex"], 16) * 100),
}
)
line_items.append(item)
try:
# create new checkout session for payment
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + "success?session_id={CHECKOUT_SESSION_ID}",
cancel_url=domain_url + "canceled",
payment_method_types=["card"],
mode="payment",
line_items=[
{
"name": "Sherlock Holmes",
"quantity": 1,
"currency": "usd",
"amount": round(float(5) * 100),
}
],
line_items=line_items,
)
save_transaction(
checkout_session["id"], pet_data, body["from_user"], "STRIPE"
)
return Response({"sessionId": checkout_session["id"]})
except Exception as e:
print("e ", e)
except Exception:
return Response({"message": "Please try again"})
8 changes: 1 addition & 7 deletions backend/apps/pet/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-11 21:15
# Generated by Django 5.0.1 on 2024-03-18 19:05

import colorfield.fields
import django.core.validators
Expand Down Expand Up @@ -105,12 +105,6 @@ class Migration(migrations.Migration):
"vaccinated",
models.BooleanField(default=True, verbose_name="Vaccinated"),
),
(
"pet_index",
models.IntegerField(
null=True, unique=True, verbose_name="Pet index"
),
),
(
"price_currency",
djmoney.models.fields.CurrencyField(
Expand Down
17 changes: 0 additions & 17 deletions backend/apps/pet/migrations/0002_remove_pet_pet_index.py

This file was deleted.

11 changes: 2 additions & 9 deletions backend/apps/transaction/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,15 +28,8 @@ def clean(self):
# !TransactionalAdmin
class TransactionalAdmin(admin.ModelAdmin):
form = TransactionModelForm
list_display = [
"from_user",
"confirmations",
"value",
"adopted_pet_slug",
"created",
"modified",
]
list_display_links = ["from_user", "confirmations"]
list_display = ["from_user", "value", "adopted_pet_slug", "created", "session_id"]
list_display_links = ["from_user", "session_id"]


admin.site.register(Transaction, TransactionalAdmin)
40 changes: 40 additions & 0 deletions backend/apps/transaction/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import httpx

from abstract.constants import stripe


# ? save_transaction
def save_transaction(
session_id: str, pet_data: list, from_user: str, payment_options: str
):
url = "http://127.0.0.1:8000/transactions/"
try:
for pet_data in pet_data:
response = httpx.post(
url,
json={
"from_user": from_user,
"confirmations": 1 if session_id is not None else 0,
"value": str(pet_data["value"] / 100),
"adopted_pet_slug": pet_data["adopted_pet_slug"],
"payment_options": payment_options,
"session_id": session_id,
},
)
response.raise_for_status()
if response.status_code == 201:
print("Request successful!")
print("Response:", response.json())
else:
print("Request failed with status code:", response.status_code)
except httpx.HTTPError as e:
print("HTTPError occurred:", str(e))
except Exception as e:
print("An error occurred:", str(e))


# ? get_transaction_detail
def get_transaction_detail(session_id: str):
session = stripe.checkout.Session.retrieve(session_id)
payment_intent = stripe.PaymentIntent.retrieve(session["payment_intent"])
return payment_intent["amount"] / 100
11 changes: 10 additions & 1 deletion backend/apps/transaction/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-18 12:37
# Generated by Django 5.0.1 on 2024-03-18 19:07

import django_extensions.db.fields
from django.db import migrations, models
Expand Down Expand Up @@ -45,6 +45,15 @@ class Migration(migrations.Migration):
"adopted_pet_slug",
models.CharField(max_length=100, verbose_name="adopted slug"),
),
(
"payment_options",
models.CharField(
choices=[("STRIPE", "stripe"), ("ETHEREUM", "ethereum")],
max_length=100,
null=True,
verbose_name="payment options",
),
),
],
options={
"verbose_name": "Transaction",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Generated by Django 5.0.1 on 2024-03-18 19:08

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("transaction", "0001_initial"),
]

operations = [
migrations.AlterField(
model_name="transaction",
name="adopted_pet_slug",
field=models.CharField(
db_index=True, max_length=100, unique=True, verbose_name="adopted slug"
),
),
migrations.AlterField(
model_name="transaction",
name="payment_options",
field=models.CharField(
choices=[("STRIPE", "stripe"), ("ETHEREUM", "ethereum")],
default=1,
max_length=100,
verbose_name="payment options",
),
preserve_default=False,
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
# Generated by Django 5.0.1 on 2024-03-19 16:08

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("transaction", "0002_alter_transaction_adopted_pet_slug_and_more"),
]

operations = [
migrations.RemoveField(
model_name="transaction",
name="confirmations",
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.1 on 2024-03-19 16:36

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("transaction", "0003_remove_transaction_confirmations"),
]

operations = [
migrations.AddField(
model_name="transaction",
name="confirmations",
field=models.IntegerField(null=True, verbose_name="confirmations"),
),
]
18 changes: 18 additions & 0 deletions backend/apps/transaction/migrations/0005_transaction_session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.1 on 2024-03-19 16:41

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
("transaction", "0004_transaction_confirmations"),
]

operations = [
migrations.AddField(
model_name="transaction",
name="session",
field=models.CharField(max_length=100, null=True, verbose_name="session"),
),
]
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 5.0.1 on 2024-03-19 16:41

from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("transaction", "0005_transaction_session"),
]

operations = [
migrations.RenameField(
model_name="transaction",
old_name="session",
new_name="session_id",
),
]
14 changes: 9 additions & 5 deletions backend/apps/transaction/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,21 @@
from django.utils.translation import gettext_lazy as _
from django_extensions.db.models import TimeStampedModel

from .validate_field import validate_confirmations, validate_from_user
from abstract.constants import PaymentOptions


# !Transaction
class Transaction(TimeStampedModel):
from_user = models.CharField(_("from user"), max_length=100)
confirmations = models.IntegerField(
_("confirmations"), validators=[validate_confirmations]
)
confirmations = models.IntegerField(_("confirmations"), null=True)
value = models.CharField(_("value"), max_length=100)
adopted_pet_slug = models.CharField(_("adopted slug"), max_length=100)
adopted_pet_slug = models.CharField(
_("adopted slug"), unique=True, db_index=True, max_length=100
)
payment_options = models.CharField(
_("payment options"), max_length=100, choices=PaymentOptions
)
session_id = models.CharField(_("session"), max_length=100, null=True)

class Meta:
verbose_name = "Transaction"
Expand Down
5 changes: 3 additions & 2 deletions backend/apps/transaction/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView

Expand All @@ -18,5 +19,5 @@ def post(self, request, format=None):
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)
return Response(serializer.errors, status=400)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
2 changes: 1 addition & 1 deletion backend/apps/upload/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-11 21:15
# Generated by Django 5.0.1 on 2024-03-18 19:05

from django.db import migrations, models

Expand Down
2 changes: 1 addition & 1 deletion backend/apps/user_profile/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-11 21:15
# Generated by Django 5.0.1 on 2024-03-18 19:05

import django.core.validators
import django.db.models.deletion
Expand Down
2 changes: 1 addition & 1 deletion backend/apps/users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Generated by Django 5.0.1 on 2024-03-11 21:15
# Generated by Django 5.0.1 on 2024-03-18 19:05

import django.utils.timezone
from django.db import migrations, models
Expand Down
2 changes: 1 addition & 1 deletion backend/run_migrations.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/bin/sh
APP_NAMES=("users" "user_profile" "pet" "upload")
APP_NAMES=("users" "user_profile" "pet" "upload" "order" "transaction")

for APP_NAME in "${APP_NAMES[@]}"; do
# Run makemigrations for specific apps
Expand Down
2 changes: 1 addition & 1 deletion frontend/contract-ui/contracts/PetLocal.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"abi":"[{\"type\":\"constructor\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"initialPetIndex\"}]},{\"type\":\"function\",\"name\":\"addPet\",\"constant\":false,\"payable\":false,\"inputs\":[],\"outputs\":[]},{\"type\":\"function\",\"name\":\"addToCart\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"_petId\"},{\"type\":\"string\",\"name\":\"_petName\"},{\"type\":\"string\",\"name\":\"_petColor\"},{\"type\":\"uint256\",\"name\":\"_petPrice\"},{\"type\":\"string\",\"name\":\"_petPhoto\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"adoptPet\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"adoptIdx\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"allAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPetsByOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getCartItems\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"tuple[]\",\"components\":[{\"type\":\"uint256\",\"name\":\"id\"},{\"type\":\"string\",\"name\":\"name\"},{\"type\":\"string\",\"name\":\"color\"},{\"type\":\"uint256\",\"name\":\"price\"},{\"type\":\"string\",\"name\":\"photo\"}]}]},{\"type\":\"function\",\"name\":\"getCartLength\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"getOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"owner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"ownerAddressToPetList\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"address\"},{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"petIdxToOwnerAddress\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"petIndex\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"removeCart\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"index\"}],\"outputs\":[]}]","address":"0x5FbDB2315678afecb367f032d93F642f64180aa3","network":"localhost","deployer":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"}
{"abi":"[{\"type\":\"constructor\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"initialPetIndex\"}]},{\"type\":\"function\",\"name\":\"addPet\",\"constant\":false,\"payable\":false,\"inputs\":[],\"outputs\":[]},{\"type\":\"function\",\"name\":\"addToCart\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"_petId\"},{\"type\":\"string\",\"name\":\"_petSlug\"},{\"type\":\"string\",\"name\":\"_petName\"},{\"type\":\"string\",\"name\":\"_petColor\"},{\"type\":\"uint256\",\"name\":\"_petPrice\"},{\"type\":\"string\",\"name\":\"_petPhoto\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"adoptPet\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"adoptIdx\"}],\"outputs\":[]},{\"type\":\"function\",\"name\":\"allAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPets\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getAllAdoptedPetsByOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256[]\"}]},{\"type\":\"function\",\"name\":\"getCartItems\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"tuple[]\",\"components\":[{\"type\":\"uint256\",\"name\":\"id\"},{\"type\":\"string\",\"name\":\"slug\"},{\"type\":\"string\",\"name\":\"name\"},{\"type\":\"string\",\"name\":\"color\"},{\"type\":\"uint256\",\"name\":\"price\"},{\"type\":\"string\",\"name\":\"photo\"}]}]},{\"type\":\"function\",\"name\":\"getCartLength\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"getOwner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"owner\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"ownerAddressToPetList\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"address\"},{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"petIdxToOwnerAddress\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[{\"type\":\"uint256\"}],\"outputs\":[{\"type\":\"address\"}]},{\"type\":\"function\",\"name\":\"petIndex\",\"constant\":true,\"stateMutability\":\"view\",\"payable\":false,\"inputs\":[],\"outputs\":[{\"type\":\"uint256\"}]},{\"type\":\"function\",\"name\":\"removeCart\",\"constant\":false,\"payable\":false,\"inputs\":[{\"type\":\"uint256\",\"name\":\"index\"}],\"outputs\":[]}]","address":"0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0","network":"localhost","deployer":"0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"}
Loading

0 comments on commit b29c573

Please sign in to comment.