Razorpay Django 与回调 URL 集成(CSRF 令牌丢失或不正确。)

Posted

技术标签:

【中文标题】Razorpay Django 与回调 URL 集成(CSRF 令牌丢失或不正确。)【英文标题】:Razorpay Django Integration with Callback URL (CSRF token missing or incorrect.) 【发布时间】:2021-12-21 10:37:18 【问题描述】:

我正在尝试使用 Razor Pay 进行基于类的视图,一切正常。但是当我 POST 数据太相同时,它会给出错误Forbidden (CSRF token missing or incorrect.): /buy-coin

我有两个问题

    我们如何为 post 方法免除 CSRF Token 在 Razorpay javascript 代码中,我们可以在回调 url 中添加csrf 令牌吗?

Razorpay Python 集成链接 - https://razorpay.com/docs/payment-gateway/server-integration/python/

查看.py

class BuyCoinPageView(LoginRequiredMixin, View):
    def get(self, request, *args, **kwargs):
        client = razorpay.Client(auth=("scretKey", "secretKey"))
        data =  "amount": 10000, "currency": "INR", "receipt": "order_rcptid_11" 
        payment = client.order.create(data=data)
        print('Razor Pay - ', payment['id'])
        return render(request, "pricing-page.html", 'payment': payment)
    
    def post(self, request, *args, **kwargs):
        data = request.POST
        print(data)
        return render(request, "pricing-page.html")

HTML 文件

<a href="#" id="rzp-button1" class="btn-buy">Buy Now</a>
<script src="https://checkout.razorpay.com/v1/checkout.js"></script>
<script>
var options = 
    "key": "rzp_test_hwAkAHZlKJdgee", // Enter the Key ID generated from the Dashboard
    "amount": "50000", // Amount is in currency subunits. Default currency is INR. Hence, 50000 refers to 50000 paise
    "currency": "INR",
    "name": "Acme Corp",
    "description": "Test Transaction",
    "image": "https://example.com/your_logo",
    "order_id": "payment.id", //This is a sample Order ID. Pass the `id` obtained in the response of Step 1
    "callback_url": "% url 'buy_coin' %",
    "prefill": 
        "name": "Gaurav Kumar",
        "email": "gaurav.kumar@example.com",
        "contact": "9999999999"
    ,
    "notes": 
        "address": "Razorpay Corporate Office"
    ,
    "theme": 
        "color": "#3399cc"
    
;
var rzp1 = new Razorpay(options);
document.getElementById('rzp-button1').onclick = function(e)
    rzp1.open();
    e.preventDefault();

</script>

终端日志 -

[08/Nov/2021 15:22:12] "GET /static/assets/css/style.css HTTP/1.1" 200 27172
[08/Nov/2021 15:22:12] "GET /media/exam-logos/Java-logo.jpg HTTP/1.1" 200 38915
Razor Pay -  order_IJ9ngRpV19pdEc
[08/Nov/2021 15:22:16] "GET /buy-coin HTTP/1.1" 200 8478
Forbidden (CSRF token missing or incorrect.): /buy-coin
[08/Nov/2021 15:22:37] "POST /buy-coin HTTP/1.1" 403 2519

【问题讨论】:

【参考方案1】:

为你的 call_back 写一个函数并做一个 csrf 豁免

from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def razorpay_call_back(request):
   "write your code here"

【讨论】:

以上是关于Razorpay Django 与回调 URL 集成(CSRF 令牌丢失或不正确。)的主要内容,如果未能解决你的问题,请参考以下文章

RazorPay Android 集成

Django:Hellosignup 回调 url 不来查看

如何使用 Razorpay PHP API 获取付款详情?

django安装与简介

构建请求 URL 以通过同一字段多次过滤 Django 查询集

在生成 django 管理 URL 时覆盖查询集过滤器