something added

This commit is contained in:
Adil Mohak 2021-04-10 21:43:18 +03:00
parent 9c16f956ec
commit 8895fc9b12
13 changed files with 458 additions and 97 deletions

View File

@ -0,0 +1,26 @@
# Generated by Django 3.1.3 on 2021-04-04 16:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Invoice',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('total', models.FloatField(blank=True, null=True)),
('amount', models.FloatField(blank=True, null=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.3 on 2021-04-04 16:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payments', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='invoice',
name='payment_complete',
field=models.BooleanField(default=False),
),
]

View File

@ -0,0 +1,18 @@
# Generated by Django 3.1.3 on 2021-04-05 05:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payments', '0002_invoice_payment_complete'),
]
operations = [
migrations.AddField(
model_name='invoice',
name='invoice_code',
field=models.CharField(blank=True, max_length=200, null=True),
),
]

View File

@ -1,3 +1,12 @@
from django.db import models
from django.contrib.auth.views import get_user_model
# Create your models here.
User = get_user_model()
class Invoice(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
total = models.FloatField(null=True, blank=True)
amount = models.FloatField(null=True, blank=True)
payment_complete = models.BooleanField(default=False)
invoice_code = models.CharField(max_length=200, blank=True, null=True)

View File

@ -0,0 +1,5 @@
<h1>Invoices</h1>
<h3>{{ invoice.user }}</h3>
<h3>{{ invoice.amount }}</h3>
<h3>{{ invoice.total }}</h3>

View File

@ -0,0 +1,13 @@
<h1>Invoices</h1>
<form method="POST">{% csrf_token %}
<input type="number" name="amount" required="true">
<button type="submit">Pay now</button>
</form>
{% for invoice in invoices %}
<h3>{{ invoice.user }}</h3>
<h3>{{ invoice.amount }}</h3>
<h3>{{ invoice.total }}</h3>
<h3>{{ invoice.payment_complete }}</h3>
{% endfor %}

View File

@ -1,9 +0,0 @@
<h2>Buy for $5.00</h2>
<form action="{% url 'charge' %}" method="post">
{% csrf_token %}
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ key }}"
data-description="A Django Charge"
data-amount="500"
data-locale="auto"></script>
</form>

View File

@ -3,6 +3,9 @@
{% load static %}
{% block header %}
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="https://use.fontawesome.com/aade6c6330.js"></script>
{% endblock %}
@ -68,14 +71,17 @@
<h1 class="display-4">Payment GateWays</h1>
<div class="row">
<div class="col-12 d-flex justify-content-center">
<form method="POST" action="{% url 'gopay_payment' %}">
{% csrf_token %}
<button name="pay" type="submit" class="btn btn-primary">Zaplatit</button>
</form>
<script type="text/javascript" src="https://gw.sandbox.gopay.com/gp-gw/js/embed.js"></script>
<div class="card-payment paypal">
<h4>Paypal</h4>
<div id="smart-button-container">
<div style="text-align: center;">
<div id="paypal-button-container"></div>
</div>
</div>
</div>
<div class="card-payment stripe">
<h4>Stripe</h4>
<form action="{% url 'charge' %}" method="POST">
@ -87,7 +93,6 @@
data-locale="auto">
</script>
</form>
<!-- <a href="{% url 'stripe' %}" class="btn"><i class="fa fa-cc-stripe" aria-hidden="true"></i> Stripe</a> -->
<p>
Make payment with stripe and get jobs done.
</p>
@ -106,10 +111,6 @@
Make payment with stripe and get jobs done.
</p>
</div>
<!-- <a href="{% url 'paypal' %}" class="btn btn-lg btn-secondary mx-3">PayPal</a>
<a href="{% url 'stripe' %}" class="btn btn-lg btn-secondary mx-3">Stripe</a>
<a href="{% url 'coinbase' %}" class="btn btn-lg btn-secondary mx-3">CoinBase</a>
<a href="{% url 'paylike' %}" class="btn btn-lg btn-secondary mx-3">Paylike</a> -->
</div>
</div>
</div>
@ -119,35 +120,85 @@
{% block js %}
<script src="https://www.paypal.com/sdk/js?client-id=sb&currency=EUR" data-sdk-integration-source="button-factory"></script>
<!-- Paypal setup -->
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=AabPcZJCP3oBL_2GTVXO58VnsyvVEzUrWORwilbX9fA5ywWdR9YSaIdu4v-nDVMIszpI1PEy9K-76jlW&currency=USD"></script>
<script>
function initPayPalButton() {
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'paypal',
// django cookie
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
const csrftoken = getCookie('csrftoken');
// approve the payment complete for the invoice
function completeOrder() {
var invoice = '{{ invoice_session }}'
var url = "{% url 'complete' %}";
fetch(url, {
method: 'POST',
headers: {
'Content-type': 'application/json',
'X-CSRFToken': csrftoken,
},
body: JSON.stringify({
'invoice': invoice
})
})
}
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{"amount":{"currency_code":"EUR","value":1}}]
purchase_units: [{
amount: {
value: '1.44'
}
}]
});
},
// style: {
// color: 'blue',
// shape: 'rect',
// label: 'pay',
// height: 40
// },
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
alert('Transaction completed by ' + details.payer.name.given_name + '!');
// Show a success message to the buyer
// call the create function
completeOrder();
window.location = "/payments/payment-succeed";
// alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
},
}
onError: function(err) {
console.log(err);
}
}).render('#paypal-button-container');
}
initPayPalButton();
</script>
{% endblock js %}

