stripe in django

 base/urls.py

 

from django.contrib import admin

from django.urls import path, include

 

from home.urls import *

 

urlpatterns = [

    path("", include("home.urls")),

    path("admin/", admin.site.urls),

]

----------------------------------------

base/settings.py

 

# custom settings

STRIPE_SECRET_KEY = "sk_test_51OHnnsSGnyUJDQBR0LGiMbHKaJL3TxetmiT2Q2lbeFwiCzNdLU00yx1DQ058"

STRIPE_PUBLISHABLE_KEY = "pk_test_51OHnnsSGnyUJDQBR3BYbdXjlwfJloYKZ27WtZ8ukp00KmyPKPpp"

PAYMENT_SUCCESS_URL =  "http://localhost:8000/success"

PAYMENT_CANCEL_URL = "http://localhost:8000/failed"

 

 

 

home/views.py

 

from django.shortcuts import render, redirect

from django.http import HttpResponse

from django.urls import reverse

import stripe

from django.conf import settings

from rest_framework.views import APIView

from rest_framework.response import Response

from rest_framework import status

 

 

def PayHome(request):

    return render(request, "pay.html")

 

 

def ProceedCheckout(request):

    if request.method == "POST":

        data = request.POST

        price = data.get("amount")

        print(price)

 

        try:

            price_in_cents = int(float(price) * 100)

        except (ValueError, TypeError):

            return HttpResponse("Invalid amount")

 

        stripe.api_key = settings.STRIPE_SECRET_KEY

        checkout_session = stripe.checkout.Session.create(

            payment_method_types=["card"],

            line_items=[

                {

                    "price_data": {

                        "currency": "inr",

                        "unit_amount": price_in_cents,

                        "product_data": {

                            "name": "subscripe app",

                            "description": "demo description",

                            "images": [

                                f"https://assets-prd.ignimgs.com/2022/06/07/f9-1654561616280.jpg"

                            ],

                            # "images": "https://assets-prd.ignimgs.com/2022/06/07/f9-1654561616280.jpg",

                        },

                    },

                    "quantity": 1,

                }

            ],

            metadata={"product_id": 122},

            mode="payment",

            success_url=settings.PAYMENT_SUCCESS_URL

            + "?session_id={CHECKOUT_SESSION_ID}",

            cancel_url=settings.PAYMENT_CANCEL_URL,

        )

 

        return redirect(checkout_session.url)

 

    else:

        return HttpResponse("bad method call")

 

 

class SuccessUrlView(APIView):

    def get(self, request):

        # Retrieve the session ID from the query parameters

        session_id = request.GET.get("session_id")

 

        if session_id:

            stripe.api_key = settings.STRIPE_SECRET_KEY

 

            # Retrieve the Checkout session

            checkout_session = stripe.checkout.Session.retrieve(session_id)

            payment_intent = checkout_session.get("payment_intent")

 

            # Use the payment ID as needed (print it, save it to the database, etc.)

            print("Payment Intent ID:", payment_intent)

 

            return Response(

                {

                    "message": "Payment done!",

                    "status": status.HTTP_201_CREATED,

                    "payment_id": payment_intent,

                },

                status=status.HTTP_201_CREATED,

            )

        else:

            return Response(

                {"message": "Invalid request", "status": status.HTTP_400_BAD_REQUEST},

                status=status.HTTP_400_BAD_REQUEST,

            )

 

 

def FailedUrl(request):

    return render(request, "fail.html")

 

----------------------------------------------------------

home/urls.py

 

from django.urls import path

from .views import *

 

urlpatterns = [

    path("",PayHome),

    path("check-out",ProceedCheckout,name="check-out"),

    path("success",SuccessUrlView.as_view()),

    path("failed",FailedUrl),

]

 

------------------------------------------------------

home/pay.html

 

<!doctype html>

