Facebook PageView

How to setup Razorpay in python ?

Written by Parvatiandsons Team

Step 1 -> Firstly install the Razorpay user machine

pip razorpay command

 

Step 2->  Open the views.py file and create a function like this and also import the Razorpay and JSON.

 

 

from django.shortcut import HttpResponse
import json
import razorpay

def getOrderID(request, amt):
 __context = {}
 
 try:
 __context['order_Key'] = 'rzp_live_SAQqLTl1SzdQZ6'
 razorpay_client = razorpay.Client(
 auth =('rzp_live_SAQqLTl1SzdQZ6','ALm7v3J3m1D5avK3jY4OgZy6')
 )
 order = razorpay_client.order.create(dict(amount=amt, currency='INR',
 receipt = '',notes = {},payme
nt_capture ='1'))
 order['order_Key']='rzp_live_SAQqLTl1SzdQZ6'
 order['amount']=amt
 return HttpResponse(json.dumps(order), content_type='application/json')
 except Exception as error:
 print(error)
 return render(request, 'error.html', {'error': error})

 

Step 3 -> Set URL like these and import the function that you had created in step 2 

from .views import getOrderID

path('plan/pay/<int:amt>/', getOrderID, name='Planpay'),

 

Step  4 -> Create a js file and write a function like this and set the URL like your URL was created.

function fn_TestJSON(text) {
 if (typeof text == "string") {
 return false;
 }
 try {
 text = JSON.stringify(text)
 JSON.parse(text);
 return true;
 } catch (error) {
 console.log(error)
 return false;
 }
}
function fn_GetOrderdID() {
 var amt = $('#objplanprice').val()
 amt = parseFloat(amt).toFixed(2)
 amt = amt * 100
 $.ajax({
 url: "/settings/plan/pay/" + amt + "/",
 }).done(function(res) {
 if (fn_TestJSON(res)) {
 var options = {
 "key": res.order_Key,
 "amount": res.amount,
 'currency': 'INR',
 "name": 'your name / your site name ',
 "description": "You are paying to name.....",
 "image": '',
 "order_id": res.id,
 "handler": function(response) {
 response.amount = amt
 $("input[name='payment']").val(JSON.stringify(response))
 $('#frmFranchise').submit()
 },
 "prefill": {
 "name": $('#id_name').val(),
 "email": $('#id_email').val(),
 "contact": $('#id_mobile_no').val(),
 },
 "notes": {}
 };
 var rzpl = new Razorpay(options);
 rzpl.open();
 }
 });
}

 

step 5 -> Create forms.py file and write this.

from django import forms
from .models import Payment

class paymetForm(forms.ModelForm):
    

    class Meta:
        model = Payment
        fields = "__all__"
        exclude = ('is_approved', 'payment_id', 'order_id', 'code', 'payment_method',
                   'signature', 'privacy_policy', 'plan', 'amount')

    def __init__(self, *args, **kw):
        super(paymetForm, self).__init__(*args, **kw)
      

 

 

Step 6 -> Open views.py file and firstly create a funtuion and import json for the Save the payment form data or create forms 

 

 import json

def franchiseregistation(request,id):
 __context = {}

 try:
 objplan = Plan.objects.get(pk=id)
 if request.method == 'POST':
 payment = request.POST['payment']
 payment = json.loads(payment)
 print(payment)

 form = FranchiseForm(request.POST, request.FILES)
 if form.is_valid():
 start_date = datetime.now()
 end_date = start_date + timedelta(days=365)
 obj=form.save(commit=False)
 obj.code = max_code()
 obj.payment_id= payment['razorpay_payment_id']
 obj.order_id= payment['razorpay_order_id']
 obj.signature= payment['razorpay_signature']
 obj.amount= (int(payment['amount'])/100)
 obj.plan = objplan
 obj.pried_from = start_date
 obj.pried_to = end_date
 obj.save()
 Wallet.objects.create(amount=0,franchise=obj)
 messages.add_message(request, messages.SUCCESS, 'Thanks your Form
has been Submitted!')

 else:
 messages.add_message(request, messages.ERROR, 'Form Validation Er
ror!')
 else:
 form = FranchiseForm()
 __context['plan_id']=id
 __context['plan'] = objplan
 __context['form'] = form
 return render(request, 'websites/payment.html',__context)
 except Exception as error:
 print(error)
 return render(request, 'error.html', {'error': error})

step 7 ->  Create paymet.html page and create form for payment save.

 

<section class="space-ptb">
 <div class="container">
 <div class="row justify-content-center">
 <div class="col-md-8 text-center">
 <div class="section-title">
 <h2>Franchise Registration</h2>
 <p>If success is a process with a number of defined steps, th
en it is just like any other process. So, what is the first step in any process?<
/p>
 </div>
 </div>
 </div>
 <div>
 <div>
 {% if messages %} {% for message in messages %} {% if message.lev
el == DEFAULT_MESSAGE_LEVELS.ERROR %}
 <div class="alert alert-danger" role="alert">
 {{message}}
 </div> {% endif %} {% if message.level == DEFAULT_MESSAGE_LEVELS.
SUCCESS %}
 <div class="alert alert-success" role="alert">
 {{message}}
 </div> {% endif %}{% endfor %}{% endif %}
 <br>
 <form class="" id="frmFranchise" method="POST" action="{% url
'websites:franchiseregistation' plan_id %}" enctype="multipart/form-data">
 {% csrf_token %} {% for hidden_field in form.hidden_fields %}
{{ hidden_field.errors }} {{ hidden_field }} {% endfor %} {% if form.non_field_e
rrors %}
 <div class="alert alert-danger" role="alert">
 {% for error in form.non_field_errors %} {{ error }} {% e
ndfor %}
 </div>
 {% endif %}
 <div class="row">{% for field in form.visible_fields %}
 <div class="col-md-4 form-group">
 <label for="" {%if field.field.required%} class="req
" {%else%} class="nreq" {%endif%}>{{ field.label }} </label> {% if form.is_bound
%} {% if field.errors %} {% render_field field class="form-control isinvalid" placeholder=field.label
 %} {% for error in field.errors %}
 <div class="invalid-feedback">
 {{ error }}
 </div>
{% endfor %} {% else %} {% render_field field class="
form-
control" rows=2 placeholder=field.label %} {% endif %} {% else %} {% render_field
field class="form-control" rows=2 %} {% endif %}
 </div>
{% endfor %}
 </div>
 <input type="hidden" name="payment">
 <div class="form-group col-sm-12">
 <button type="button" onclick="fn_GetOrderdID()" id="t
blpay" class="btn btn-primary">pay</button>
 <button type="submit" id="btnSubmit" class="btn btnprimary">Submit</button>
 </div>
 </form>
 </div>
 </div>
 </div>
 </div>
</section>
<input type="hidden" id="objplanprice" value="{{plan.price}}">

 

  • How to add onchange event in django-python