View File

@ -0,0 +1,50 @@
{% extends 'base.html' %}
{% block title %}PayPal{% endblock title %}
{% load static %}
{% block header %}
<script src="https://use.fontawesome.com/aade6c6330.js"></script>
{% endblock %}
{% block content %}
<style type="text/css">
.counter-wrapper {
background-color: #d1e5e1;
padding: 10px 20px;
}
.bg-counter {
padding: 5px 10px;
border-radius: 5px;
background-color: #aae9df;
}
</style>
<div class="container">
<center>
<h3><i class="fa fa-check-circle-o text-success" aria-hidden="true"></i> Payment Succeed, You has been make payment successfuly.</h3>
<div class="counter-wrapper">Redirect to the invoice in </span><span class="bg-counter" id="counter">8</div>
</center>
</div>
{% endblock content %}
{% block js %}
<script type="text/javascript">
var counterEl = document.getElementById('counter');
var num = parseInt(counterEl.innerText);
var invoice_code = "{{ invoice_session }}"
setInterval(counter, 1000)
function counter() {
num = num - 1;
if (num < 0) { return }
counterEl.innerText = num;
}
setTimeout(changeWindowLocation, 9000)
function changeWindowLocation() {
window.location = "/";
}
</script>
{% endblock %}

View File

@ -1,45 +1,56 @@
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Add meta tags for mobile and IE -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title> PayPal Smart Payment Buttons Integration | Client Demo </title>
</head>
<body>
<style>
.w3-container {
font-size: 14px;
}
<!-- Set up a container element for the button -->
<div id="paypal-button-container"></div>
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<!-- Include the PayPal JavaScript SDK -->
<script src="https://www.paypal.com/sdk/js?client-id=AabPcZJCP3oBL_2GTVXO58VnsyvVEzUrWORwilbX9fA5ywWdR9YSaIdu4v-nDVMIszpI1PEy9K-76jlW&currency=USD"></script>
<div class="center">
<h3 class="donate">
<div class="w3-card-4">
<script>
// Render the PayPal button into #paypal-button-container
paypal.Buttons({
<header class="w3-container w3-blue">
<h1>DONATE</h1>
</header>
// Set up the transaction
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '88.44'
}
}]
});
},
<div class="w3-container">
<p>Donate for a great cause. Be a hero.</p>
<!-- PAYPAL BUTTONS HERE -->
style: {
color: 'blue',
shape: 'pill',
label: 'pay',
height: 40
},
</div>
// Finalize the transaction
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
// Show a success message to the buyer
alert('Transaction completed by ' + details.payer.name.given_name + '!');
});
}
<footer class="w3-container w3-blue">
<h5>&copy Professional Cipher</h5>
</footer>
</div>
</h3>
</div>
}).render('#paypal-button-container');
</script>
</body>
</html>