<html lang="en">

  <head>

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Pay Page</title>

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">

  </head>

  <body>

   

    <br>

    <br>

 

 

    <div class="row">

        <div class="col-2"></div>

        <div class="col-8">

 

            <form method="post" action="{% url 'check-out' %}">

                {% csrf_token %}

                <div class="mb-3">

                  <label for="amount" class="form-label">Amount</label>

                  <input type="number" class="form-control" name="amount" id="amount">

                </div>

                <button type="submit" class="btn btn-primary">Submit</button>

              </form>

 

        </div>

        <div class="col-2"></div>

    </div>

 

 

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>

  </body>

</html>

 

----------------------------------------------------

Note: add you own template in success.html and fail.html

 

-------------------------------------------

requirements.txt

 

apturl==0.5.2

argcomplete==3.1.6

asgiref==3.7.2

attrs==23.1.0

awscli==1.22.34

bcrypt==3.2.0

blinker==1.4

botocore==1.23.34

Brlapi==0.8.3

certifi==2020.6.20

chardet==4.0.0

click==8.0.3

colorama==0.4.4

command-not-found==0.3

cryptography==3.4.8

cupshelpers==1.0

dbus-python==1.2.18

defer==1.0.6

distlib==0.3.7

distro==1.7.0

distro-info==1.1+ubuntu0.1

Django==4.2.7

django-filter==23.5

django-phonenumber-field==7.2.0

djangorestframework==3.14.0

djangorestframework-simplejwt==5.3.1

docutils==0.17.1

drf-spectacular==0.27.0

drf-spectacular-sidecar==2023.12.1

duplicity==0.8.21

fasteners==0.14.1

filelock==3.13.1

future==0.18.2

gyp==0.1

httplib2==0.20.2

idna==3.3

importlib-metadata==4.6.4

inflection==0.5.1

jeepney==0.7.1

jmespath==0.10.0

jsonschema==4.20.0

jsonschema-specifications==2023.11.2

keyring==23.5.0

language-selector==0.1

launchpadlib==1.10.16

lazr.restfulclient==0.14.4

lazr.uri==1.0.6

lockfile==0.12.2

louis==3.20.0

macaroonbakery==1.3.1

Mako==1.1.3

Markdown==3.5.1

MarkupSafe==2.0.1

monotonic==1.6

more-itertools==8.10.0

multidict==6.0.4

myapp==0.1.dev0

netifaces==0.11.0

oauthlib==3.2.0

olefile==0.46

paramiko==2.9.3

pexpect==4.8.0

phonenumberslite==8.13.27

Pillow==9.0.1

platformdirs==4.0.0

protobuf==3.12.4

ptyprocess==0.7.0

pyapp==4.13.1

pyasn1==0.4.8

pycairo==1.20.1

pycups==2.0.1

Pygments==2.11.2

PyGObject==3.42.1

PyJWT==2.3.0

pymacaroons==0.13.0

PyNaCl==1.5.0

pyparsing==2.4.7

pyRFC3339==1.1

python-apt==2.4.0+ubuntu2

python-dateutil==2.8.1

python-debian==0.1.43+ubuntu1.1

python-dotenv==1.0.0

pytz==2022.1

pyxdg==0.27

PyYAML==5.4.1

referencing==0.32.0

reportlab==3.6.8

requests==2.25.1

roman==3.3

rpds-py==0.15.2

rsa==4.8

s3transfer==0.5.0

SecretStorage==3.3.1

six==1.16.0

sqlparse==0.4.4

ssh-import-id==5.11

stripe==7.10.0

systemd-python==234

typing_extensions==4.8.0

ubuntu-advantage-tools==8001

ubuntu-drivers-common==0.0.0

ufw==0.36.1

unattended-upgrades==0.1

uritemplate==4.1.1

urllib3==1.26.5

usb-creator==0.3.7

virtualenv==20.24.7

wadllib==1.3.6

xdg==5

xkit==0.0.0

yarl==1.9.3

zipp==1.0.0

 

 

Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI