简体   繁体   English

在这种情况下如何编写获取 - django 应用程序付款

[英]how to write the fetch in that case - django app payment

hello I am working on a django app 'my app is about paying for someone service' client will access to the page and click on their selected person and then they will fill a form and click on get the service and then people who work in the plateform will go to another page and they can find a list of forms of people who want to get their service.... but I want the form not to be posted until the payment is done so my database will not be fall.你好,我正在开发一个 django 应用程序“我的应用程序是关于为某人服务付费”的客户将访问该页面并单击他们选择的人,然后他们将填写表格并单击获取服务然后在工作的人plateform 将 go 转到另一个页面,他们可以找到 forms 想要获得他们服务的人的列表....但我希望在付款完成之前不要发布表格,这样我的数据库就不会崩溃。 so this is my views.py I have actually 2 functions:所以这是我的 views.py 我实际上有 2 个功能:

#here where client can select people they are willing to take service from 
@login_required(login_url='login')
def pSelected(request,slug):
    profile = get_object_or_404(Profile,slug=slug)

    form = MessageForm()
    if request.method == 'POST':
        form = MessageForm(request.POST,request.user)
        form.sender = request.user.username
        form.receiver = request.POST.get('receiver', '')
        if form.is_valid():
            form.sender = request.user.username
            form.receiver = request.POST.get('receiver', '')
            messages.success(request, f'succed')
            form.save()
            print(form.sender,form.receiver)
    else:
        form = MessageForm()
    return render(request,'base/p-selected.html',context)
#here for workers in the platefrorm 
@login_required(login_url='login')
def giveService(request):
    requests = Message.objects.all().order_by('-id')

    context={'requests':requests}
    return render(request, 'base/giveService.html',context)

now in my p-selected.html现在在我的 p-selected.html

<form>
<!--I have here for example a form method post *inside of my form I have input get and payment with paypal -->

<input type="submit" value="GET" class="btn get" style="outline: none; margin:auto;"/>

<div id="paypal-button-container"></div>

</form>
<!-- Include the PayPal JavaScript SDK -->
    <script src="https://www.paypal.com/sdk/js?client-id=I-Already-Put-Here-The-Id&currency=USD"></script>

    <script>
        // Render the PayPal button into #paypal-button-container
        paypal.Buttons({

            // Call your server to set up the transaction
            createOrder: function(data, actions) {
                return fetch('/demo/checkout/api/paypal/order/create/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    return orderData.id;
                });
            },

            // Call your server to finalize the transaction
            onApprove: function(data, actions) {
                return fetch('/demo/checkout/api/paypal/order/' + data.orderID + '/capture/', {
                    method: 'post'
                }).then(function(res) {
                    return res.json();
                }).then(function(orderData) {
                    // Three cases to handle:
                    //   (1) Recoverable INSTRUMENT_DECLINED -> call actions.restart()
                    //   (2) Other non-recoverable errors -> Show a failure message
                    //   (3) Successful transaction -> Show confirmation or thank you

                    // This example reads a v2/checkout/orders capture response, propagated from the server
                    // You could use a different API or structure for your 'orderData'
                    var errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                    if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                        return actions.restart(); // Recoverable state, per:
                        // https://developer.paypal.com/docs/checkout/integration-features/funding-failure/
                    }

                    if (errorDetail) {
                        var msg = 'Sorry, your transaction could not be processed.';
                        if (errorDetail.description) msg += '\n\n' + errorDetail.description;
                        if (orderData.debug_id) msg += ' (' + orderData.debug_id + ')';
                        return alert(msg); // Show a failure message (try to avoid alerts in production environments)
                    }

                    // Successful capture! For demo purposes:
                    console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
                    var transaction = orderData.purchase_units[0].payments.captures[0];
                    alert('Transaction '+ transaction.status + ': ' + transaction.id + '\n\nSee console for all available details');

                    // Replace the above to show a success message within this page, e.g.
                    // const element = document.getElementById('paypal-button-container');
                    // element.innerHTML = '';
                    // element.innerHTML = '<h3>Thank you for your payment!</h3>';
                    // Or go to another URL:  actions.redirect('thank_you.html');
                });
            }

        }).render('#paypal-button-container');
    </script>

I want the workers in plateform to not receive the form until the payment is done by clients how I can do it in that case I already tried but I really couldn't succed many times maybe because I am not that good in js..I hope you guys can help me in that I won't forget your help thank you so much.我希望平台上的工作人员在客户完成付款之前不要收到表格,在那种情况下我该怎么做我已经尝试过但我真的无法成功很多次,也许是因为我在 js 方面不太好..我希望你们能帮助我,我不会忘记你们的帮助,非常感谢你们。

The PayPal button code in your example is for a server-side integration.您示例中的 PayPal 按钮代码用于服务器端集成。 To use it, the first thing you need to do is make two actual django routes on your server (one for create, one for capture) that call the PayPal API and return JSON data of the result.要使用它,您需要做的第一件事是在您的服务器上创建两个实际的 django 路由(一个用于创建,一个用于捕获)调用 PayPal API 并返回结果的 JSON 数据。

Next you need to change the fetch('/demo/checkout/api/paypal/order/' in the JS sample to actually point to the local paths of those working routes you made.接下来,您需要更改 JS 示例中的fetch('/demo/checkout/api/paypal/order/'以实际指向您创建的那些工作路线的本地路径。

(Alternatively, instead of doing thisroute and API work you can switch over to a client-side JS integration ... not recommended, client-side payments are for much simpler use cases than yours that don't need to trigger any server side code on success, like saving a record of the transaction or saving form data as in your case) (或者,您可以切换到客户端 JS 集成,而不是执行 thisroute 和 API 工作......不推荐,客户端支付用于比您不需要触发任何服务器端代码的更简单的用例成功时,例如保存交易记录或保存表单数据,就像您的情况一样)

Once you have a working PayPal button to simply process the payment (either server or client side), next you need to make use of your form data from the onApprove function. The simplest thing to do would be to trigger form submission with JS, however this is bad since you could receive completed payments without getting that information received and processed correctly.一旦你有了一个有效的 PayPal 按钮来简单地处理支付(服务器端或客户端),接下来你需要使用来自onApprove function 的表单数据。最简单的方法是使用 JS 触发表单提交,但是这很糟糕,因为您可能会在没有正确接收和处理该信息的情况下收到已完成的付款。

The best solution is to serialize the form data into a JSON object (using JS), and include it in the body of the fetch request to the capture order route.最好的解决方案是将表单数据序列化为 JSON object(使用 JS),并将其包含在获取订单路由的 fetch 请求的body中。 That way your capture route can validate all the form data before capturing, do the capture, and on success immediately add the transaction record and submitted form data to your django backend, right before returning that JSON response to the calling JS fetch.这样您的捕获路由可以在捕获之前验证所有表单数据,进行捕获,并在成功后立即将交易记录和提交的表单数据添加到您的 django 后端,就在将 JSON 响应返回给调用 JS 提取之前。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM