payment integration

This commit is contained in:
Adil Mohak 2021-04-04 16:55:40 +03:00
parent ab02887dc8
commit 9c16f956ec
26 changed files with 611 additions and 1 deletions

View File

@ -50,7 +50,10 @@ INSTALLED_APPS = [
'result.apps.ResultConfig',
'search.apps.SearchConfig',
'quiz.apps.QuizConfig',
'crispy_forms'
'payments',
'crispy_forms',
'rest_framework',
]
MIDDLEWARE = [
@ -157,3 +160,21 @@ CRISPY_TEMPLATE_PACK = 'bootstrap4'
LOGIN_REDIRECT_URL = '/'
LOGOUT_REDIRECT_URL = '/'
REST_FRAMEWORK = {
# 'DEFAULT_RENDERER_CLASSES': [
# 'rest_framework.renderers.JSONRenderer',
# ],
# 'DEFAULT_PARSER_CLASSES': [
# 'rest_framework.parsers.JSONParser',
# ]
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.IsAuthenticated',
],
'DEFAULT_AUTHENTICATION_CLASSES': [
'rest_framework.authentication.SessionAuthentication',
'rest_framework.authentication.BasicAuthentication'
]
}
STRIPE_SECRET_KEY = "sk_test_51IcEVZHbzY4cUA9T3BZdDayN4gmbJyXuaLCzpLT15HZoOmC17G7CxeEdXeIHSWyhYfxpljsclzzjsFukYNqJTbrW00tv3qIbN2"
STRIPE_PUBLISHABLE_KEY = "pk_test_51IcEVZHbzY4cUA9TrKHqyHkUQqQRRMoilwYgwSJaMjfis6rN6KZPmjcbGX6LUHpIkUV2i06JBnplberIbHtYcdfv00Tu8eMXHj"

View File

@ -15,6 +15,10 @@ urlpatterns = [
url(r'^search/', include('search.urls')),
url(r'^quiz/', include('quiz.urls')),
url(r'^payments/', include('payments.urls')),
url('accounts/api/', include('accounts.api.urls', namespace='accounts-api')),
url(r'^admin/', admin.site.urls),
]

View File

@ -0,0 +1,10 @@
from rest_framework import serializers
from django.contrib.auth.views import get_user_model
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = '__all__'

View File

@ -0,0 +1,9 @@
from . import views
from django.urls import path
app_name = "accounts-api"
urlpatterns = [
path('', views.UserListAPIView.as_view(), name="users-api"),
]

View File

@ -0,0 +1,24 @@
from rest_framework import generics
from django.contrib.auth.views import get_user_model
from .serializers import UserSerializer
User = get_user_model()
class UserListAPIView(generics.ListAPIView):
lookup_field = 'id'
serializer_class = UserSerializer
def get_queryset(self):
qs = User.objects.all()
q = self.request.GET.get('q')
if q is not None:
qs = qs.filter(username__iexact=q)
return qs
class UserDetailView(generics.RetrieveAPIView):
lookup_field = 'id'
queryset = User.objects.all()
model = User

View File

@ -0,0 +1,30 @@
# Generated by Django 3.1.3 on 2021-04-01 14:18
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0009_auto_20200906_1403'),
]
operations = [
migrations.AlterField(
model_name='parent',
name='student',
field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.SET_NULL, to='accounts.student'),
),
migrations.AlterField(
model_name='parent',
name='user',
field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
),
migrations.AlterField(
model_name='user',
name='first_name',
field=models.CharField(blank=True, max_length=150, verbose_name='first name'),
),
]

View File

@ -0,0 +1,10 @@
# from rest_framework import serializers
# from django.contrib.auth.views import get_user_model
#
# User = get_user_model()
#
#
# class UserSerializer(serializers.ModelSerializer):
# class Meta:
# model = User
# fields = '__all__'

0
payments/__init__.py Normal file
View File

3
payments/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

5
payments/apps.py Normal file
View File

@ -0,0 +1,5 @@
from django.apps import AppConfig
class PaymentsConfig(AppConfig):
name = 'payments'

View File

3
payments/models.py Normal file
View File

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

8
payments/server.py Normal file
View File

@ -0,0 +1,8 @@
# Set your secret key. Remember to switch to your live secret key in production.
# See your keys here: https://dashboard.stripe.com/account/apikeys
stripe.api_key = "sk_test_51IcEVZHbzY4cUA9T3BZdDayN4gmbJyXuaLCzpLT15HZoOmC17G7CxeEdXeIHSWyhYfxpljsclzzjsFukYNqJTbrW00tv3qIbN2"
intent = stripe.PaymentIntent.create(
amount=1099,
currency='usd',
)