View File

@ -1,9 +0,0 @@
{% extends 'base.html' %}
{% block title %}Thank you{% endblock title %}
{% load static %}
{% block content %}
<div class="container">
<center><h1>Thank you</h1></center>
</div>
{% endblock content %}

View File

@ -2,6 +2,7 @@ from django.urls import path
from . import views
urlpatterns = [
path('', views.PaymentGetwaysView.as_view(), name='payment_gateways'),
# path('gateways/', views.payment_gateways, name="gateways"),
path('paypal/', views.payment_paypal, name="paypal"),
@ -9,10 +10,14 @@ urlpatterns = [
path('coinbase/', views.payment_coinbase, name="coinbase"),
path('paylike/', views.payment_paylike, name="paylike"),
# path('charge/', views.charge, name="charge"),
path('thank_you/', views.thank_you, name="thank_you"),
path('create_invoice/', views.create_invoice, name="create_invoice"),
path('invoice_detail/<int:id>/', views.invoice_detail, name="invoice_detail"),
# path('charge/', views.charge, name="charge"),
path('payment-succeed/', views.payment_succeed, name="payment-succeed"),
path('charge/', views.charge, name='charge'), # new
path('', views.PaymentGetwaysView.as_view(), name='home_'),
path('complete/', views.paymentComplete, name="complete"),
path('gopay_payment/', views.gopay_payment, name="gopay_payment"),
]

View File

@ -1,6 +1,14 @@
from django.shortcuts import render
from django.conf import settings
from django.http import JsonResponse
from .models import Invoice
import stripe
import uuid
import json
stripe.api_key = settings.STRIPE_SECRET_KEY
# stripe.ApplePayDomain.create(
@ -31,8 +39,8 @@ def payment_paylike(request):
return render(request, 'payments/paylike.html', context={})
def thank_you(request):
return render(request, 'payments/thank_you.html', context={})
def payment_succeed(request):
return render(request, 'payments/payment_succeed.html', context={})
# def charge(request):
@ -48,17 +56,19 @@ def thank_you(request):
from django.shortcuts import redirect
from django.views.generic.base import TemplateView
class PaymentGetwaysView(TemplateView):
template_name = 'payments/payment_gateways.html'
def get_context_data(self, **kwargs): # new
context = super().get_context_data(**kwargs)
context = super(PaymentGetwaysView, self).get_context_data(**kwargs)
context['key'] = settings.STRIPE_PUBLISHABLE_KEY
context['amount'] = 500
context['description'] = "Stripe Payment"
context['invoice_session'] = self.request.session['invoice_session']
print(context['invoice_session'])
return context
@ -67,8 +77,171 @@ def charge(request): # new
if request.method == 'POST':
charge = stripe.Charge.create(
amount=500,
currency='usd',
currency='eur',
description='A Django charge',
source=request.POST['stripeToken']
)
return render(request, 'payments/charge.html')
invoice_code = request.session['invoice_session']
invoice = Invoice.objects.get(invoice_code=invoice_code)
invoice.payment_complete = True
invoice.save()
return redirect('completed')
# return JsonResponse({"invoice_code": invoice.invoice_code}, status=201)
# return render(request, 'payments/charge.html')
def create_invoice(request):
print(request.is_ajax())
if request.method == 'POST':
invoice = Invoice.objects.create(
user = request.user,
amount = request.POST.get('amount'),
total=26,
invoice_code=str(uuid.uuid4()),
)
request.session['invoice_session'] = invoice.invoice_code
return redirect('payment_gateways')
# if request.is_ajax():
# invoice = Invoice.objects.create(
# user = request.user,
# amount = 15,
# total=26,
# )
# return JsonResponse({'invoice': invoice}, status=201) # created
return render(request, 'invoices.html', context={
'invoices': Invoice.objects.filter(user=request.user)
})
def invoice_detail(request, slug):
return render(request, 'invoice_detail.html', context={
'invoice': Invoice.objects.get(invoice_code=slug)
})
def paymentComplete(request):
print(request.is_ajax())
if request.is_ajax() or request.method == 'POST':
invoice_id = request.session['invoice_session']
invoice = Invoice.objects.get(id=invoice_id)
invoice.payment_complete = True
invoice.save()
# return redirect('invoice', invoice.invoice_code)
body = json.loads(request.body)
print('BODY:', body)
return JsonResponse('Payment completed!', safe=False)
from django.http import JsonResponse
import gopay
from gopay.enums import Recurrence, PaymentInstrument, BankSwiftCode, Currency, Language
def gopay_payment(request):
print("\nrequest \n", request.method)
# api = gopay.payments({
# 'goid': '8302931681',
# 'clientId': '1061399163',
# 'clientSecret': 'stDTmVXF',
# 'isProductionMode': False,
# 'scope': gopay.TokenScope.ALL,
# 'language': gopay.Language.ENGLISH,
# 'timeout': 30
# })
# # token is retrieved automatically, you don't have to call some method `get_token`
# response = api.get_status('3000006542')
# if response.has_succeed():
# print("hooray, API returned " + str(response))
# else:
# print("oops, API returned " + str(response.status_code) + ": " + str(response))
# payments = gopay.payments({
# 'goid': 'my goid',
# 'clientId': 'my id',
# 'clientSecret': 'my secret',
# 'isProductionMode': False
# })
if request.method == 'POST':
user = request.user
payments = gopay.payments({
'goid': '8302931681',
'clientId': '1061399163',
'clientSecret': 'stDTmVXF',
'isProductionMode': False,
'scope': gopay.TokenScope.ALL,
'language': gopay.Language.ENGLISH,
'timeout': 30
})
# recurrent payment must have field ''
recurrentPayment = {
'recurrence': {
'recurrence_cycle': Recurrence.DAILY,
'recurrence_period': "7",
'recurrence_date_to': '2015-12-31'
}
}
# pre-authorized payment must have field 'preauthorization'
preauthorizedPayment = {
'preauthorization': True
}
response = payments.create_payment({
'payer': {
'default_payment_instrument': PaymentInstrument.BANK_ACCOUNT,
'allowed_payment_instruments': [PaymentInstrument.BANK_ACCOUNT],
'default_swift': BankSwiftCode.FIO_BANKA,
'allowed_swifts': [BankSwiftCode.FIO_BANKA, BankSwiftCode.MBANK],
'contact': {
'first_name': user.first_name,
'last_name': user.last_name,
'email': user.email,
'phone_number': user.phone,
'city': 'example city',
'street': 'Plana 67',
'postal_code': '373 01',
'country_code': 'CZE',
},
# 'contact': {
# 'first_name': 'Zbynek',
# 'last_name': 'Zak',
# 'email': 'zbynek.zak@gopay.cz',
# 'phone_number': '+420777456123',
# 'city': 'C.Budejovice',
# 'street': 'Plana 67',
# 'postal_code': '373 01',
# 'country_code': 'CZE',
# },
},
'amount': 150,
'currency': Currency.CZECH_CROWNS,
'order_number': '001',
'order_description': 'pojisteni01',
'items': [
{'name': 'item01', 'amount': 50},
{'name': 'item02', 'amount': 100},
],
'additional_params': [
{'name': 'invoicenumber', 'value': '2015001003'}
],
'callback': {
'return_url': 'http://www.your-url.tld/return',
'notification_url': 'http://www.your-url.tld/notify'
},
'lang': Language.CZECH, # if lang is not specified, then default lang is used
})
if response.has_succeed():
print("\nPayment Succeed\n")
print("hooray, API returned " + str(response))
else:
print("\nPayment Fail\n")
print("oops, API returned " + str(response.status_code) + ": " + str(response))
return JsonResponse({"message": str(response)})
return JsonResponse({"message": "GET requested"})