Skip to content

Commit

Permalink
Changed sdk ile, trying to see if this will work.
Browse files Browse the repository at this point in the history
  • Loading branch information
Preshh0 committed May 9, 2022
1 parent 5f7b94d commit f765599
Show file tree
Hide file tree
Showing 20 changed files with 221 additions and 101 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
venv
db.sqlite3
Pipfile
Pipfile*
staticfiles
Binary file modified db.sqlite3
Binary file not shown.
Binary file modified myshop/__pycache__/settings.cpython-38.pyc
Binary file not shown.
7 changes: 4 additions & 3 deletions myshop/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@
"""

import os
from lazerpay import Lazerpay
from lazerpay.resource import LazerPayClient

LAZER_PUBLIC_KEY = 'pk_test_XN33dNcIN8nOsaOc90ZYdjIn176Ix8unyqr9KRLtURL8ZgSPbo'

LAZER_SECRET_KEY = 'sk_test_vvqDUkFETASs5U7eA6awsRBd1e6pVvb0cwuecK6GNaFeVwSJb2'

lazerpay = Lazerpay(LAZER_PUBLIC_KEY, LAZER_SECRET_KEY)
lazerpay = LazerPayClient(pubKey=LAZER_PUBLIC_KEY, secretKey=LAZER_SECRET_KEY)

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
Expand Down Expand Up @@ -138,7 +138,7 @@
STATIC_URL = '/static/'

STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
os.path.join(BASE_DIR, 'shop/static'),
)

MEDIA_URL = '/media/'
Expand All @@ -150,3 +150,4 @@

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
23 changes: 23 additions & 0 deletions orders/migrations/0003_alter_order_id_alter_orderitem_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# Generated by Django 4.0.3 on 2022-05-09 12:43

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('orders', '0002_order_lazerpay_id'),
]

operations = [
migrations.AlterField(
model_name='order',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
migrations.AlterField(
model_name='orderitem',
name='id',
field=models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID'),
),
]
Binary file not shown.
Binary file modified payment/__pycache__/models.cpython-38.pyc
Binary file not shown.
Binary file modified payment/__pycache__/urls.cpython-38.pyc
Binary file not shown.
Binary file modified payment/__pycache__/views.cpython-38.pyc
Binary file not shown.
26 changes: 26 additions & 0 deletions payment/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# Generated by Django 4.0.3 on 2022-05-09 12:37

from django.db import migrations, models


class Migration(migrations.Migration):

initial = True

dependencies = [
]

operations = [
migrations.CreateModel(
name='PayWithCrypto',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=225)),
('email', models.EmailField(max_length=254)),
('amount', models.PositiveBigIntegerField()),
('currency', models.CharField(max_length=225)),
('reference', models.CharField(max_length=25)),
('successful', models.BooleanField(default=False)),
],
),
]
18 changes: 18 additions & 0 deletions payment/migrations/0002_paywithcrypto_coin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 4.0.3 on 2022-05-09 12:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('payment', '0001_initial'),
]

operations = [
migrations.AddField(
model_name='paywithcrypto',
name='coin',
field=models.CharField(default='USDC', max_length=225),
),
]
Binary file not shown.
Binary file not shown.
7 changes: 4 additions & 3 deletions payment/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ class PayWithCrypto(models.Model):
email = models.EmailField()
amount = models.PositiveBigIntegerField()
currency = models.CharField(max_length=225)
coin = models.CharField(max_length=225, default="USDC")
reference = models.CharField(max_length=25)
successful = models.BooleanField(default=False)

def save(self):
def save(self, *args, **kwargs):
while not self.reference:
reference = secrets.token_urlsafe(16)
if not PayWithCrypto.objects.filter(reference=reference).exists():
self.reference = reference

super().save()
super().save(*args, **kwargs)
105 changes: 36 additions & 69 deletions payment/services.py
Original file line number Diff line number Diff line change
@@ -1,86 +1,53 @@
from lazerpay import Lazerpay
from lazerpay.resource import LazerPayClient
from myshop.settings import *
lazerpay = Lazerpay(LAZER_PUBLIC_KEY, LAZER_SECRET_KEY)
from myshop.settings import lazerpay

'''
Initialize payment
'''
async def payment_tx(data):
transaction_payload = {
'reference': data['reference'], # Replace with a reference you generated
'customer_name': 'Njoku Emmanuel',
'customer_email': '[email protected]',
'coin': 'BUSD', # BUSD, DAI, USDC or USDT
'currency': 'USD', # NGN, AED, GBP, EUR
'amount': 100,
'accept_partial_payment': True, # By default it's false
}

response = await lazerpay.payment.initialize_payment(transaction_payload)
print(response)

'''
Confirm Payment
'''
lazerpay = LazerPayClient(pubKey=LAZER_PUBLIC_KEY, secretKey=LAZER_SECRET_KEY)

async def confirm_tx ():
transaction_payload = {
'identifier': '0xa523F92BBF59bB19FCc7020A7e9004A05B697C25',
}
response = await lazerpay.payment.confirm_payment(transaction_payload)
print(response)

'''
Create a payment link
Initialize payment
'''

async def test_create_link():
transaction_payload = {
'title': 'Njoku Test',
'description': 'Testing this sdk',
'logo':
'https://assets.audiomack.com/fireboydml/bbbd8710eff038d4f603cc39ec94a6a6c2c5b6f4100b28d62557d10d87246f27.jpeg?width=340&height=340&max=true',
'currency': 'USD',
'type': 'standard',
'amount': 100,
'redirect_url': "https://keosariel.github.io"
}

response = await lazerpay.payment_links.create_payment_link(transaction_payload)
print(response)

'''
Update a payment link
'''
async def update_paymentLink ():
transaction_payload = {
"identifier": "pq9pgb",
"status": "inactive"
}

response = await lazerpay.payment_links.update_payment_link(transaction_payload)
print(response)
try:
response = lazerpay.initTransaction(
reference="YOUR_REFERENCE", # Replace with a reference you generated
amount="10",
customer_name="Njoku Emmanuel",
customer_email="[email protected]",
coin="USDC",
currency="NGN",
accept_partial_payment=True # By default, it's false
)
except Exception as e:
raise e

'''
Get all payment links
Confirm Payment
'''
async def get_all_paymentlinks():
response = await lazerpay.payment_links.get_all_paymentlinks()
print(response)
try:
response = lazerpay.confirmPayment(
identifier="address generated or the reference generated by you from initializing payment"
)
except Exception as e:
raise e

'''
Get a single payment link
Get Accepted Coins
'''
async def get_paymentlink ():
identifier = 'pq9pgb'

response = await lazerpay.payment_links.get_paymentlink(identifier)
print(response)
try:
response = lazerpay.getAcceptedCoins()
except Exception as e:
raise e

'''
Get Accepted Coins
Payout
'''
async def get_accepted_coins ():
response = await lazerpay.misc.test_get_links()
print(response)
try:
response = lazerpay.payout(amount=1,
recipient="0x0B4d358D349809037003F96A3593ff9015E89efA",
coin="BUSD",
blockchain="Binance Smart Chain"
)
except Exception as e:
raise e
5 changes: 3 additions & 2 deletions payment/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@

urlpatterns = [
path('process/', payment_process, name='process'),
path('done/', payment_done, name='done'),
# path('done/', payment_done, name='done'),
path('canceled/', payment_canceled, name='canceled'),
path('apitest', PaymentLink.as_view())
path('apitest', PaymentLink.as_view()),
path('confirm', ConfirmPayment.as_view())
]
92 changes: 69 additions & 23 deletions payment/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,30 +6,38 @@
from django.shortcuts import render, redirect, get_object_or_404
from myshop.settings import lazerpay
from orders.models import Order
from .models import PayWithCrypto


gateway = 'uwjdksidljjzld'
# gateway = 'uwjdksidljjzld'

async def payment_process(request):
def payment_process(request):
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
total_cost = order.get_total_cost()

if request.method == 'POST':
transaction_payload = {
'reference': 'YOUR_REFERENCE', # Replace with a reference you generated
'customer_name': 'Njoku Emmanuel',
'customer_email': '[email protected]',
'coin': 'BUSD', # BUSD, DAI, USDC or USDT
'currency': 'USD', # NGN, AED, GBP, EUR
'amount': total_cost,
'accept_partial_payment': True, # By default it's false
}

result = await lazerpay.payment.initialize_payment(transaction_payload)
result = result.json()

if result['is_success']:
try:
payment_info = PayWithCrypto.objects.create(
name=request.data['name'],
email=request.data['email'],
currency=request.data['currency'],
coin=request.data['coin']
)
response = lazerpay.initTransaction(
reference=payment_info['reference'], # Replace with a reference you generated
amount=amount,
customer_name=payment_info['name'],
customer_email=payment_info['email'],
coin=payment_info['coin'],
currency=payment_info['currency'],
accept_partial_payment=True # By default, it's false
)
return Response(response, status=status.HTTP_200_OK)
except Exception as e:
return Response(e, status=status.HTTP_400_BAD_REQUEST)

if response['is_success']:
#mark the order as paid
order.paid = True

Expand All @@ -40,13 +48,51 @@ def payment_canceled(request):

class PaymentLink(APIView):
def post(self, request):
order_id = request.session.get('order_id')
order = get_object_or_404(Order, id=order_id)
amount = order.get_total_cost()

try:
response = test_create_link(request.data)
payment_info = PayWithCrypto.objects.create(
name=request.data['name'],
email=request.data['email'],
currency=request.data['currency'],
amount=request.data['amount'],
coin=request.data['coin']
)
response = lazerpay.initTransaction(
reference=payment_info['reference'], # Replace with a reference you generated
amount=payment_info['amount'],
customer_name=payment_info['name'],
customer_email=payment_info['email'],
coin=payment_info['coin'],
currency=payment_info['currency'],
accept_partial_payment=True # By default, it's false
)
return Response(response, status=status.HTTP_200_OK)
except Exception as e:
return Response(
{
'message':e
},
status=status.HTTP_400_BAD_REQUEST
)
return Response(e, status=status.HTTP_400_BAD_REQUEST)

class ConfirmPayment(APIView):
def post(self, request):
try:
response_1 = lazerpay.confirmPayment(
identifier = request.data['reference']|request.data['address']
)
if response_1:
PayWithCrypto.objects.filter(reference=request.data['reference']).update(successful=True)
return Response(
{
'message':'Payment Successful'
},
status=status.HTTP_200_OK
)
else:
return Response(
{
"message":"Payment Failed"
},
status=status.HTTP_200_OK
)
except Exception as e:
return Response(e, status=status.HTTP_400_BAD_REQUEST)
Loading

0 comments on commit f765599

Please sign in to comment.