View File

@ -0,0 +1,48 @@
{% 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 your dashboard 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);
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

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

View File

@ -0,0 +1,9 @@
<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

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

View File

@ -0,0 +1,153 @@
{% extends 'base.html' %}
{% block title %}Choose a gateway{% endblock title %}
{% load static %}
{% block header %}
<script src="https://use.fontawesome.com/aade6c6330.js"></script>
{% endblock %}
{% block content %}
<style type="text/css">
.card-payment {
border-top: 10px solid #ddd;
border-radius: 0px;
padding: 10px;
margin: 0;
/*background: #fff;*/
text-align: center;
width: 300px;
transition: .5s;
}
.card-payment:hover {
background: #f4f4f4;
}
.card-payment h4 {
font-weight: 200;
}
.card-payment p {
margin: 5px;
font-weight: 300;
}
.card-payment.paypal {
border-top-color: #ffc439;
/*transform: translateY(-50px);*/
}
.card-payment.stripe {
border-top-color: #62b8ea;
}
.card-payment.coinbase {
border-top-color: #1652f0;
}
.card-payment.paylike {
border-top-color: #60a65d;
}
.btn {
width: 100%;
border-radius: 1px;
padding: 10px;
color: #fff!important;
transition: .5s;
}
.btn:hover {
transform: scale(.95);
}
.btn:focus {
box-shadow: none!important;
}
.stripe .btn {
background: #6869d4;
}
.coinbase .btn {
background: #1652f0;
}
.paylike .btn {
background: #60a65d;
}
</style>
<div class="container">
<h1 class="display-4">Payment GateWays</h1>
<div class="row">
<div class="col-12 d-flex justify-content-center">
<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">
{% csrf_token %}
<script src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="{{ key }}"
data-description="{{ description }}"
data-amount="{{ amount }}"
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>
</div>
<div class="card-payment coinbase">
<h4>CoinBase</h4>
<a href="{% url 'coinbase' %}" class="btn"><span style="font-weight: 1000">C</span> CoinBase</a>
<p>
Make payment with stripe and get jobs done.
</p>
</div>
<div class="card-payment paylike">
<h4>Paylike</h4>
<a href="{% url 'paylike' %}" class="btn">Paylike</a>
<p>
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>
{% endblock content %}
{% block js %}
<script src="https://www.paypal.com/sdk/js?client-id=sb&currency=EUR" data-sdk-integration-source="button-factory"></script>
<script>
function initPayPalButton() {
paypal.Buttons({
style: {
shape: 'rect',
color: 'gold',
layout: 'vertical',
label: 'paypal',
},
createOrder: function(data, actions) {
return actions.order.create({
purchase_units: [{"amount":{"currency_code":"EUR","value":1}}]
});
},
onApprove: function(data, actions) {
return actions.order.capture().then(function(details) {
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,45 @@
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<style>
.w3-container {
font-size: 14px;
}
.center {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="center">
<h3 class="donate">
<div class="w3-card-4">
<header class="w3-container w3-blue">
<h1>DONATE</h1>
</header>
<div class="w3-container">
<p>Donate for a great cause. Be a hero.</p>
<!-- PAYPAL BUTTONS HERE -->
</div>
<footer class="w3-container w3-blue">
<h5>&copy Professional Cipher</h5>
</footer>
</div>
</h3>
</div>
</body>

View File

@ -0,0 +1,16 @@
{% extends 'base.html' %}
{% block title %}Stripe{% endblock title %}
{% load static %}
{% block header %}
<script src="https://js.stripe.com/v3/"></script>
{% endblock %}
{% block content %}
<div class="container">
<center>
<h1>Stripe</h1>
<button id="checkout-button">Checkout</button>
</center>
</div>
{% endblock content %}

View File

@ -0,0 +1,9 @@
{% 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 %}

3
payments/tests.py Normal file
View File

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

18
payments/urls.py Normal file
View File

@ -0,0 +1,18 @@
from django.urls import path
from . import views
urlpatterns = [
# path('gateways/', views.payment_gateways, name="gateways"),
path('paypal/', views.payment_paypal, name="paypal"),
path('stripe/', views.payment_stripe, name="stripe"),
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('charge/', views.charge, name='charge'), # new
path('', views.PaymentGetwaysView.as_view(), name='home_'),
]

74
payments/views.py Normal file
View File

@ -0,0 +1,74 @@
from django.shortcuts import render
from django.conf import settings
import stripe
stripe.api_key = settings.STRIPE_SECRET_KEY
# stripe.ApplePayDomain.create(
# domain_name='example.com',
# )
# def payment_gateways(request):
# print(settings.STRIPE_PUBLISHABLE_KEY)
# context = {
# 'key': settings.STRIPE_PUBLISHABLE_KEY
# }
# return render(request, 'payments/payment_gateways.html', context)
def payment_paypal(request):
return render(request, 'payments/paypal.html', context={})
def payment_stripe(request):
return render(request, 'payments/stripe.html', context={})
def payment_coinbase(request):
return render(request, 'payments/coinbase.html', context={})
def payment_paylike(request):
return render(request, 'payments/paylike.html', context={})
def thank_you(request):
return render(request, 'payments/thank_you.html', context={})
# def charge(request):
# if request.method == 'POST':
# charge = stripe.Charge.create(
# amount=500,
# currency='eur',
# description='Payment GetWays',
# source=request.POST['stripeToken']
# )
# return render(request, 'payments/charge.html')
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['key'] = settings.STRIPE_PUBLISHABLE_KEY
context['amount'] = 500
context['description'] = "Stripe Payment"
return context
def charge(request): # new
if request.method == 'POST':
charge = stripe.Charge.create(
amount=500,
currency='usd',
description='A Django charge',
source=request.POST['stripeToken']
)
return render(request, 'payments/charge.html')

88
payments/views_stripe.py Normal file
View File

@ -0,0 +1,88 @@
# #! /usr/bin/env python3.6
# """
# server.py
# Stripe Sample.
# Python 3.6 or newer required.
# """
# import stripe
# import json
# import os
# from flask import Flask, render_template, jsonify, request, send_from_directory
# from dotenv import load_dotenv, find_dotenv
# # Setup Stripe python client library
# load_dotenv(find_dotenv())
# stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
# stripe.api_version = os.getenv('STRIPE_API_VERSION')
# static_dir = str(os.path.abspath(os.path.join(__file__ , "..", os.getenv("STATIC_DIR"))))
# app = Flask(__name__, static_folder=static_dir,
# static_url_path="", template_folder=static_dir)
# @app.route('/checkout', methods=['GET'])
# def get_checkout_page():
# # Display checkout page
# return render_template('index.html')
# def calculate_order_amount(items):
# # Replace this constant with a calculation of the order's amount
# # Calculate the order total on the server to prevent
# # people from directly manipulating the amount on the client
# return 1400
# @app.route('/create-payment-intent', methods=['POST'])
# def create_payment():
# data = json.loads(request.data)
# # Create a PaymentIntent with the order amount and currency
# intent = stripe.PaymentIntent.create(
# amount=calculate_order_amount(data['items']),
# currency=data['currency']
# )
# try:
# # Send publishable key and PaymentIntent details to client
# return jsonify({'publishableKey': os.getenv('STRIPE_PUBLISHABLE_KEY'), 'clientSecret': intent.client_secret})
# except Exception as e:
# return jsonify(error=str(e)), 403
# @app.route('/webhook', methods=['POST'])
# def webhook_received():
# # You can use webhooks to receive information about asynchronous payment events.
# # For more about our webhook events check out https://stripe.com/docs/webhooks.
# webhook_secret = os.getenv('STRIPE_WEBHOOK_SECRET')
# request_data = json.loads(request.data)
# if webhook_secret:
# # Retrieve the event by verifying the signature using the raw body and secret if webhook signing is configured.
# signature = request.headers.get('stripe-signature')
# try:
# event = stripe.Webhook.construct_event(
# payload=request.data, sig_header=signature, secret=webhook_secret)
# data = event['data']
# except Exception as e:
# return e
# # Get the type of webhook event sent - used to check the status of PaymentIntents.
# event_type = event['type']
# else:
# data = request_data['data']
# event_type = request_data['type']
# data_object = data['object']
# if event_type == 'payment_intent.succeeded':
# print('💰 Payment received!')
# # Fulfill any orders, e-mail receipts, etc
# # To cancel the payment you will need to issue a Refund (https://stripe.com/docs/api/refunds)
# elif event_type == 'payment_intent.payment_failed':
# print('❌ Payment failed.')
# return jsonify({'status': 'success'})
# if __name__ == '__main__':
# app.run()

View File

@ -18,6 +18,8 @@
<!-- <link rel="stylesheet" type="text/css" href="{% static 'css/black.css' %}"> -->
<link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}">
<script src="https://js.stripe.com/v3/"></script>
{% block header %}{% endblock %}
</head>
<body>